blob: 75755ece76f1dac1a824a1de814885fc137f99c9 [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 Dunbardbc93372008-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.
1359static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001360 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001361 return true;
1362 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1363 return hasObjCExceptionAttribute(Super);
1364 return false;
1365}
1366
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001367/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001368
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001369CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1370 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001371{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001372 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001373 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001374}
1375
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001376/// GetClass - Return a reference to the class for the given interface
1377/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001378llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001379 const ObjCInterfaceDecl *ID) {
1380 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001381}
1382
1383/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001384llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001385 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001386}
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001387llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1388 *Method) {
1389 return EmitSelector(Builder, Method->getSelector());
1390}
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001391
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001392/// Generate a constant CFString object.
1393/*
1394 struct __builtin_CFString {
1395 const int *isa; // point to __CFConstantStringClassReference
1396 int flags;
1397 const char *str;
1398 long length;
1399 };
1400*/
1401
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001402llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001403 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001404 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001405}
1406
1407/// Generates a message send where the super is the receiver. This is
1408/// a message send to self with special delivery semantics indicating
1409/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001410CodeGen::RValue
1411CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001412 QualType ResultType,
1413 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001414 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001415 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001416 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001417 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001418 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001419 // Create and init a super structure; this is a (receiver, class)
1420 // pair we will pass to objc_msgSendSuper.
1421 llvm::Value *ObjCSuper =
1422 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1423 llvm::Value *ReceiverAsObject =
1424 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1425 CGF.Builder.CreateStore(ReceiverAsObject,
1426 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001427
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001428 // If this is a class message the metaclass is passed as the target.
1429 llvm::Value *Target;
1430 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001431 if (isCategoryImpl) {
1432 // Message sent to 'super' in a class method defined in a category
1433 // implementation requires an odd treatment.
1434 // If we are in a class method, we must retrieve the
1435 // _metaclass_ for the current class, pointed at by
1436 // the class's "isa" pointer. The following assumes that
1437 // isa" is the first ivar in a class (which it must be).
1438 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1439 Target = CGF.Builder.CreateStructGEP(Target, 0);
1440 Target = CGF.Builder.CreateLoad(Target);
1441 }
1442 else {
1443 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1444 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1445 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1446 Target = Super;
1447 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001448 } else {
1449 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1450 }
Mike Stumpf5408fe2009-05-16 07:57:57 +00001451 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1452 // ObjCTypes types.
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001453 const llvm::Type *ClassTy =
1454 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001455 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001456 CGF.Builder.CreateStore(Target,
1457 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001458 return EmitLegacyMessageSend(CGF, ResultType,
1459 EmitSelector(CGF.Builder, Sel),
1460 ObjCSuper, ObjCTypes.SuperPtrCTy,
1461 true, CallArgs, ObjCTypes);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001462}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001463
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001464/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001465CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001466 QualType ResultType,
1467 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001468 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001469 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001470 const CallArgList &CallArgs,
1471 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001472 return EmitLegacyMessageSend(CGF, ResultType,
1473 EmitSelector(CGF.Builder, Sel),
1474 Receiver, CGF.getContext().getObjCIdType(),
1475 false, CallArgs, ObjCTypes);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001476}
1477
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001478CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1479 CodeGen::CodeGenFunction &CGF,
1480 QualType ResultType,
1481 llvm::Value *Sel,
1482 llvm::Value *Arg0,
1483 QualType Arg0Ty,
1484 bool IsSuper,
1485 const CallArgList &CallArgs,
1486 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001487 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001488 if (!IsSuper)
1489 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001490 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001491 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001492 CGF.getContext().getObjCSelType()));
1493 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001494
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001495 CodeGenTypes &Types = CGM.getTypes();
1496 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001497 // In 64bit ABI, type must be assumed VARARG. In 32bit abi,
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001498 // it seems not to matter.
1499 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1500
1501 llvm::Constant *Fn = NULL;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001502 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001503 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1504 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001505 } else if (ResultType->isFloatingType()) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001506 if (ObjCABI == 2) {
1507 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1508 BuiltinType::Kind k = BT->getKind();
1509 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1510 : ObjCTypes.getSendFn2(IsSuper);
1511 }
1512 }
1513 else
Mike Stumpf5408fe2009-05-16 07:57:57 +00001514 // FIXME. This currently matches gcc's API for x86-32. May need to change
1515 // for others if we have their API.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001516 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001517 } else {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001518 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1519 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001520 }
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001521 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001522 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001523 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001524}
1525
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001526llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001527 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001528 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001529 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001530 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1531
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001532 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1533 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001534}
1535
Fariborz Jahanianda320092009-01-29 19:24:30 +00001536void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001537 // FIXME: We shouldn't need this, the protocol decl should contain enough
1538 // information to tell us whether this was a declaration or a definition.
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001539 DefinedProtocols.insert(PD->getIdentifier());
1540
1541 // If we have generated a forward reference to this protocol, emit
1542 // it now. Otherwise do nothing, the protocol objects are lazily
1543 // emitted.
1544 if (Protocols.count(PD->getIdentifier()))
1545 GetOrEmitProtocol(PD);
1546}
1547
Fariborz Jahanianda320092009-01-29 19:24:30 +00001548llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001549 if (DefinedProtocols.count(PD->getIdentifier()))
1550 return GetOrEmitProtocol(PD);
1551 return GetOrEmitProtocolRef(PD);
1552}
1553
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001554/*
1555 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1556 struct _objc_protocol {
1557 struct _objc_protocol_extension *isa;
1558 char *protocol_name;
1559 struct _objc_protocol_list *protocol_list;
1560 struct _objc__method_prototype_list *instance_methods;
1561 struct _objc__method_prototype_list *class_methods
1562 };
1563
1564 See EmitProtocolExtension().
1565*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001566llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1567 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1568
1569 // Early exit if a defining object has already been generated.
1570 if (Entry && Entry->hasInitializer())
1571 return Entry;
1572
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001573 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001574 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001575 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1576
Chris Lattner8ec03f52008-11-24 03:54:41 +00001577 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001578
1579 // Construct method lists.
1580 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1581 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001582 for (ObjCProtocolDecl::instmeth_iterator
1583 i = PD->instmeth_begin(CGM.getContext()),
1584 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001585 ObjCMethodDecl *MD = *i;
1586 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1587 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1588 OptInstanceMethods.push_back(C);
1589 } else {
1590 InstanceMethods.push_back(C);
1591 }
1592 }
1593
Douglas Gregor6ab35242009-04-09 21:40:53 +00001594 for (ObjCProtocolDecl::classmeth_iterator
1595 i = PD->classmeth_begin(CGM.getContext()),
1596 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001597 ObjCMethodDecl *MD = *i;
1598 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1599 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1600 OptClassMethods.push_back(C);
1601 } else {
1602 ClassMethods.push_back(C);
1603 }
1604 }
1605
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001606 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001607 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001608 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001609 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001610 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001611 PD->protocol_begin(),
1612 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001613 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001614 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1615 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001616 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1617 InstanceMethods);
1618 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001619 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1620 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001621 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1622 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001623 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1624 Values);
1625
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001626 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001627 // Already created, fix the linkage and update the initializer.
1628 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001629 Entry->setInitializer(Init);
1630 } else {
1631 Entry =
1632 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1633 llvm::GlobalValue::InternalLinkage,
1634 Init,
1635 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1636 &CGM.getModule());
1637 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001638 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001639 UsedGlobals.push_back(Entry);
1640 // FIXME: Is this necessary? Why only for protocol?
1641 Entry->setAlignment(4);
1642 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001643
1644 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001645}
1646
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001647llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001648 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1649
1650 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001651 // We use the initializer as a marker of whether this is a forward
1652 // reference or not. At module finalization we add the empty
1653 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001654 Entry =
1655 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001656 llvm::GlobalValue::ExternalLinkage,
1657 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001658 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001659 &CGM.getModule());
1660 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001661 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001662 UsedGlobals.push_back(Entry);
1663 // FIXME: Is this necessary? Why only for protocol?
1664 Entry->setAlignment(4);
1665 }
1666
1667 return Entry;
1668}
1669
1670/*
1671 struct _objc_protocol_extension {
1672 uint32_t size;
1673 struct objc_method_description_list *optional_instance_methods;
1674 struct objc_method_description_list *optional_class_methods;
1675 struct objc_property_list *instance_properties;
1676 };
1677*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001678llvm::Constant *
1679CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1680 const ConstantVector &OptInstanceMethods,
1681 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001682 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001683 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001684 std::vector<llvm::Constant*> Values(4);
1685 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001686 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001687 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1688 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001689 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1690 OptInstanceMethods);
1691 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001692 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1693 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001694 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1695 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001696 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1697 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001698 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001699
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001700 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001701 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1702 Values[3]->isNullValue())
1703 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1704
1705 llvm::Constant *Init =
1706 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001707
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001708 // No special section, but goes in llvm.used
1709 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1710 Init,
1711 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001712}
1713
1714/*
1715 struct objc_protocol_list {
1716 struct objc_protocol_list *next;
1717 long count;
1718 Protocol *list[];
1719 };
1720*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001721llvm::Constant *
1722CGObjCMac::EmitProtocolList(const std::string &Name,
1723 ObjCProtocolDecl::protocol_iterator begin,
1724 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001725 std::vector<llvm::Constant*> ProtocolRefs;
1726
Daniel Dunbardbc93372008-08-21 21:57:41 +00001727 for (; begin != end; ++begin)
1728 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001729
1730 // Just return null for empty protocol lists
1731 if (ProtocolRefs.empty())
1732 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1733
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001734 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001735 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1736
1737 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001738 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001739 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1740 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1741 Values[2] =
1742 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1743 ProtocolRefs.size()),
1744 ProtocolRefs);
1745
1746 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1747 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001748 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001749 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001750 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1751}
1752
1753/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001754 struct _objc_property {
1755 const char * const name;
1756 const char * const attributes;
1757 };
1758
1759 struct _objc_property_list {
1760 uint32_t entsize; // sizeof (struct _objc_property)
1761 uint32_t prop_count;
1762 struct _objc_property[prop_count];
1763 };
1764*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001765llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1766 const Decl *Container,
1767 const ObjCContainerDecl *OCD,
1768 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001769 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001770 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1771 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001772 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001773 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001774 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001775 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1776 Prop));
1777 }
1778
1779 // Return null for empty list.
1780 if (Properties.empty())
1781 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1782
1783 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001784 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001785 std::vector<llvm::Constant*> Values(3);
1786 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1787 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1788 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1789 Properties.size());
1790 Values[2] = llvm::ConstantArray::get(AT, Properties);
1791 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1792
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001793 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001794 CreateMetadataVar(Name, Init,
1795 (ObjCABI == 2) ? "__DATA, __objc_const" :
1796 "__OBJC,__property,regular,no_dead_strip",
1797 (ObjCABI == 2) ? 8 : 4,
1798 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001799 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001800}
1801
1802/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001803 struct objc_method_description_list {
1804 int count;
1805 struct objc_method_description list[];
1806 };
1807*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001808llvm::Constant *
1809CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1810 std::vector<llvm::Constant*> Desc(2);
1811 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1812 ObjCTypes.SelectorPtrTy);
1813 Desc[1] = GetMethodVarType(MD);
1814 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1815 Desc);
1816}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001817
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001818llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1819 const char *Section,
1820 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001821 // Return null for empty list.
1822 if (Methods.empty())
1823 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1824
1825 std::vector<llvm::Constant*> Values(2);
1826 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1827 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1828 Methods.size());
1829 Values[1] = llvm::ConstantArray::get(AT, Methods);
1830 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1831
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001832 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001833 return llvm::ConstantExpr::getBitCast(GV,
1834 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001835}
1836
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001837/*
1838 struct _objc_category {
1839 char *category_name;
1840 char *class_name;
1841 struct _objc_method_list *instance_methods;
1842 struct _objc_method_list *class_methods;
1843 struct _objc_protocol_list *protocols;
1844 uint32_t size; // <rdar://4585769>
1845 struct _objc_property_list *instance_properties;
1846 };
1847 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001848void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001849 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001850
Mike Stumpf5408fe2009-05-16 07:57:57 +00001851 // FIXME: This is poor design, the OCD should have a pointer to the category
1852 // decl. Additionally, note that Category can be null for the @implementation
1853 // w/o an @interface case. Sema should just create one for us as it does for
1854 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001855 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001856 const ObjCCategoryDecl *Category =
1857 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001858 std::string ExtName(Interface->getNameAsString() + "_" +
1859 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001860
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001861 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001862 for (ObjCCategoryImplDecl::instmeth_iterator
1863 i = OCD->instmeth_begin(CGM.getContext()),
1864 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001865 // Instance methods should always be defined.
1866 InstanceMethods.push_back(GetMethodConstant(*i));
1867 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001868 for (ObjCCategoryImplDecl::classmeth_iterator
1869 i = OCD->classmeth_begin(CGM.getContext()),
1870 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001871 // Class methods should always be defined.
1872 ClassMethods.push_back(GetMethodConstant(*i));
1873 }
1874
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001875 std::vector<llvm::Constant*> Values(7);
1876 Values[0] = GetClassName(OCD->getIdentifier());
1877 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001878 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001879 Values[2] =
1880 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1881 ExtName,
1882 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001883 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001884 Values[3] =
1885 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001886 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001887 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001888 if (Category) {
1889 Values[4] =
1890 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1891 Category->protocol_begin(),
1892 Category->protocol_end());
1893 } else {
1894 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1895 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001896 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001897
1898 // If there is no category @interface then there can be no properties.
1899 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001900 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001901 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001902 } else {
1903 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1904 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001905
1906 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1907 Values);
1908
1909 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001910 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1911 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001912 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001913 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001914}
1915
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001916// FIXME: Get from somewhere?
1917enum ClassFlags {
1918 eClassFlags_Factory = 0x00001,
1919 eClassFlags_Meta = 0x00002,
1920 // <rdr://5142207>
1921 eClassFlags_HasCXXStructors = 0x02000,
1922 eClassFlags_Hidden = 0x20000,
1923 eClassFlags_ABI2_Hidden = 0x00010,
1924 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1925};
1926
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001927/*
1928 struct _objc_class {
1929 Class isa;
1930 Class super_class;
1931 const char *name;
1932 long version;
1933 long info;
1934 long instance_size;
1935 struct _objc_ivar_list *ivars;
1936 struct _objc_method_list *methods;
1937 struct _objc_cache *cache;
1938 struct _objc_protocol_list *protocols;
1939 // Objective-C 1.0 extensions (<rdr://4585769>)
1940 const char *ivar_layout;
1941 struct _objc_class_ext *ext;
1942 };
1943
1944 See EmitClassExtension();
1945 */
1946void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001947 DefinedSymbols.insert(ID->getIdentifier());
1948
Chris Lattner8ec03f52008-11-24 03:54:41 +00001949 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001950 // FIXME: Gross
1951 ObjCInterfaceDecl *Interface =
1952 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001953 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001954 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001955 Interface->protocol_begin(),
1956 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001957 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001958 unsigned Size =
1959 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001960
1961 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001962 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001963 Flags |= eClassFlags_Hidden;
1964
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001965 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001966 for (ObjCImplementationDecl::instmeth_iterator
1967 i = ID->instmeth_begin(CGM.getContext()),
1968 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001969 // Instance methods should always be defined.
1970 InstanceMethods.push_back(GetMethodConstant(*i));
1971 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001972 for (ObjCImplementationDecl::classmeth_iterator
1973 i = ID->classmeth_begin(CGM.getContext()),
1974 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001975 // Class methods should always be defined.
1976 ClassMethods.push_back(GetMethodConstant(*i));
1977 }
1978
Douglas Gregor653f1b12009-04-23 01:02:12 +00001979 for (ObjCImplementationDecl::propimpl_iterator
1980 i = ID->propimpl_begin(CGM.getContext()),
1981 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001982 ObjCPropertyImplDecl *PID = *i;
1983
1984 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1985 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1986
1987 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1988 if (llvm::Constant *C = GetMethodConstant(MD))
1989 InstanceMethods.push_back(C);
1990 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1991 if (llvm::Constant *C = GetMethodConstant(MD))
1992 InstanceMethods.push_back(C);
1993 }
1994 }
1995
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001996 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00001997 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001998 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001999 // Record a reference to the super class.
2000 LazySymbols.insert(Super->getIdentifier());
2001
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002002 Values[ 1] =
2003 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2004 ObjCTypes.ClassPtrTy);
2005 } else {
2006 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2007 }
2008 Values[ 2] = GetClassName(ID->getIdentifier());
2009 // Version is always 0.
2010 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2011 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2012 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002013 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002014 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002015 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002016 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002017 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002018 // cache is always NULL.
2019 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2020 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002021 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002022 Values[11] = EmitClassExtension(ID);
2023 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2024 Values);
2025
2026 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002027 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2028 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002029 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002030 DefinedClasses.push_back(GV);
2031}
2032
2033llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2034 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002035 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002036 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002037 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002038
Daniel Dunbar04d40782009-04-14 06:00:08 +00002039 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002040 Flags |= eClassFlags_Hidden;
2041
2042 std::vector<llvm::Constant*> Values(12);
2043 // The isa for the metaclass is the root of the hierarchy.
2044 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2045 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2046 Root = Super;
2047 Values[ 0] =
2048 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2049 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002050 // The super class for the metaclass is emitted as the name of the
2051 // super class. The runtime fixes this up to point to the
2052 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002053 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2054 Values[ 1] =
2055 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2056 ObjCTypes.ClassPtrTy);
2057 } else {
2058 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2059 }
2060 Values[ 2] = GetClassName(ID->getIdentifier());
2061 // Version is always 0.
2062 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2063 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2064 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002065 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002066 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002067 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002068 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002069 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002070 // cache is always NULL.
2071 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2072 Values[ 9] = Protocols;
2073 // ivar_layout for metaclass is always NULL.
2074 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2075 // The class extension is always unused for metaclasses.
2076 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2077 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2078 Values);
2079
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002080 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002081 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002082
2083 // Check for a forward reference.
2084 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2085 if (GV) {
2086 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2087 "Forward metaclass reference has incorrect type.");
2088 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2089 GV->setInitializer(Init);
2090 } else {
2091 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2092 llvm::GlobalValue::InternalLinkage,
2093 Init, Name,
2094 &CGM.getModule());
2095 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002096 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002097 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002098 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002099
2100 return GV;
2101}
2102
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002103llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002104 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002105
Mike Stumpf5408fe2009-05-16 07:57:57 +00002106 // FIXME: Should we look these up somewhere other than the module. Its a bit
2107 // silly since we only generate these while processing an implementation, so
2108 // exactly one pointer would work if know when we entered/exitted an
2109 // implementation block.
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002110
2111 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002112 // Previously, metaclass with internal linkage may have been defined.
2113 // pass 'true' as 2nd argument so it is returned.
2114 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002115 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2116 "Forward metaclass reference has incorrect type.");
2117 return GV;
2118 } else {
2119 // Generate as an external reference to keep a consistent
2120 // module. This will be patched up when we emit the metaclass.
2121 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2122 llvm::GlobalValue::ExternalLinkage,
2123 0,
2124 Name,
2125 &CGM.getModule());
2126 }
2127}
2128
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002129/*
2130 struct objc_class_ext {
2131 uint32_t size;
2132 const char *weak_ivar_layout;
2133 struct _objc_property_list *properties;
2134 };
2135*/
2136llvm::Constant *
2137CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2138 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002139 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002140
2141 std::vector<llvm::Constant*> Values(3);
2142 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002143 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002144 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002145 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002146
2147 // Return null if no extension bits are used.
2148 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2149 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2150
2151 llvm::Constant *Init =
2152 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002153 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002154 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2155 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002156}
2157
2158/*
2159 struct objc_ivar {
2160 char *ivar_name;
2161 char *ivar_type;
2162 int ivar_offset;
2163 };
2164
2165 struct objc_ivar_list {
2166 int ivar_count;
2167 struct objc_ivar list[count];
2168 };
2169 */
2170llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002171 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002172 std::vector<llvm::Constant*> Ivars, Ivar(3);
2173
2174 // When emitting the root class GCC emits ivar entries for the
2175 // actual class structure. It is not clear if we need to follow this
2176 // behavior; for now lets try and get away with not doing it. If so,
2177 // the cleanest solution would be to make up an ObjCInterfaceDecl
2178 // for the class.
2179 if (ForClass)
2180 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002181
2182 ObjCInterfaceDecl *OID =
2183 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002184
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002185 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002186 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002187
2188 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2189 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002190 // Ignore unnamed bit-fields.
2191 if (!IVD->getDeclName())
2192 continue;
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002193 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2194 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002195 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002196 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002197 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002198 }
2199
2200 // Return null for empty list.
2201 if (Ivars.empty())
2202 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2203
2204 std::vector<llvm::Constant*> Values(2);
2205 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2206 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2207 Ivars.size());
2208 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2209 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2210
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002211 llvm::GlobalVariable *GV;
2212 if (ForClass)
2213 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002214 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2215 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002216 else
2217 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2218 + ID->getNameAsString(),
2219 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002220 4, true);
2221 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002222}
2223
2224/*
2225 struct objc_method {
2226 SEL method_name;
2227 char *method_types;
2228 void *method;
2229 };
2230
2231 struct objc_method_list {
2232 struct objc_method_list *obsolete;
2233 int count;
2234 struct objc_method methods_list[count];
2235 };
2236*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002237
2238/// GetMethodConstant - Return a struct objc_method constant for the
2239/// given method if it has been defined. The result is null if the
2240/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002241llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002242 // FIXME: Use DenseMap::lookup
2243 llvm::Function *Fn = MethodDefinitions[MD];
2244 if (!Fn)
2245 return 0;
2246
2247 std::vector<llvm::Constant*> Method(3);
2248 Method[0] =
2249 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2250 ObjCTypes.SelectorPtrTy);
2251 Method[1] = GetMethodVarType(MD);
2252 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2253 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2254}
2255
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002256llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2257 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002258 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002259 // Return null for empty list.
2260 if (Methods.empty())
2261 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2262
2263 std::vector<llvm::Constant*> Values(3);
2264 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2265 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2266 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2267 Methods.size());
2268 Values[2] = llvm::ConstantArray::get(AT, Methods);
2269 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2270
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002271 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002272 return llvm::ConstantExpr::getBitCast(GV,
2273 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002274}
2275
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002276llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002277 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002278 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002279 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002280
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002281 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002282 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002283 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002284 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002285 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002286 llvm::GlobalValue::InternalLinkage,
2287 Name,
2288 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002289 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002290
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002291 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002292}
2293
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002294llvm::GlobalVariable *
2295CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2296 llvm::Constant *Init,
2297 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002298 unsigned Align,
2299 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002300 const llvm::Type *Ty = Init->getType();
2301 llvm::GlobalVariable *GV =
2302 new llvm::GlobalVariable(Ty, false,
2303 llvm::GlobalValue::InternalLinkage,
2304 Init,
2305 Name,
2306 &CGM.getModule());
2307 if (Section)
2308 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002309 if (Align)
2310 GV->setAlignment(Align);
2311 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002312 UsedGlobals.push_back(GV);
2313 return GV;
2314}
2315
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002316llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002317 // Abuse this interface function as a place to finalize.
2318 FinishModule();
2319
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002320 return NULL;
2321}
2322
Chris Lattner74391b42009-03-22 21:03:39 +00002323llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002324 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002325}
2326
Chris Lattner74391b42009-03-22 21:03:39 +00002327llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002328 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002329}
2330
Chris Lattner74391b42009-03-22 21:03:39 +00002331llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002332 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002333}
2334
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002335/*
2336
2337Objective-C setjmp-longjmp (sjlj) Exception Handling
2338--
2339
2340The basic framework for a @try-catch-finally is as follows:
2341{
2342 objc_exception_data d;
2343 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002344 bool _call_try_exit = true;
2345
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002346 objc_exception_try_enter(&d);
2347 if (!setjmp(d.jmp_buf)) {
2348 ... try body ...
2349 } else {
2350 // exception path
2351 id _caught = objc_exception_extract(&d);
2352
2353 // enter new try scope for handlers
2354 if (!setjmp(d.jmp_buf)) {
2355 ... match exception and execute catch blocks ...
2356
2357 // fell off end, rethrow.
2358 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002359 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002360 } else {
2361 // exception in catch block
2362 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002363 _call_try_exit = false;
2364 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002365 }
2366 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002367 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002368
2369finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002370 if (_call_try_exit)
2371 objc_exception_try_exit(&d);
2372
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002373 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002374 ... dispatch to finally destination ...
2375
2376finally_rethrow:
2377 objc_exception_throw(_rethrow);
2378
2379finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002380}
2381
2382This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002383uses _rethrow to determine if objc_exception_try_exit should be called
2384and if the object should be rethrown. This breaks in the face of
2385throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002386
2387We specialize this framework for a few particular circumstances:
2388
2389 - If there are no catch blocks, then we avoid emitting the second
2390 exception handling context.
2391
2392 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2393 e)) we avoid emitting the code to rethrow an uncaught exception.
2394
2395 - FIXME: If there is no @finally block we can do a few more
2396 simplifications.
2397
2398Rethrows and Jumps-Through-Finally
2399--
2400
2401Support for implicit rethrows and jumping through the finally block is
2402handled by storing the current exception-handling context in
2403ObjCEHStack.
2404
Daniel Dunbar898d5082008-09-30 01:06:03 +00002405In order to implement proper @finally semantics, we support one basic
2406mechanism for jumping through the finally block to an arbitrary
2407destination. Constructs which generate exits from a @try or @catch
2408block use this mechanism to implement the proper semantics by chaining
2409jumps, as necessary.
2410
2411This mechanism works like the one used for indirect goto: we
2412arbitrarily assign an ID to each destination and store the ID for the
2413destination in a variable prior to entering the finally block. At the
2414end of the finally block we simply create a switch to the proper
2415destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002416
2417Code gen for @synchronized(expr) stmt;
2418Effectively generating code for:
2419objc_sync_enter(expr);
2420@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002421*/
2422
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002423void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2424 const Stmt &S) {
2425 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002426 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002427 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002428 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002429 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2430 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2431 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002432
2433 // For @synchronized, call objc_sync_enter(sync.expr). The
2434 // evaluation of the expression must occur before we enter the
2435 // @synchronized. We can safely avoid a temp here because jumps into
2436 // @synchronized are illegal & this will dominate uses.
2437 llvm::Value *SyncArg = 0;
2438 if (!isTry) {
2439 SyncArg =
2440 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2441 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002442 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002443 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002444
2445 // Push an EH context entry, used for handling rethrows and jumps
2446 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002447 CGF.PushCleanupBlock(FinallyBlock);
2448
Anders Carlsson273558f2009-02-07 21:37:21 +00002449 CGF.ObjCEHValueStack.push_back(0);
2450
Daniel Dunbar898d5082008-09-30 01:06:03 +00002451 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002452 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2453 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002454 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2455 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002456 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2457 "_call_try_exit");
2458 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2459
Anders Carlsson80f25672008-09-09 17:59:25 +00002460 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002461 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002462 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2463 "jmpbufarray");
2464 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002465 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002466 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002467
Daniel Dunbar55e87422008-11-11 02:29:29 +00002468 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2469 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002470 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002471 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002472
2473 // Emit the @try block.
2474 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002475 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2476 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002477 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002478
2479 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002480 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002481
2482 // Retrieve the exception object. We may emit multiple blocks but
2483 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002484 llvm::Value *Caught =
2485 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2486 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002487 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002488 if (!isTry)
2489 {
2490 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002491 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002492 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002493 }
2494 else if (const ObjCAtCatchStmt* CatchStmt =
2495 cast<ObjCAtTryStmt>(S).getCatchStmts())
2496 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002497 // Enter a new exception try block (in case a @catch block throws
2498 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002499 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002500
Chris Lattner34b02a12009-04-22 02:26:14 +00002501 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002502 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002503 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002504
Daniel Dunbar55e87422008-11-11 02:29:29 +00002505 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2506 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002507 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002508
2509 CGF.EmitBlock(CatchBlock);
2510
Daniel Dunbar55e40722008-09-27 07:03:52 +00002511 // Handle catch list. As a special case we check if everything is
2512 // matched and avoid generating code for falling off the end if
2513 // so.
2514 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002515 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002516 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002517
Steve Naroff7ba138a2009-03-03 19:52:17 +00002518 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002519 const PointerType *PT = 0;
2520
Anders Carlsson80f25672008-09-09 17:59:25 +00002521 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002522 if (!CatchParam) {
2523 AllMatched = true;
2524 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002525 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002526
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002527 // catch(id e) always matches.
2528 // FIXME: For the time being we also match id<X>; this should
2529 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002530 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002531 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002532 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002533 }
2534
Daniel Dunbar55e40722008-09-27 07:03:52 +00002535 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002536 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002537 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002538 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002539 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002540 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002541
Anders Carlssondde0a942008-09-11 09:15:33 +00002542 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002543 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002544 break;
2545 }
2546
Daniel Dunbar129271a2008-09-27 07:36:24 +00002547 assert(PT && "Unexpected non-pointer type in @catch");
2548 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002549 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002550 assert(ObjCType && "Catch parameter must have Objective-C type!");
2551
2552 // Check if the @catch block matches the exception object.
2553 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2554
Chris Lattner34b02a12009-04-22 02:26:14 +00002555 llvm::Value *Match =
2556 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2557 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002558
Daniel Dunbar55e87422008-11-11 02:29:29 +00002559 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002560
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002561 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002562 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002563
2564 // Emit the @catch block.
2565 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002566 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002567 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002568
2569 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002570 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002571 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002572 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002573
2574 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002575 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002576
2577 CGF.EmitBlock(NextCatchBlock);
2578 }
2579
Daniel Dunbar55e40722008-09-27 07:03:52 +00002580 if (!AllMatched) {
2581 // None of the handlers caught the exception, so store it to be
2582 // rethrown at the end of the @finally block.
2583 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002584 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002585 }
2586
2587 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002588 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002589 CGF.Builder.CreateStore(
2590 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2591 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002592 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002593 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002594 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002595 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002596 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002597 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002598 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002599 }
2600
Daniel Dunbar898d5082008-09-30 01:06:03 +00002601 // Pop the exception-handling stack entry. It is important to do
2602 // this now, because the code in the @finally block is not in this
2603 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002604 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2605
Anders Carlsson273558f2009-02-07 21:37:21 +00002606 CGF.ObjCEHValueStack.pop_back();
2607
Anders Carlsson80f25672008-09-09 17:59:25 +00002608 // Emit the @finally block.
2609 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002610 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2611
2612 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2613
2614 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002615 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002616
2617 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002618 if (isTry) {
2619 if (const ObjCAtFinallyStmt* FinallyStmt =
2620 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2621 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002622 } else {
2623 // Emit objc_sync_exit(expr); as finally's sole statement for
2624 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002625 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002626 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002627
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002628 // Emit the switch block
2629 if (Info.SwitchBlock)
2630 CGF.EmitBlock(Info.SwitchBlock);
2631 if (Info.EndBlock)
2632 CGF.EmitBlock(Info.EndBlock);
2633
Daniel Dunbar898d5082008-09-30 01:06:03 +00002634 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002635 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002636 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002637 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002638
2639 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002640}
2641
2642void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002643 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002644 llvm::Value *ExceptionAsObject;
2645
2646 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2647 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2648 ExceptionAsObject =
2649 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2650 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002651 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002652 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002653 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002654 }
2655
Chris Lattnerbbccd612009-04-22 02:38:11 +00002656 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002657 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002658
2659 // Clear the insertion point to indicate we are in unreachable code.
2660 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002661}
2662
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002663/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002664/// object: objc_read_weak (id *src)
2665///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002666llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002667 llvm::Value *AddrWeakObj)
2668{
Eli Friedman8339b352009-03-07 03:57:15 +00002669 const llvm::Type* DestTy =
2670 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002671 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002672 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002673 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002674 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002675 return read_weak;
2676}
2677
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002678/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2679/// objc_assign_weak (id src, id *dst)
2680///
2681void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2682 llvm::Value *src, llvm::Value *dst)
2683{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002684 const llvm::Type * SrcTy = src->getType();
2685 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002686 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002687 assert(Size <= 8 && "does not support size > 8");
2688 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2689 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002690 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2691 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002692 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2693 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002694 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002695 src, dst, "weakassign");
2696 return;
2697}
2698
Fariborz Jahanian58626502008-11-19 00:59:10 +00002699/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2700/// objc_assign_global (id src, id *dst)
2701///
2702void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2703 llvm::Value *src, llvm::Value *dst)
2704{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002705 const llvm::Type * SrcTy = src->getType();
2706 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002707 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002708 assert(Size <= 8 && "does not support size > 8");
2709 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2710 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002711 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2712 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002713 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2714 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002715 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002716 src, dst, "globalassign");
2717 return;
2718}
2719
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002720/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2721/// objc_assign_ivar (id src, id *dst)
2722///
2723void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2724 llvm::Value *src, llvm::Value *dst)
2725{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002726 const llvm::Type * SrcTy = src->getType();
2727 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002728 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002729 assert(Size <= 8 && "does not support size > 8");
2730 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2731 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002732 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2733 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002734 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2735 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002736 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002737 src, dst, "assignivar");
2738 return;
2739}
2740
Fariborz Jahanian58626502008-11-19 00:59:10 +00002741/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2742/// objc_assign_strongCast (id src, id *dst)
2743///
2744void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2745 llvm::Value *src, llvm::Value *dst)
2746{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002747 const llvm::Type * SrcTy = src->getType();
2748 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002749 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002750 assert(Size <= 8 && "does not support size > 8");
2751 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2752 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002753 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2754 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002755 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2756 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002757 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002758 src, dst, "weakassign");
2759 return;
2760}
2761
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002762/// EmitObjCValueForIvar - Code Gen for ivar reference.
2763///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002764LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2765 QualType ObjectTy,
2766 llvm::Value *BaseValue,
2767 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002768 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002769 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002770 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2771 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002772}
2773
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002774llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002775 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002776 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002777 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002778 return llvm::ConstantInt::get(
2779 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2780 Offset);
2781}
2782
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002783/* *** Private Interface *** */
2784
2785/// EmitImageInfo - Emit the image info marker used to encode some module
2786/// level information.
2787///
2788/// See: <rdr://4810609&4810587&4810587>
2789/// struct IMAGE_INFO {
2790/// unsigned version;
2791/// unsigned flags;
2792/// };
2793enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002794 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2795 // this implies.
2796 eImageInfo_GarbageCollected = (1 << 1),
2797 eImageInfo_GCOnly = (1 << 2),
2798 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2799
2800 // A flag indicating that the module has no instances of an
2801 // @synthesize of a superclass variable. <rdar://problem/6803242>
2802 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002803};
2804
2805void CGObjCMac::EmitImageInfo() {
2806 unsigned version = 0; // Version is unused?
2807 unsigned flags = 0;
2808
2809 // FIXME: Fix and continue?
2810 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2811 flags |= eImageInfo_GarbageCollected;
2812 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2813 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002814
2815 // We never allow @synthesize of a superclass property.
2816 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002817
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002818 // Emitted as int[2];
2819 llvm::Constant *values[2] = {
2820 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2821 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2822 };
2823 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002824
2825 const char *Section;
2826 if (ObjCABI == 1)
2827 Section = "__OBJC, __image_info,regular";
2828 else
2829 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002830 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002831 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2832 llvm::ConstantArray::get(AT, values, 2),
2833 Section,
2834 0,
2835 true);
2836 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002837}
2838
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002839
2840// struct objc_module {
2841// unsigned long version;
2842// unsigned long size;
2843// const char *name;
2844// Symtab symtab;
2845// };
2846
2847// FIXME: Get from somewhere
2848static const int ModuleVersion = 7;
2849
2850void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002851 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002852
2853 std::vector<llvm::Constant*> Values(4);
2854 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2855 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002856 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002857 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002858 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002859 CreateMetadataVar("\01L_OBJC_MODULES",
2860 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2861 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002862 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002863}
2864
2865llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002866 unsigned NumClasses = DefinedClasses.size();
2867 unsigned NumCategories = DefinedCategories.size();
2868
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002869 // Return null if no symbols were defined.
2870 if (!NumClasses && !NumCategories)
2871 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2872
2873 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002874 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2875 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2876 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2877 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2878
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002879 // The runtime expects exactly the list of defined classes followed
2880 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002881 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002882 for (unsigned i=0; i<NumClasses; i++)
2883 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2884 ObjCTypes.Int8PtrTy);
2885 for (unsigned i=0; i<NumCategories; i++)
2886 Symbols[NumClasses + i] =
2887 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2888 ObjCTypes.Int8PtrTy);
2889
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002890 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002891 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002892 NumClasses + NumCategories),
2893 Symbols);
2894
2895 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2896
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002897 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002898 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2899 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002900 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002901 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2902}
2903
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002904llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002905 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002906 LazySymbols.insert(ID->getIdentifier());
2907
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002908 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2909
2910 if (!Entry) {
2911 llvm::Constant *Casted =
2912 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2913 ObjCTypes.ClassPtrTy);
2914 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002915 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2916 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002917 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002918 }
2919
2920 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002921}
2922
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002923llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002924 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2925
2926 if (!Entry) {
2927 llvm::Constant *Casted =
2928 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2929 ObjCTypes.SelectorPtrTy);
2930 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002931 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2932 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002933 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002934 }
2935
2936 return Builder.CreateLoad(Entry, false, "tmp");
2937}
2938
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002939llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002940 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002941
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002942 if (!Entry)
2943 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2944 llvm::ConstantArray::get(Ident->getName()),
2945 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002946 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002947
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002948 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002949}
2950
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002951/// GetIvarLayoutName - Returns a unique constant for the given
2952/// ivar layout bitmap.
2953llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2954 const ObjCCommonTypesHelper &ObjCTypes) {
2955 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2956}
2957
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002958static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2959 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002960 if (FQT.isObjCGCStrong())
2961 return QualType::Strong;
2962
2963 if (FQT.isObjCGCWeak())
2964 return QualType::Weak;
2965
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002966 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002967 return QualType::Strong;
2968
2969 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002970 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002971
2972 return QualType::GCNone;
2973}
2974
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002975void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2976 unsigned int BytePos,
2977 bool ForStrongLayout,
2978 bool &HasUnion) {
2979 const RecordDecl *RD = RT->getDecl();
2980 // FIXME - Use iterator.
2981 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2982 RD->field_end(CGM.getContext()));
2983 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2984 const llvm::StructLayout *RecLayout =
2985 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2986
2987 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2988 ForStrongLayout, HasUnion);
2989}
2990
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002991void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002992 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002993 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002994 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002995 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002996 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002997 bool IsUnion = (RD && RD->isUnion());
2998 uint64_t MaxUnionIvarSize = 0;
2999 uint64_t MaxSkippedUnionIvarSize = 0;
3000 FieldDecl *MaxField = 0;
3001 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003002 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003003 uint64_t MaxFieldOffset = 0;
3004 uint64_t MaxSkippedFieldOffset = 0;
3005 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003006
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003007 if (RecFields.empty())
3008 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003009 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3010 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3011
Chris Lattnerf1690852009-03-31 08:48:01 +00003012 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003013 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003014 uint64_t FieldOffset;
3015 if (RD)
3016 FieldOffset =
3017 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3018 else
3019 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003020
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003021 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003022 if (!Field->getIdentifier() || Field->isBitField()) {
3023 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003024 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003025 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003026 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003027
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003028 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003029 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003030 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003031 if (FQT->isUnionType())
3032 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003033
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003034 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003035 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003036 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003037 continue;
3038 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003039
3040 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003041 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003042 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003043 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003044 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003045 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003046 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3047 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003048 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003049 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003050 FQT = CArray->getElementType();
3051 }
3052
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003053 assert(!FQT->isUnionType() &&
3054 "layout for array of unions not supported");
3055 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003056 int OldIndex = IvarsInfo.size() - 1;
3057 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003058
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003059 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003060 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003061 ForStrongLayout, HasUnion);
3062
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003063 // Replicate layout information for each array element. Note that
3064 // one element is already done.
3065 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003066 for (int FirstIndex = IvarsInfo.size() - 1,
3067 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003068 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003069 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3070 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3071 IvarsInfo[i].ivar_size));
3072 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3073 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3074 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003075 }
3076 continue;
3077 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003078 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003079 // At this point, we are done with Record/Union and array there of.
3080 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003081 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003082
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003083 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003084 if ((ForStrongLayout && GCAttr == QualType::Strong)
3085 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003086 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003087 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003088 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003089 MaxUnionIvarSize = UnionIvarSize;
3090 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003091 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003092 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003093 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003094 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003095 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003096 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003097 } else if ((ForStrongLayout &&
3098 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3099 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3100 if (IsUnion) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00003101 // FIXME: Why the asymmetry? We divide by word size in bits on other
3102 // side.
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003103 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003104 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003105 MaxSkippedUnionIvarSize = UnionIvarSize;
3106 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003107 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003108 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003109 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003110 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003111 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003112 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003113 }
3114 }
3115 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003116
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003117 if (LastFieldBitfield) {
3118 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003119 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3120 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003121 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003122 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003123 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003124 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3125 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003126 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003127 }
3128
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003129 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003130 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003131 MaxUnionIvarSize));
3132 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003133 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003134 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003135}
3136
3137/// BuildIvarLayout - Builds ivar layout bitmap for the class
3138/// implementation for the __strong or __weak case.
3139/// The layout map displays which words in ivar list must be skipped
3140/// and which must be scanned by GC (see below). String is built of bytes.
3141/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3142/// of words to skip and right nibble is count of words to scan. So, each
3143/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3144/// represented by a 0x00 byte which also ends the string.
3145/// 1. when ForStrongLayout is true, following ivars are scanned:
3146/// - id, Class
3147/// - object *
3148/// - __strong anything
3149///
3150/// 2. When ForStrongLayout is false, following ivars are scanned:
3151/// - __weak anything
3152///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003153llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003154 const ObjCImplementationDecl *OMD,
3155 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003156 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003157
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003158 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003159 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3160 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3161 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003162
Chris Lattnerf1690852009-03-31 08:48:01 +00003163 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003164 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003165 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003166
Daniel Dunbar37153282009-05-04 04:10:48 +00003167 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003168 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3169 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3170 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3171 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3172
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003173 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003174 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003175
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003176 SkipIvars.clear();
3177 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003178
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003179 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003180 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003181 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003182
3183 // Sort on byte position in case we encounterred a union nested in
3184 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003185 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003186 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003187 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003188 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003189
3190 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003191 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003192 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003193 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003194 if (IvarsInfo[0].ivar_bytepos == 0) {
3195 WordsToSkip = 0;
3196 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003197 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003198 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3199 WordsToScan = IvarsInfo[0].ivar_size;
3200 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003201 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003202 unsigned int TailPrevGCObjC =
3203 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003204 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003205 // consecutive 'scanned' object pointers.
3206 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003207 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 // Skip over 'gc'able object pointer which lay over each other.
3209 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3210 continue;
3211 // Must skip over 1 or more words. We save current skip/scan values
3212 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003213 SKIP_SCAN SkScan;
3214 SkScan.skip = WordsToSkip;
3215 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003216 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003217
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003218 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003219 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3220 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003221 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003222 WordsToSkip = 0;
3223 WordsToScan = IvarsInfo[i].ivar_size;
3224 }
3225 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003226 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003227 SKIP_SCAN SkScan;
3228 SkScan.skip = WordsToSkip;
3229 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003230 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003231 }
3232
3233 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003234 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003235 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003236 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003237 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3238 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003239 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003240 IvarsInfo[LastIndex].ivar_bytepos +
3241 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003242 BytesSkipped = (LastByteSkipped > LastByteScanned);
3243 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003244 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003245 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003246 SKIP_SCAN SkScan;
3247 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3248 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003249 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003250 }
3251 }
3252 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3253 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003254 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003255 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003256 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3257 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3258 // 0xM0 followed by 0x0N detected.
3259 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3260 for (int j = i+1; j < SkipScan; j++)
3261 SkipScanIvars[j] = SkipScanIvars[j+1];
3262 --SkipScan;
3263 }
3264 }
3265
3266 // Generate the string.
3267 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003268 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003269 unsigned char byte;
3270 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3271 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3272 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3273 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3274
3275 if (skip_small > 0 || skip_big > 0)
3276 BytesSkipped = true;
3277 // first skip big.
3278 for (unsigned int ix = 0; ix < skip_big; ix++)
3279 BitMap += (unsigned char)(0xf0);
3280
3281 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003282 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003283 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003284 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003285 byte |= 0xf;
3286 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003287 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003288 byte |= scan_small;
3289 scan_small = 0;
3290 }
3291 BitMap += byte;
3292 }
3293 // next scan big
3294 for (unsigned int ix = 0; ix < scan_big; ix++)
3295 BitMap += (unsigned char)(0x0f);
3296 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003297 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003298 byte = scan_small;
3299 BitMap += byte;
3300 }
3301 }
3302 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003303 unsigned char zero = 0;
3304 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003305
3306 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3307 printf("\n%s ivar layout for class '%s': ",
3308 ForStrongLayout ? "strong" : "weak",
3309 OMD->getClassInterface()->getNameAsCString());
3310 const unsigned char *s = (unsigned char*)BitMap.c_str();
3311 for (unsigned i = 0; i < BitMap.size(); i++)
3312 if (!(s[i] & 0xf0))
3313 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3314 else
3315 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3316 printf("\n");
3317 }
3318
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003319 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3320 // final layout.
3321 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003322 return llvm::Constant::getNullValue(PtrTy);
3323 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3324 llvm::ConstantArray::get(BitMap.c_str()),
3325 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003326 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003327 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003328}
3329
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003330llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003331 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3332
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003333 // FIXME: Avoid std::string copying.
3334 if (!Entry)
3335 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3336 llvm::ConstantArray::get(Sel.getAsString()),
3337 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003338 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003339
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003340 return getConstantGEP(Entry, 0, 0);
3341}
3342
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003343// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003344llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003345 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3346}
3347
3348// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003349llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003350 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3351}
3352
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003353llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003354 std::string TypeStr;
3355 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3356
3357 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003358
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003359 if (!Entry)
3360 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3361 llvm::ConstantArray::get(TypeStr),
3362 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003363 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003364
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003365 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003366}
3367
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003368llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003369 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003370 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3371 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003372
3373 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3374
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003375 if (!Entry)
3376 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3377 llvm::ConstantArray::get(TypeStr),
3378 "__TEXT,__cstring,cstring_literals",
3379 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003380
3381 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003382}
3383
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003384// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003385llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003386 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3387
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003388 if (!Entry)
3389 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3390 llvm::ConstantArray::get(Ident->getName()),
3391 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003392 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003393
3394 return getConstantGEP(Entry, 0, 0);
3395}
3396
3397// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003398// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003399llvm::Constant *
3400 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3401 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003402 std::string TypeStr;
3403 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003404 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3405}
3406
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003407void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3408 const ObjCContainerDecl *CD,
3409 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003410 NameOut = '\01';
3411 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003412 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003413 assert (CD && "Missing container decl in GetNameForMethod");
3414 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003415 if (const ObjCCategoryImplDecl *CID =
3416 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3417 NameOut += '(';
3418 NameOut += CID->getNameAsString();
3419 NameOut+= ')';
3420 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003421 NameOut += ' ';
3422 NameOut += D->getSelector().getAsString();
3423 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003424}
3425
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003426void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003427 EmitModuleInfo();
3428
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003429 // Emit the dummy bodies for any protocols which were referenced but
3430 // never defined.
3431 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3432 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3433 if (i->second->hasInitializer())
3434 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003435
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003436 std::vector<llvm::Constant*> Values(5);
3437 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3438 Values[1] = GetClassName(i->first);
3439 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3440 Values[3] = Values[4] =
3441 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3442 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3443 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3444 Values));
3445 }
3446
3447 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003448 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003449 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003450 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003451 }
3452
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003453 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003454 llvm::GlobalValue *GV =
3455 new llvm::GlobalVariable(AT, false,
3456 llvm::GlobalValue::AppendingLinkage,
3457 llvm::ConstantArray::get(AT, Used),
3458 "llvm.used",
3459 &CGM.getModule());
3460
3461 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003462
3463 // Add assembler directives to add lazy undefined symbol references
3464 // for classes which are referenced but not defined. This is
3465 // important for correct linker interaction.
3466
3467 // FIXME: Uh, this isn't particularly portable.
3468 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003469
3470 if (!CGM.getModule().getModuleInlineAsm().empty())
3471 s << "\n";
3472
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003473 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3474 e = LazySymbols.end(); i != e; ++i) {
3475 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3476 }
3477 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3478 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003479 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003480 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3481 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003482
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003483 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003484}
3485
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003486CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003487 : CGObjCCommonMac(cgm),
3488 ObjCTypes(cgm)
3489{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003490 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003491 ObjCABI = 2;
3492}
3493
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003494/* *** */
3495
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003496ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3497: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003498{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003499 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3500 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003501
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003502 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003503 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003504 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003505 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003506 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3507
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003508 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003509 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003510 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003511
Mike Stumpf5408fe2009-05-16 07:57:57 +00003512 // FIXME: It would be nice to unify this with the opaque type, so that the IR
3513 // comes out a bit cleaner.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003514 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3515 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003516
3517 // I'm not sure I like this. The implicit coordination is a bit
3518 // gross. We should solve this in a reasonable fashion because this
3519 // is a pretty common task (match some runtime data structure with
3520 // an LLVM data structure).
3521
3522 // FIXME: This is leaked.
3523 // FIXME: Merge with rewriter code?
3524
3525 // struct _objc_super {
3526 // id self;
3527 // Class cls;
3528 // }
3529 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3530 SourceLocation(),
3531 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003532 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3533 Ctx.getObjCIdType(), 0, false));
3534 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3535 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003536 RD->completeDefinition(Ctx);
3537
3538 SuperCTy = Ctx.getTagDeclType(RD);
3539 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3540
3541 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003542 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3543
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003544 // struct _prop_t {
3545 // char *name;
3546 // char *attributes;
3547 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003548 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003549 CGM.getModule().addTypeName("struct._prop_t",
3550 PropertyTy);
3551
3552 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003553 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003554 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003555 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003556 // }
3557 PropertyListTy = llvm::StructType::get(IntTy,
3558 IntTy,
3559 llvm::ArrayType::get(PropertyTy, 0),
3560 NULL);
3561 CGM.getModule().addTypeName("struct._prop_list_t",
3562 PropertyListTy);
3563 // struct _prop_list_t *
3564 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3565
3566 // struct _objc_method {
3567 // SEL _cmd;
3568 // char *method_type;
3569 // char *_imp;
3570 // }
3571 MethodTy = llvm::StructType::get(SelectorPtrTy,
3572 Int8PtrTy,
3573 Int8PtrTy,
3574 NULL);
3575 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003576
3577 // struct _objc_cache *
3578 CacheTy = llvm::OpaqueType::get();
3579 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3580 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003581}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003582
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003583ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3584 : ObjCCommonTypesHelper(cgm)
3585{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003586 // struct _objc_method_description {
3587 // SEL name;
3588 // char *types;
3589 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003590 MethodDescriptionTy =
3591 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003592 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003593 NULL);
3594 CGM.getModule().addTypeName("struct._objc_method_description",
3595 MethodDescriptionTy);
3596
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003597 // struct _objc_method_description_list {
3598 // int count;
3599 // struct _objc_method_description[1];
3600 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003601 MethodDescriptionListTy =
3602 llvm::StructType::get(IntTy,
3603 llvm::ArrayType::get(MethodDescriptionTy, 0),
3604 NULL);
3605 CGM.getModule().addTypeName("struct._objc_method_description_list",
3606 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003607
3608 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003609 MethodDescriptionListPtrTy =
3610 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3611
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003612 // Protocol description structures
3613
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003614 // struct _objc_protocol_extension {
3615 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3616 // struct _objc_method_description_list *optional_instance_methods;
3617 // struct _objc_method_description_list *optional_class_methods;
3618 // struct _objc_property_list *instance_properties;
3619 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003620 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003621 llvm::StructType::get(IntTy,
3622 MethodDescriptionListPtrTy,
3623 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003624 PropertyListPtrTy,
3625 NULL);
3626 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3627 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003628
3629 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003630 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3631
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003632 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003633
3634 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3635 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3636
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003637 const llvm::Type *T =
3638 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3639 LongTy,
3640 llvm::ArrayType::get(ProtocolTyHolder, 0),
3641 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003642 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3643
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003644 // struct _objc_protocol {
3645 // struct _objc_protocol_extension *isa;
3646 // char *protocol_name;
3647 // struct _objc_protocol **_objc_protocol_list;
3648 // struct _objc_method_description_list *instance_methods;
3649 // struct _objc_method_description_list *class_methods;
3650 // }
3651 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003652 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003653 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3654 MethodDescriptionListPtrTy,
3655 MethodDescriptionListPtrTy,
3656 NULL);
3657 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3658
3659 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3660 CGM.getModule().addTypeName("struct._objc_protocol_list",
3661 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003662 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003663 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3664
3665 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003666 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003667 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003668
3669 // Class description structures
3670
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003671 // struct _objc_ivar {
3672 // char *ivar_name;
3673 // char *ivar_type;
3674 // int ivar_offset;
3675 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003676 IvarTy = llvm::StructType::get(Int8PtrTy,
3677 Int8PtrTy,
3678 IntTy,
3679 NULL);
3680 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3681
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003682 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003683 IvarListTy = llvm::OpaqueType::get();
3684 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3685 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3686
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003687 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003688 MethodListTy = llvm::OpaqueType::get();
3689 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3690 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3691
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003692 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003693 ClassExtensionTy =
3694 llvm::StructType::get(IntTy,
3695 Int8PtrTy,
3696 PropertyListPtrTy,
3697 NULL);
3698 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3699 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3700
3701 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3702
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003703 // struct _objc_class {
3704 // Class isa;
3705 // Class super_class;
3706 // char *name;
3707 // long version;
3708 // long info;
3709 // long instance_size;
3710 // struct _objc_ivar_list *ivars;
3711 // struct _objc_method_list *methods;
3712 // struct _objc_cache *cache;
3713 // struct _objc_protocol_list *protocols;
3714 // char *ivar_layout;
3715 // struct _objc_class_ext *ext;
3716 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003717 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3718 llvm::PointerType::getUnqual(ClassTyHolder),
3719 Int8PtrTy,
3720 LongTy,
3721 LongTy,
3722 LongTy,
3723 IvarListPtrTy,
3724 MethodListPtrTy,
3725 CachePtrTy,
3726 ProtocolListPtrTy,
3727 Int8PtrTy,
3728 ClassExtensionPtrTy,
3729 NULL);
3730 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3731
3732 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3733 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3734 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3735
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003736 // struct _objc_category {
3737 // char *category_name;
3738 // char *class_name;
3739 // struct _objc_method_list *instance_method;
3740 // struct _objc_method_list *class_method;
3741 // uint32_t size; // sizeof(struct _objc_category)
3742 // struct _objc_property_list *instance_properties;// category's @property
3743 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003744 CategoryTy = llvm::StructType::get(Int8PtrTy,
3745 Int8PtrTy,
3746 MethodListPtrTy,
3747 MethodListPtrTy,
3748 ProtocolListPtrTy,
3749 IntTy,
3750 PropertyListPtrTy,
3751 NULL);
3752 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3753
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003754 // Global metadata structures
3755
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003756 // struct _objc_symtab {
3757 // long sel_ref_cnt;
3758 // SEL *refs;
3759 // short cls_def_cnt;
3760 // short cat_def_cnt;
3761 // char *defs[cls_def_cnt + cat_def_cnt];
3762 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003763 SymtabTy = llvm::StructType::get(LongTy,
3764 SelectorPtrTy,
3765 ShortTy,
3766 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003767 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003768 NULL);
3769 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3770 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3771
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003772 // struct _objc_module {
3773 // long version;
3774 // long size; // sizeof(struct _objc_module)
3775 // char *name;
3776 // struct _objc_symtab* symtab;
3777 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003778 ModuleTy =
3779 llvm::StructType::get(LongTy,
3780 LongTy,
3781 Int8PtrTy,
3782 SymtabPtrTy,
3783 NULL);
3784 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003785
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003786
Mike Stumpf5408fe2009-05-16 07:57:57 +00003787 // FIXME: This is the size of the setjmp buffer and should be target
3788 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson124526b2008-09-09 10:10:21 +00003789 uint64_t SetJmpBufferSize = 18;
3790
3791 // Exceptions
3792 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003793 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003794
3795 ExceptionDataTy =
3796 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3797 SetJmpBufferSize),
3798 StackPtrTy, NULL);
3799 CGM.getModule().addTypeName("struct._objc_exception_data",
3800 ExceptionDataTy);
3801
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003802}
3803
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003804ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003805: ObjCCommonTypesHelper(cgm)
3806{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003807 // struct _method_list_t {
3808 // uint32_t entsize; // sizeof(struct _objc_method)
3809 // uint32_t method_count;
3810 // struct _objc_method method_list[method_count];
3811 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003812 MethodListnfABITy = llvm::StructType::get(IntTy,
3813 IntTy,
3814 llvm::ArrayType::get(MethodTy, 0),
3815 NULL);
3816 CGM.getModule().addTypeName("struct.__method_list_t",
3817 MethodListnfABITy);
3818 // struct method_list_t *
3819 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003820
3821 // struct _protocol_t {
3822 // id isa; // NULL
3823 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003824 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003825 // const struct method_list_t * const instance_methods;
3826 // const struct method_list_t * const class_methods;
3827 // const struct method_list_t *optionalInstanceMethods;
3828 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003829 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003830 // const uint32_t size; // sizeof(struct _protocol_t)
3831 // const uint32_t flags; // = 0
3832 // }
3833
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003834 // Holder for struct _protocol_list_t *
3835 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3836
3837 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3838 Int8PtrTy,
3839 llvm::PointerType::getUnqual(
3840 ProtocolListTyHolder),
3841 MethodListnfABIPtrTy,
3842 MethodListnfABIPtrTy,
3843 MethodListnfABIPtrTy,
3844 MethodListnfABIPtrTy,
3845 PropertyListPtrTy,
3846 IntTy,
3847 IntTy,
3848 NULL);
3849 CGM.getModule().addTypeName("struct._protocol_t",
3850 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003851
3852 // struct _protocol_t*
3853 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003854
Fariborz Jahanianda320092009-01-29 19:24:30 +00003855 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003856 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003857 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003858 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003859 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3860 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003861 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003862 NULL);
3863 CGM.getModule().addTypeName("struct._objc_protocol_list",
3864 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003865 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3866 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003867
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003868 // struct _objc_protocol_list*
3869 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003870
3871 // struct _ivar_t {
3872 // unsigned long int *offset; // pointer to ivar offset location
3873 // char *name;
3874 // char *type;
3875 // uint32_t alignment;
3876 // uint32_t size;
3877 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003878 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3879 Int8PtrTy,
3880 Int8PtrTy,
3881 IntTy,
3882 IntTy,
3883 NULL);
3884 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3885
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003886 // struct _ivar_list_t {
3887 // uint32 entsize; // sizeof(struct _ivar_t)
3888 // uint32 count;
3889 // struct _iver_t list[count];
3890 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003891 IvarListnfABITy = llvm::StructType::get(IntTy,
3892 IntTy,
3893 llvm::ArrayType::get(
3894 IvarnfABITy, 0),
3895 NULL);
3896 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3897
3898 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003899
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003900 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003901 // uint32_t const flags;
3902 // uint32_t const instanceStart;
3903 // uint32_t const instanceSize;
3904 // uint32_t const reserved; // only when building for 64bit targets
3905 // const uint8_t * const ivarLayout;
3906 // const char *const name;
3907 // const struct _method_list_t * const baseMethods;
3908 // const struct _objc_protocol_list *const baseProtocols;
3909 // const struct _ivar_list_t *const ivars;
3910 // const uint8_t * const weakIvarLayout;
3911 // const struct _prop_list_t * const properties;
3912 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003913
3914 // FIXME. Add 'reserved' field in 64bit abi mode!
3915 ClassRonfABITy = llvm::StructType::get(IntTy,
3916 IntTy,
3917 IntTy,
3918 Int8PtrTy,
3919 Int8PtrTy,
3920 MethodListnfABIPtrTy,
3921 ProtocolListnfABIPtrTy,
3922 IvarListnfABIPtrTy,
3923 Int8PtrTy,
3924 PropertyListPtrTy,
3925 NULL);
3926 CGM.getModule().addTypeName("struct._class_ro_t",
3927 ClassRonfABITy);
3928
3929 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3930 std::vector<const llvm::Type*> Params;
3931 Params.push_back(ObjectPtrTy);
3932 Params.push_back(SelectorPtrTy);
3933 ImpnfABITy = llvm::PointerType::getUnqual(
3934 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3935
3936 // struct _class_t {
3937 // struct _class_t *isa;
3938 // struct _class_t * const superclass;
3939 // void *cache;
3940 // IMP *vtable;
3941 // struct class_ro_t *ro;
3942 // }
3943
3944 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3945 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3946 llvm::PointerType::getUnqual(ClassTyHolder),
3947 CachePtrTy,
3948 llvm::PointerType::getUnqual(ImpnfABITy),
3949 llvm::PointerType::getUnqual(
3950 ClassRonfABITy),
3951 NULL);
3952 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3953
3954 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3955 ClassnfABITy);
3956
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003957 // LLVM for struct _class_t *
3958 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3959
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003960 // struct _category_t {
3961 // const char * const name;
3962 // struct _class_t *const cls;
3963 // const struct _method_list_t * const instance_methods;
3964 // const struct _method_list_t * const class_methods;
3965 // const struct _protocol_list_t * const protocols;
3966 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003967 // }
3968 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003969 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003970 MethodListnfABIPtrTy,
3971 MethodListnfABIPtrTy,
3972 ProtocolListnfABIPtrTy,
3973 PropertyListPtrTy,
3974 NULL);
3975 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003976
3977 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003978 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3979 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003980
3981 // MessageRefTy - LLVM for:
3982 // struct _message_ref_t {
3983 // IMP messenger;
3984 // SEL name;
3985 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003986
3987 // First the clang type for struct _message_ref_t
3988 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3989 SourceLocation(),
3990 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003991 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3992 Ctx.VoidPtrTy, 0, false));
3993 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3994 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003995 RD->completeDefinition(Ctx);
3996
3997 MessageRefCTy = Ctx.getTagDeclType(RD);
3998 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3999 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004000
4001 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4002 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4003
4004 // SuperMessageRefTy - LLVM for:
4005 // struct _super_message_ref_t {
4006 // SUPER_IMP messenger;
4007 // SEL name;
4008 // };
4009 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4010 SelectorPtrTy,
4011 NULL);
4012 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4013
4014 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4015 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4016
Daniel Dunbare588b992009-03-01 04:46:24 +00004017
4018 // struct objc_typeinfo {
4019 // const void** vtable; // objc_ehtype_vtable + 2
4020 // const char* name; // c++ typeinfo string
4021 // Class cls;
4022 // };
4023 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4024 Int8PtrTy,
4025 ClassnfABIPtrTy,
4026 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004027 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004028 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004029}
4030
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004031llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4032 FinishNonFragileABIModule();
4033
4034 return NULL;
4035}
4036
Daniel Dunbar463b8762009-05-15 21:48:48 +00004037void CGObjCNonFragileABIMac::AddModuleClassList(const
4038 std::vector<llvm::GlobalValue*>
4039 &Container,
4040 const char *SymbolName,
4041 const char *SectionName) {
4042 unsigned NumClasses = Container.size();
4043
4044 if (!NumClasses)
4045 return;
4046
4047 std::vector<llvm::Constant*> Symbols(NumClasses);
4048 for (unsigned i=0; i<NumClasses; i++)
4049 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4050 ObjCTypes.Int8PtrTy);
4051 llvm::Constant* Init =
4052 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4053 NumClasses),
4054 Symbols);
4055
4056 llvm::GlobalVariable *GV =
4057 new llvm::GlobalVariable(Init->getType(), false,
4058 llvm::GlobalValue::InternalLinkage,
4059 Init,
4060 SymbolName,
4061 &CGM.getModule());
4062 GV->setAlignment(8);
4063 GV->setSection(SectionName);
4064 UsedGlobals.push_back(GV);
4065}
4066
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004067void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4068 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004069
Daniel Dunbar463b8762009-05-15 21:48:48 +00004070 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004071 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004072 AddModuleClassList(DefinedClasses,
4073 "\01L_OBJC_LABEL_CLASS_$",
4074 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004075 AddModuleClassList(DefinedNonLazyClasses,
4076 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4077 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004078
4079 // Build list of all implemented category addresses in array
4080 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004081 AddModuleClassList(DefinedCategories,
4082 "\01L_OBJC_LABEL_CATEGORY_$",
4083 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004084 AddModuleClassList(DefinedNonLazyCategories,
4085 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4086 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004087
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004088 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4089 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4090 std::vector<llvm::Constant*> Values(2);
4091 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004092 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004093 // FIXME: Fix and continue?
4094 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4095 flags |= eImageInfo_GarbageCollected;
4096 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4097 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004098 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004099 llvm::Constant* Init = llvm::ConstantArray::get(
4100 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4101 Values);
4102 llvm::GlobalVariable *IMGV =
4103 new llvm::GlobalVariable(Init->getType(), false,
4104 llvm::GlobalValue::InternalLinkage,
4105 Init,
4106 "\01L_OBJC_IMAGE_INFO",
4107 &CGM.getModule());
4108 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004109 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004110 UsedGlobals.push_back(IMGV);
4111
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004112 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004113
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004114 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4115 e = UsedGlobals.end(); i != e; ++i) {
4116 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4117 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004118
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004119 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4120 llvm::GlobalValue *GV =
4121 new llvm::GlobalVariable(AT, false,
4122 llvm::GlobalValue::AppendingLinkage,
4123 llvm::ConstantArray::get(AT, Used),
4124 "llvm.used",
4125 &CGM.getModule());
4126
4127 GV->setSection("llvm.metadata");
4128
4129}
4130
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004131/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004132/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004133/// except for the 19 selectors in the list, we generate 32bit-style
4134/// message dispatch call for all the rest.
4135///
4136bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004137 if (NonLegacyDispatchMethods.empty()) {
4138 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4139 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4140 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4141 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4142 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4143 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4144 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4145 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4146 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4147 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4148
4149 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4150 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4151 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4152 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4153 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4154 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4155 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4156 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004157 // "countByEnumeratingWithState:objects:count"
4158 IdentifierInfo *KeyIdents[] = {
4159 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4160 &CGM.getContext().Idents.get("objects"),
4161 &CGM.getContext().Idents.get("count")
4162 };
4163 NonLegacyDispatchMethods.insert(
4164 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004165 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004166 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004167}
4168
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004169// Metadata flags
4170enum MetaDataDlags {
4171 CLS = 0x0,
4172 CLS_META = 0x1,
4173 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004174 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004175 CLS_EXCEPTION = 0x20
4176};
4177/// BuildClassRoTInitializer - generate meta-data for:
4178/// struct _class_ro_t {
4179/// uint32_t const flags;
4180/// uint32_t const instanceStart;
4181/// uint32_t const instanceSize;
4182/// uint32_t const reserved; // only when building for 64bit targets
4183/// const uint8_t * const ivarLayout;
4184/// const char *const name;
4185/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004186/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004187/// const struct _ivar_list_t *const ivars;
4188/// const uint8_t * const weakIvarLayout;
4189/// const struct _prop_list_t * const properties;
4190/// }
4191///
4192llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4193 unsigned flags,
4194 unsigned InstanceStart,
4195 unsigned InstanceSize,
4196 const ObjCImplementationDecl *ID) {
4197 std::string ClassName = ID->getNameAsString();
4198 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4199 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4200 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4201 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4202 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004203 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4204 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004206 // const struct _method_list_t * const baseMethods;
4207 std::vector<llvm::Constant*> Methods;
4208 std::string MethodListName("\01l_OBJC_$_");
4209 if (flags & CLS_META) {
4210 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004211 for (ObjCImplementationDecl::classmeth_iterator
4212 i = ID->classmeth_begin(CGM.getContext()),
4213 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004214 // Class methods should always be defined.
4215 Methods.push_back(GetMethodConstant(*i));
4216 }
4217 } else {
4218 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004219 for (ObjCImplementationDecl::instmeth_iterator
4220 i = ID->instmeth_begin(CGM.getContext()),
4221 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004222 // Instance methods should always be defined.
4223 Methods.push_back(GetMethodConstant(*i));
4224 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004225 for (ObjCImplementationDecl::propimpl_iterator
4226 i = ID->propimpl_begin(CGM.getContext()),
4227 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004228 ObjCPropertyImplDecl *PID = *i;
4229
4230 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4231 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4232
4233 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4234 if (llvm::Constant *C = GetMethodConstant(MD))
4235 Methods.push_back(C);
4236 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4237 if (llvm::Constant *C = GetMethodConstant(MD))
4238 Methods.push_back(C);
4239 }
4240 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004241 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004242 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004243 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004244
4245 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4246 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4247 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4248 + OID->getNameAsString(),
4249 OID->protocol_begin(),
4250 OID->protocol_end());
4251
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004252 if (flags & CLS_META)
4253 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4254 else
4255 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004256 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4257 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004258 if (flags & CLS_META)
4259 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4260 else
4261 Values[ 9] =
4262 EmitPropertyList(
4263 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4264 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004265 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4266 Values);
4267 llvm::GlobalVariable *CLASS_RO_GV =
4268 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4269 llvm::GlobalValue::InternalLinkage,
4270 Init,
4271 (flags & CLS_META) ?
4272 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4273 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4274 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004275 CLASS_RO_GV->setAlignment(
4276 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004277 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004278 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004279
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004280}
4281
4282/// BuildClassMetaData - This routine defines that to-level meta-data
4283/// for the given ClassName for:
4284/// struct _class_t {
4285/// struct _class_t *isa;
4286/// struct _class_t * const superclass;
4287/// void *cache;
4288/// IMP *vtable;
4289/// struct class_ro_t *ro;
4290/// }
4291///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004292llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4293 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004294 llvm::Constant *IsAGV,
4295 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004296 llvm::Constant *ClassRoGV,
4297 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004298 std::vector<llvm::Constant*> Values(5);
4299 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004300 Values[1] = SuperClassGV
4301 ? SuperClassGV
4302 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004303 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4304 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4305 Values[4] = ClassRoGV; // &CLASS_RO_GV
4306 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4307 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004308 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4309 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004310 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004311 GV->setAlignment(
4312 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004313 if (HiddenVisibility)
4314 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004315 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004316}
4317
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004318bool
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00004319CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
4320 return OD->getClassMethod(CGM.getContext(), GetNullarySelector("load")) != 0;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004321}
4322
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004323void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004324 uint32_t &InstanceStart,
4325 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004326 const ASTRecordLayout &RL =
4327 CGM.getContext().getASTObjCImplementationLayout(OID);
4328
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004329 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004330 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004331
4332 // If there are no fields, the start is the same as the end.
4333 if (!RL.getFieldCount())
4334 InstanceStart = InstanceSize;
4335 else
4336 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004337}
4338
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004339void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4340 std::string ClassName = ID->getNameAsString();
4341 if (!ObjCEmptyCacheVar) {
4342 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004343 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004344 false,
4345 llvm::GlobalValue::ExternalLinkage,
4346 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004347 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004348 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004349
4350 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004351 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004352 false,
4353 llvm::GlobalValue::ExternalLinkage,
4354 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004355 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004356 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004357 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004358 assert(ID->getClassInterface() &&
4359 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004360 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004361 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004362 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004363 uint32_t InstanceSize = InstanceStart;
4364 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004365 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4366 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004367
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004368 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004369
Daniel Dunbar04d40782009-04-14 06:00:08 +00004370 bool classIsHidden =
4371 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004372 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004373 flags |= OBJC2_CLS_HIDDEN;
4374 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004375 // class is root
4376 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004377 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004378 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004379 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004380 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004381 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4382 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4383 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004384 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004385 // work on super class metadata symbol.
4386 std::string SuperClassName =
4387 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004388 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004389 }
4390 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4391 InstanceStart,
4392 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004393 std::string TClassName = ObjCMetaClassName + ClassName;
4394 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004395 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4396 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004397
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004398 // Metadata for the class
4399 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004400 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004401 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004402
4403 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4404 flags |= CLS_EXCEPTION;
4405
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004406 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004407 flags |= CLS_ROOT;
4408 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004409 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004410 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004411 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004412 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004413 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004414 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004415 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004416 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004417 InstanceStart,
4418 InstanceSize,
4419 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004420
4421 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004422 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004423 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4424 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004425 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004426
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004427 // Determine if this class is also "non-lazy".
4428 if (ImplementationIsNonLazy(ID))
4429 DefinedNonLazyClasses.push_back(ClassMD);
4430
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004431 // Force the definition of the EHType if necessary.
4432 if (flags & CLS_EXCEPTION)
4433 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004434}
4435
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004436/// GenerateProtocolRef - This routine is called to generate code for
4437/// a protocol reference expression; as in:
4438/// @code
4439/// @protocol(Proto1);
4440/// @endcode
4441/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4442/// which will hold address of the protocol meta-data.
4443///
4444llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4445 const ObjCProtocolDecl *PD) {
4446
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004447 // This routine is called for @protocol only. So, we must build definition
4448 // of protocol's meta-data (not a reference to it!)
4449 //
4450 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004451 ObjCTypes.ExternalProtocolPtrTy);
4452
4453 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4454 ProtocolName += PD->getNameAsCString();
4455
4456 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4457 if (PTGV)
4458 return Builder.CreateLoad(PTGV, false, "tmp");
4459 PTGV = new llvm::GlobalVariable(
4460 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004461 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004462 Init,
4463 ProtocolName,
4464 &CGM.getModule());
4465 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4466 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4467 UsedGlobals.push_back(PTGV);
4468 return Builder.CreateLoad(PTGV, false, "tmp");
4469}
4470
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004471/// GenerateCategory - Build metadata for a category implementation.
4472/// struct _category_t {
4473/// const char * const name;
4474/// struct _class_t *const cls;
4475/// const struct _method_list_t * const instance_methods;
4476/// const struct _method_list_t * const class_methods;
4477/// const struct _protocol_list_t * const protocols;
4478/// const struct _prop_list_t * const properties;
4479/// }
4480///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004481void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004482 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004483 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4484 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004485 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004486 std::string ExtClassName(getClassSymbolPrefix() +
4487 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004488
4489 std::vector<llvm::Constant*> Values(6);
4490 Values[0] = GetClassName(OCD->getIdentifier());
4491 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004492 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004493 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004494 std::vector<llvm::Constant*> Methods;
4495 std::string MethodListName(Prefix);
4496 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4497 "_$_" + OCD->getNameAsString();
4498
Douglas Gregor653f1b12009-04-23 01:02:12 +00004499 for (ObjCCategoryImplDecl::instmeth_iterator
4500 i = OCD->instmeth_begin(CGM.getContext()),
4501 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004502 // Instance methods should always be defined.
4503 Methods.push_back(GetMethodConstant(*i));
4504 }
4505
4506 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004507 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004508 Methods);
4509
4510 MethodListName = Prefix;
4511 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4512 OCD->getNameAsString();
4513 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004514 for (ObjCCategoryImplDecl::classmeth_iterator
4515 i = OCD->classmeth_begin(CGM.getContext()),
4516 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004517 // Class methods should always be defined.
4518 Methods.push_back(GetMethodConstant(*i));
4519 }
4520
4521 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004522 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004523 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004524 const ObjCCategoryDecl *Category =
4525 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004526 if (Category) {
4527 std::string ExtName(Interface->getNameAsString() + "_$_" +
4528 OCD->getNameAsString());
4529 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4530 + Interface->getNameAsString() + "_$_"
4531 + Category->getNameAsString(),
4532 Category->protocol_begin(),
4533 Category->protocol_end());
4534 Values[5] =
4535 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4536 OCD, Category, ObjCTypes);
4537 }
4538 else {
4539 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4540 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4541 }
4542
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004543 llvm::Constant *Init =
4544 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4545 Values);
4546 llvm::GlobalVariable *GCATV
4547 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4548 false,
4549 llvm::GlobalValue::InternalLinkage,
4550 Init,
4551 ExtCatName,
4552 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004553 GCATV->setAlignment(
4554 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004555 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004556 UsedGlobals.push_back(GCATV);
4557 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004558
4559 // Determine if this category is also "non-lazy".
4560 if (ImplementationIsNonLazy(OCD))
4561 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004562}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004563
4564/// GetMethodConstant - Return a struct objc_method constant for the
4565/// given method if it has been defined. The result is null if the
4566/// method has not been defined. The return value has type MethodPtrTy.
4567llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4568 const ObjCMethodDecl *MD) {
4569 // FIXME: Use DenseMap::lookup
4570 llvm::Function *Fn = MethodDefinitions[MD];
4571 if (!Fn)
4572 return 0;
4573
4574 std::vector<llvm::Constant*> Method(3);
4575 Method[0] =
4576 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4577 ObjCTypes.SelectorPtrTy);
4578 Method[1] = GetMethodVarType(MD);
4579 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4580 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4581}
4582
4583/// EmitMethodList - Build meta-data for method declarations
4584/// struct _method_list_t {
4585/// uint32_t entsize; // sizeof(struct _objc_method)
4586/// uint32_t method_count;
4587/// struct _objc_method method_list[method_count];
4588/// }
4589///
4590llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4591 const std::string &Name,
4592 const char *Section,
4593 const ConstantVector &Methods) {
4594 // Return null for empty list.
4595 if (Methods.empty())
4596 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4597
4598 std::vector<llvm::Constant*> Values(3);
4599 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004600 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004601 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4602 // method_count
4603 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4604 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4605 Methods.size());
4606 Values[2] = llvm::ConstantArray::get(AT, Methods);
4607 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4608
4609 llvm::GlobalVariable *GV =
4610 new llvm::GlobalVariable(Init->getType(), false,
4611 llvm::GlobalValue::InternalLinkage,
4612 Init,
4613 Name,
4614 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004615 GV->setAlignment(
4616 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004617 GV->setSection(Section);
4618 UsedGlobals.push_back(GV);
4619 return llvm::ConstantExpr::getBitCast(GV,
4620 ObjCTypes.MethodListnfABIPtrTy);
4621}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004622
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004623/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4624/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004625llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004626 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004627 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004628 // FIXME: We shouldn't need to do this lookup.
4629 unsigned Index;
4630 const ObjCInterfaceDecl *Container =
4631 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4632 assert(Container && "Unable to find ivar container!");
4633 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004634 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004635 llvm::GlobalVariable *IvarOffsetGV =
4636 CGM.getModule().getGlobalVariable(Name);
4637 if (!IvarOffsetGV)
4638 IvarOffsetGV =
4639 new llvm::GlobalVariable(ObjCTypes.LongTy,
4640 false,
4641 llvm::GlobalValue::ExternalLinkage,
4642 0,
4643 Name,
4644 &CGM.getModule());
4645 return IvarOffsetGV;
4646}
4647
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004648llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004649 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004650 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004651 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004652 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4653 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4654 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004655 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004656 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004657
Mike Stumpf5408fe2009-05-16 07:57:57 +00004658 // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
4659 // well (i.e., in ObjCIvarOffsetVariable).
Daniel Dunbar737c5022009-04-19 00:44:02 +00004660 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4661 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4662 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004663 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004664 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004665 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004666 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004667 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004668}
4669
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004670/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004671/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004672/// IvarListnfABIPtrTy.
4673/// struct _ivar_t {
4674/// unsigned long int *offset; // pointer to ivar offset location
4675/// char *name;
4676/// char *type;
4677/// uint32_t alignment;
4678/// uint32_t size;
4679/// }
4680/// struct _ivar_list_t {
4681/// uint32 entsize; // sizeof(struct _ivar_t)
4682/// uint32 count;
4683/// struct _iver_t list[count];
4684/// }
4685///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004686
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004687llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4688 const ObjCImplementationDecl *ID) {
4689
4690 std::vector<llvm::Constant*> Ivars, Ivar(5);
4691
4692 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4693 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4694
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004695 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004696
Daniel Dunbar91636d62009-04-20 00:33:43 +00004697 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004698 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004699 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004700
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004701 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4702 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004703 // Ignore unnamed bit-fields.
4704 if (!IVD->getDeclName())
4705 continue;
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004706 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004707 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004708 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4709 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004710 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004711 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004712 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004713 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004714 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004715 Align = llvm::Log2_32(Align);
4716 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004717 // NOTE. Size of a bitfield does not match gcc's, because of the
4718 // way bitfields are treated special in each. But I am told that
4719 // 'size' for bitfield ivars is ignored by the runtime so it does
4720 // not matter. If it matters, there is enough info to get the
4721 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004722 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4723 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4724 }
4725 // Return null for empty list.
4726 if (Ivars.empty())
4727 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4728 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004729 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004730 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4731 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4732 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4733 Ivars.size());
4734 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4735 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4736 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4737 llvm::GlobalVariable *GV =
4738 new llvm::GlobalVariable(Init->getType(), false,
4739 llvm::GlobalValue::InternalLinkage,
4740 Init,
4741 Prefix + OID->getNameAsString(),
4742 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004743 GV->setAlignment(
4744 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004745 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004746
4747 UsedGlobals.push_back(GV);
4748 return llvm::ConstantExpr::getBitCast(GV,
4749 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750}
4751
4752llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4753 const ObjCProtocolDecl *PD) {
4754 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4755
4756 if (!Entry) {
4757 // We use the initializer as a marker of whether this is a forward
4758 // reference or not. At module finalization we add the empty
4759 // contents for protocols which were referenced but never defined.
4760 Entry =
4761 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4762 llvm::GlobalValue::ExternalLinkage,
4763 0,
4764 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4765 &CGM.getModule());
4766 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4767 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004768 }
4769
4770 return Entry;
4771}
4772
4773/// GetOrEmitProtocol - Generate the protocol meta-data:
4774/// @code
4775/// struct _protocol_t {
4776/// id isa; // NULL
4777/// const char * const protocol_name;
4778/// const struct _protocol_list_t * protocol_list; // super protocols
4779/// const struct method_list_t * const instance_methods;
4780/// const struct method_list_t * const class_methods;
4781/// const struct method_list_t *optionalInstanceMethods;
4782/// const struct method_list_t *optionalClassMethods;
4783/// const struct _prop_list_t * properties;
4784/// const uint32_t size; // sizeof(struct _protocol_t)
4785/// const uint32_t flags; // = 0
4786/// }
4787/// @endcode
4788///
4789
4790llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4791 const ObjCProtocolDecl *PD) {
4792 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4793
4794 // Early exit if a defining object has already been generated.
4795 if (Entry && Entry->hasInitializer())
4796 return Entry;
4797
4798 const char *ProtocolName = PD->getNameAsCString();
4799
4800 // Construct method lists.
4801 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4802 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004803 for (ObjCProtocolDecl::instmeth_iterator
4804 i = PD->instmeth_begin(CGM.getContext()),
4805 e = PD->instmeth_end(CGM.getContext());
4806 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004807 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004808 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004809 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4810 OptInstanceMethods.push_back(C);
4811 } else {
4812 InstanceMethods.push_back(C);
4813 }
4814 }
4815
Douglas Gregor6ab35242009-04-09 21:40:53 +00004816 for (ObjCProtocolDecl::classmeth_iterator
4817 i = PD->classmeth_begin(CGM.getContext()),
4818 e = PD->classmeth_end(CGM.getContext());
4819 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004820 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004821 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4823 OptClassMethods.push_back(C);
4824 } else {
4825 ClassMethods.push_back(C);
4826 }
4827 }
4828
4829 std::vector<llvm::Constant*> Values(10);
4830 // isa is NULL
4831 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4832 Values[1] = GetClassName(PD->getIdentifier());
4833 Values[2] = EmitProtocolList(
4834 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4835 PD->protocol_begin(),
4836 PD->protocol_end());
4837
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004838 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004839 + PD->getNameAsString(),
4840 "__DATA, __objc_const",
4841 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004842 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 + PD->getNameAsString(),
4844 "__DATA, __objc_const",
4845 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004846 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 + PD->getNameAsString(),
4848 "__DATA, __objc_const",
4849 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004850 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004851 + PD->getNameAsString(),
4852 "__DATA, __objc_const",
4853 OptClassMethods);
4854 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4855 0, PD, ObjCTypes);
4856 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004857 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004858 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4859 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4860 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4861 Values);
4862
4863 if (Entry) {
4864 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004865 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004866 Entry->setInitializer(Init);
4867 } else {
4868 Entry =
4869 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004870 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004871 Init,
4872 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4873 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004874 Entry->setAlignment(
4875 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004876 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004877 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004878 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4879
4880 // Use this protocol meta-data to build protocol list table in section
4881 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004882 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004883 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004884 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004885 Entry,
4886 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4887 +ProtocolName,
4888 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004889 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004890 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004891 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004892 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4893 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004894 return Entry;
4895}
4896
4897/// EmitProtocolList - Generate protocol list meta-data:
4898/// @code
4899/// struct _protocol_list_t {
4900/// long protocol_count; // Note, this is 32/64 bit
4901/// struct _protocol_t[protocol_count];
4902/// }
4903/// @endcode
4904///
4905llvm::Constant *
4906CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4907 ObjCProtocolDecl::protocol_iterator begin,
4908 ObjCProtocolDecl::protocol_iterator end) {
4909 std::vector<llvm::Constant*> ProtocolRefs;
4910
Fariborz Jahanianda320092009-01-29 19:24:30 +00004911 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004912 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004913 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4914
Daniel Dunbar948e2582009-02-15 07:36:20 +00004915 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004916 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4917 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004918 return llvm::ConstantExpr::getBitCast(GV,
4919 ObjCTypes.ProtocolListnfABIPtrTy);
4920
4921 for (; begin != end; ++begin)
4922 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4923
Fariborz Jahanianda320092009-01-29 19:24:30 +00004924 // This list is null terminated.
4925 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004926 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004927
4928 std::vector<llvm::Constant*> Values(2);
4929 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4930 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004931 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004932 ProtocolRefs.size()),
4933 ProtocolRefs);
4934
4935 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4936 GV = new llvm::GlobalVariable(Init->getType(), false,
4937 llvm::GlobalValue::InternalLinkage,
4938 Init,
4939 Name,
4940 &CGM.getModule());
4941 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004942 GV->setAlignment(
4943 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004944 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004945 return llvm::ConstantExpr::getBitCast(GV,
4946 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004947}
4948
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004949/// GetMethodDescriptionConstant - This routine build following meta-data:
4950/// struct _objc_method {
4951/// SEL _cmd;
4952/// char *method_type;
4953/// char *_imp;
4954/// }
4955
4956llvm::Constant *
4957CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4958 std::vector<llvm::Constant*> Desc(3);
4959 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4960 ObjCTypes.SelectorPtrTy);
4961 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004962 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004963 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4964 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4965}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004966
4967/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4968/// This code gen. amounts to generating code for:
4969/// @code
4970/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4971/// @encode
4972///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004973LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004974 CodeGen::CodeGenFunction &CGF,
4975 QualType ObjectTy,
4976 llvm::Value *BaseValue,
4977 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004978 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004979 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004980 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4981 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004982}
4983
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004984llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4985 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004986 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004987 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004988 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4989 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004990}
4991
Fariborz Jahanian46551122009-02-04 00:22:57 +00004992CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4993 CodeGen::CodeGenFunction &CGF,
4994 QualType ResultType,
4995 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004996 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004997 QualType Arg0Ty,
4998 bool IsSuper,
4999 const CallArgList &CallArgs) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00005000 // FIXME. Even though IsSuper is passes. This function doese not handle calls
5001 // to 'super' receivers.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005002 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005003 llvm::Value *Arg0 = Receiver;
5004 if (!IsSuper)
5005 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005006
5007 // Find the message function name.
Mike Stumpf5408fe2009-05-16 07:57:57 +00005008 // FIXME. This is too much work to get the ABI-specific result type needed to
5009 // find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5011 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005012 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005013 std::string Name("\01l_");
5014 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005015#if 0
5016 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005017 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005018 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005019 // FIXME. Is there a better way of getting these names.
5020 // They are available in RuntimeFunctions vector pair.
5021 Name += "objc_msgSendId_stret_fixup";
5022 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005023 else
5024#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005025 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005026 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005027 Name += "objc_msgSendSuper2_stret_fixup";
5028 }
5029 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005030 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005031 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005032 Name += "objc_msgSend_stret_fixup";
5033 }
5034 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005035 else if (!IsSuper && ResultType->isFloatingType()) {
5036 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5037 BuiltinType::Kind k = BT->getKind();
5038 if (k == BuiltinType::LongDouble) {
5039 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5040 Name += "objc_msgSend_fpret_fixup";
5041 }
5042 else {
5043 Fn = ObjCTypes.getMessageSendFixupFn();
5044 Name += "objc_msgSend_fixup";
5045 }
5046 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 }
5048 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005049#if 0
5050// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005051 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005052 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 Name += "objc_msgSendId_fixup";
5054 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005055 else
5056#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005057 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005058 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005059 Name += "objc_msgSendSuper2_fixup";
5060 }
5061 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005062 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005063 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005064 Name += "objc_msgSend_fixup";
5065 }
5066 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005067 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005068 Name += '_';
5069 std::string SelName(Sel.getAsString());
5070 // Replace all ':' in selector name with '_' ouch!
5071 for(unsigned i = 0; i < SelName.size(); i++)
5072 if (SelName[i] == ':')
5073 SelName[i] = '_';
5074 Name += SelName;
5075 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5076 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005077 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005078 std::vector<llvm::Constant*> Values(2);
5079 Values[0] = Fn;
5080 Values[1] = GetMethodVarName(Sel);
5081 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5082 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005083 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005084 Init,
5085 Name,
5086 &CGM.getModule());
5087 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005088 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005089 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005090 }
5091 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005092
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005093 CallArgList ActualArgs;
5094 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5095 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5096 ObjCTypes.MessageRefCPtrTy));
5097 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005098 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5099 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5100 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005101 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005102 Callee = CGF.Builder.CreateBitCast(Callee,
5103 llvm::PointerType::getUnqual(FTy));
5104 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005105}
5106
5107/// Generate code for a message send expression in the nonfragile abi.
5108CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5109 CodeGen::CodeGenFunction &CGF,
5110 QualType ResultType,
5111 Selector Sel,
5112 llvm::Value *Receiver,
5113 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005114 const CallArgList &CallArgs,
5115 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005116 return LegacyDispatchedSelector(Sel)
5117 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5118 Receiver, CGF.getContext().getObjCIdType(),
5119 false, CallArgs, ObjCTypes)
5120 : EmitMessageSend(CGF, ResultType, Sel,
5121 Receiver, CGF.getContext().getObjCIdType(),
5122 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005123}
5124
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005125llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005126CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005127 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5128
Daniel Dunbardfff2302009-03-02 05:18:14 +00005129 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005130 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5131 llvm::GlobalValue::ExternalLinkage,
5132 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005133 }
5134
5135 return GV;
5136}
5137
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005138llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005139 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005140 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5141
5142 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005143 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005144 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005145 Entry =
5146 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5147 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005148 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005149 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005150 &CGM.getModule());
5151 Entry->setAlignment(
5152 CGM.getTargetData().getPrefTypeAlignment(
5153 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005154 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5155 UsedGlobals.push_back(Entry);
5156 }
5157
5158 return Builder.CreateLoad(Entry, false, "tmp");
5159}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005160
Daniel Dunbar11394522009-04-18 08:51:00 +00005161llvm::Value *
5162CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5163 const ObjCInterfaceDecl *ID) {
5164 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5165
5166 if (!Entry) {
5167 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5168 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5169 Entry =
5170 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5171 llvm::GlobalValue::InternalLinkage,
5172 ClassGV,
5173 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5174 &CGM.getModule());
5175 Entry->setAlignment(
5176 CGM.getTargetData().getPrefTypeAlignment(
5177 ObjCTypes.ClassnfABIPtrTy));
5178 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005179 UsedGlobals.push_back(Entry);
5180 }
5181
5182 return Builder.CreateLoad(Entry, false, "tmp");
5183}
5184
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005185/// EmitMetaClassRef - Return a Value * of the address of _class_t
5186/// meta-data
5187///
5188llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5189 const ObjCInterfaceDecl *ID) {
5190 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5191 if (Entry)
5192 return Builder.CreateLoad(Entry, false, "tmp");
5193
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005194 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005195 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005196 Entry =
5197 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5198 llvm::GlobalValue::InternalLinkage,
5199 MetaClassGV,
5200 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5201 &CGM.getModule());
5202 Entry->setAlignment(
5203 CGM.getTargetData().getPrefTypeAlignment(
5204 ObjCTypes.ClassnfABIPtrTy));
5205
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005206 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005207 UsedGlobals.push_back(Entry);
5208
5209 return Builder.CreateLoad(Entry, false, "tmp");
5210}
5211
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005212/// GetClass - Return a reference to the class for the given interface
5213/// decl.
5214llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5215 const ObjCInterfaceDecl *ID) {
5216 return EmitClassRef(Builder, ID);
5217}
5218
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005219/// Generates a message send where the super is the receiver. This is
5220/// a message send to self with special delivery semantics indicating
5221/// which class's method should be called.
5222CodeGen::RValue
5223CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5224 QualType ResultType,
5225 Selector Sel,
5226 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005227 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005228 llvm::Value *Receiver,
5229 bool IsClassMessage,
5230 const CodeGen::CallArgList &CallArgs) {
5231 // ...
5232 // Create and init a super structure; this is a (receiver, class)
5233 // pair we will pass to objc_msgSendSuper.
5234 llvm::Value *ObjCSuper =
5235 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5236
5237 llvm::Value *ReceiverAsObject =
5238 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5239 CGF.Builder.CreateStore(ReceiverAsObject,
5240 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5241
5242 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005243 llvm::Value *Target;
5244 if (IsClassMessage) {
5245 if (isCategoryImpl) {
5246 // Message sent to "super' in a class method defined in
5247 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005248 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005249 Target = CGF.Builder.CreateStructGEP(Target, 0);
5250 Target = CGF.Builder.CreateLoad(Target);
5251 }
5252 else
5253 Target = EmitMetaClassRef(CGF.Builder, Class);
5254 }
5255 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005256 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005257
Mike Stumpf5408fe2009-05-16 07:57:57 +00005258 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5259 // ObjCTypes types.
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005260 const llvm::Type *ClassTy =
5261 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5262 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5263 CGF.Builder.CreateStore(Target,
5264 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5265
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005266 return (LegacyDispatchedSelector(Sel))
5267 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5268 ObjCSuper, ObjCTypes.SuperPtrCTy,
5269 true, CallArgs,
5270 ObjCTypes)
5271 : EmitMessageSend(CGF, ResultType, Sel,
5272 ObjCSuper, ObjCTypes.SuperPtrCTy,
5273 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005274}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005275
5276llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5277 Selector Sel) {
5278 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5279
5280 if (!Entry) {
5281 llvm::Constant *Casted =
5282 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5283 ObjCTypes.SelectorPtrTy);
5284 Entry =
5285 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5286 llvm::GlobalValue::InternalLinkage,
5287 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5288 &CGM.getModule());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005289 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005290 UsedGlobals.push_back(Entry);
5291 }
5292
5293 return Builder.CreateLoad(Entry, false, "tmp");
5294}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005295/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5296/// objc_assign_ivar (id src, id *dst)
5297///
5298void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5299 llvm::Value *src, llvm::Value *dst)
5300{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005301 const llvm::Type * SrcTy = src->getType();
5302 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005303 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005304 assert(Size <= 8 && "does not support size > 8");
5305 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5306 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005307 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5308 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005309 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5310 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005311 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005312 src, dst, "assignivar");
5313 return;
5314}
5315
5316/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5317/// objc_assign_strongCast (id src, id *dst)
5318///
5319void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5320 CodeGen::CodeGenFunction &CGF,
5321 llvm::Value *src, llvm::Value *dst)
5322{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005323 const llvm::Type * SrcTy = src->getType();
5324 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005325 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005326 assert(Size <= 8 && "does not support size > 8");
5327 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5328 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005329 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5330 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005331 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5332 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005333 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005334 src, dst, "weakassign");
5335 return;
5336}
5337
5338/// EmitObjCWeakRead - Code gen for loading value of a __weak
5339/// object: objc_read_weak (id *src)
5340///
5341llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5342 CodeGen::CodeGenFunction &CGF,
5343 llvm::Value *AddrWeakObj)
5344{
Eli Friedman8339b352009-03-07 03:57:15 +00005345 const llvm::Type* DestTy =
5346 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005347 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005348 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005349 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005350 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005351 return read_weak;
5352}
5353
5354/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5355/// objc_assign_weak (id src, id *dst)
5356///
5357void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5358 llvm::Value *src, llvm::Value *dst)
5359{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005360 const llvm::Type * SrcTy = src->getType();
5361 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005362 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005363 assert(Size <= 8 && "does not support size > 8");
5364 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5365 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005366 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5367 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005368 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5369 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005370 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005371 src, dst, "weakassign");
5372 return;
5373}
5374
5375/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5376/// objc_assign_global (id src, id *dst)
5377///
5378void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5379 llvm::Value *src, llvm::Value *dst)
5380{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005381 const llvm::Type * SrcTy = src->getType();
5382 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005383 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005384 assert(Size <= 8 && "does not support size > 8");
5385 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5386 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005387 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5388 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005389 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5390 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005391 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005392 src, dst, "globalassign");
5393 return;
5394}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005395
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005396void
5397CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5398 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005399 bool isTry = isa<ObjCAtTryStmt>(S);
5400 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5401 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005402 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005403 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005404 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005405 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5406
5407 // For @synchronized, call objc_sync_enter(sync.expr). The
5408 // evaluation of the expression must occur before we enter the
5409 // @synchronized. We can safely avoid a temp here because jumps into
5410 // @synchronized are illegal & this will dominate uses.
5411 llvm::Value *SyncArg = 0;
5412 if (!isTry) {
5413 SyncArg =
5414 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5415 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005416 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005417 }
5418
5419 // Push an EH context entry, used for handling rethrows and jumps
5420 // through finally.
5421 CGF.PushCleanupBlock(FinallyBlock);
5422
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005423 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005424
5425 CGF.EmitBlock(TryBlock);
5426 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5427 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5428 CGF.EmitBranchThroughCleanup(FinallyEnd);
5429
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005430 // Emit the exception handler.
5431
5432 CGF.EmitBlock(TryHandler);
5433
5434 llvm::Value *llvm_eh_exception =
5435 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5436 llvm::Value *llvm_eh_selector_i64 =
5437 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5438 llvm::Value *llvm_eh_typeid_for_i64 =
5439 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5440 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5441 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5442
5443 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5444 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005445 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446
5447 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005448 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005449 bool HasCatchAll = false;
5450 if (isTry) {
5451 if (const ObjCAtCatchStmt* CatchStmt =
5452 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5453 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005454 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005455 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005456
5457 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005458 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005459 // Use i8* null here to signal this is a catch all, not a cleanup.
5460 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5461 SelectorArgs.push_back(Null);
5462 HasCatchAll = true;
5463 break;
5464 }
5465
Daniel Dunbarede8de92009-03-06 00:01:21 +00005466 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5467 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005468 llvm::Value *IDEHType =
5469 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5470 if (!IDEHType)
5471 IDEHType =
5472 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5473 llvm::GlobalValue::ExternalLinkage,
5474 0, "OBJC_EHTYPE_id", &CGM.getModule());
5475 SelectorArgs.push_back(IDEHType);
5476 HasCatchAll = true;
5477 break;
5478 }
5479
5480 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005481 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005482 assert(PT && "Invalid @catch type.");
5483 const ObjCInterfaceType *IT =
5484 PT->getPointeeType()->getAsObjCInterfaceType();
5485 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005486 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005487 SelectorArgs.push_back(EHType);
5488 }
5489 }
5490 }
5491
5492 // We use a cleanup unless there was already a catch all.
5493 if (!HasCatchAll) {
5494 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005495 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496 }
5497
5498 llvm::Value *Selector =
5499 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5500 SelectorArgs.begin(), SelectorArgs.end(),
5501 "selector");
5502 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005503 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005504 const Stmt *CatchBody = Handlers[i].second;
5505
5506 llvm::BasicBlock *Next = 0;
5507
5508 // The last handler always matches.
5509 if (i + 1 != e) {
5510 assert(CatchParam && "Only last handler can be a catch all.");
5511
5512 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5513 Next = CGF.createBasicBlock("catch.next");
5514 llvm::Value *Id =
5515 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5516 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5517 ObjCTypes.Int8PtrTy));
5518 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5519 Match, Next);
5520
5521 CGF.EmitBlock(Match);
5522 }
5523
5524 if (CatchBody) {
5525 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5526 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5527
5528 // Cleanups must call objc_end_catch.
5529 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00005530 // FIXME: It seems incorrect for objc_begin_catch to be inside this
5531 // context, but this matches gcc.
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005532 CGF.PushCleanupBlock(MatchEnd);
5533 CGF.setInvokeDest(MatchHandler);
5534
5535 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005536 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005537
5538 // Bind the catch parameter if it exists.
5539 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005540 ExcObject =
5541 CGF.Builder.CreateBitCast(ExcObject,
5542 CGF.ConvertType(CatchParam->getType()));
5543 // CatchParam is a ParmVarDecl because of the grammar
5544 // construction used to handle this, but for codegen purposes
5545 // we treat this as a local decl.
5546 CGF.EmitLocalBlockVarDecl(*CatchParam);
5547 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005548 }
5549
5550 CGF.ObjCEHValueStack.push_back(ExcObject);
5551 CGF.EmitStmt(CatchBody);
5552 CGF.ObjCEHValueStack.pop_back();
5553
5554 CGF.EmitBranchThroughCleanup(FinallyEnd);
5555
5556 CGF.EmitBlock(MatchHandler);
5557
5558 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5559 // We are required to emit this call to satisfy LLVM, even
5560 // though we don't use the result.
5561 llvm::SmallVector<llvm::Value*, 8> Args;
5562 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005563 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005564 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5565 0));
5566 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5567 CGF.Builder.CreateStore(Exc, RethrowPtr);
5568 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5569
5570 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5571
5572 CGF.EmitBlock(MatchEnd);
5573
5574 // Unfortunately, we also have to generate another EH frame here
5575 // in case this throws.
5576 llvm::BasicBlock *MatchEndHandler =
5577 CGF.createBasicBlock("match.end.handler");
5578 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005579 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 Cont, MatchEndHandler,
5581 Args.begin(), Args.begin());
5582
5583 CGF.EmitBlock(Cont);
5584 if (Info.SwitchBlock)
5585 CGF.EmitBlock(Info.SwitchBlock);
5586 if (Info.EndBlock)
5587 CGF.EmitBlock(Info.EndBlock);
5588
5589 CGF.EmitBlock(MatchEndHandler);
5590 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5591 // We are required to emit this call to satisfy LLVM, even
5592 // though we don't use the result.
5593 Args.clear();
5594 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005595 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5597 0));
5598 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5599 CGF.Builder.CreateStore(Exc, RethrowPtr);
5600 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5601
5602 if (Next)
5603 CGF.EmitBlock(Next);
5604 } else {
5605 assert(!Next && "catchup should be last handler.");
5606
5607 CGF.Builder.CreateStore(Exc, RethrowPtr);
5608 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5609 }
5610 }
5611
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005612 // Pop the cleanup entry, the @finally is outside this cleanup
5613 // scope.
5614 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5615 CGF.setInvokeDest(PrevLandingPad);
5616
5617 CGF.EmitBlock(FinallyBlock);
5618
5619 if (isTry) {
5620 if (const ObjCAtFinallyStmt* FinallyStmt =
5621 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5622 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5623 } else {
5624 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5625 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005626 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005627 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005628
5629 if (Info.SwitchBlock)
5630 CGF.EmitBlock(Info.SwitchBlock);
5631 if (Info.EndBlock)
5632 CGF.EmitBlock(Info.EndBlock);
5633
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005634 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005635 CGF.EmitBranch(FinallyEnd);
5636
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005637 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005638 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005639 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005640 CGF.Builder.CreateUnreachable();
5641
5642 CGF.EmitBlock(FinallyEnd);
5643}
5644
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005645/// EmitThrowStmt - Generate code for a throw statement.
5646void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5647 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005648 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005649 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005650 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005651 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005652 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5653 "Unexpected rethrow outside @catch block.");
5654 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005655 }
5656
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005657 llvm::Value *ExceptionAsObject =
5658 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5659 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5660 if (InvokeDest) {
5661 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005662 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005663 Cont, InvokeDest,
5664 &ExceptionAsObject, &ExceptionAsObject + 1);
5665 CGF.EmitBlock(Cont);
5666 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005667 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005668 CGF.Builder.CreateUnreachable();
5669
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005670 // Clear the insertion point to indicate we are in unreachable code.
5671 CGF.Builder.ClearInsertionPoint();
5672}
Daniel Dunbare588b992009-03-01 04:46:24 +00005673
5674llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005675CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5676 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005677 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005678
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005679 // If we don't need a definition, return the entry if found or check
5680 // if we use an external reference.
5681 if (!ForDefinition) {
5682 if (Entry)
5683 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005684
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005685 // If this type (or a super class) has the __objc_exception__
5686 // attribute, emit an external reference.
5687 if (hasObjCExceptionAttribute(ID))
5688 return Entry =
5689 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5690 llvm::GlobalValue::ExternalLinkage,
5691 0,
5692 (std::string("OBJC_EHTYPE_$_") +
5693 ID->getIdentifier()->getName()),
5694 &CGM.getModule());
5695 }
5696
5697 // Otherwise we need to either make a new entry or fill in the
5698 // initializer.
5699 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005700 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005701 std::string VTableName = "objc_ehtype_vtable";
5702 llvm::GlobalVariable *VTableGV =
5703 CGM.getModule().getGlobalVariable(VTableName);
5704 if (!VTableGV)
5705 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5706 llvm::GlobalValue::ExternalLinkage,
5707 0, VTableName, &CGM.getModule());
5708
5709 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5710
5711 std::vector<llvm::Constant*> Values(3);
5712 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5713 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005714 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005715 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5716
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005717 if (Entry) {
5718 Entry->setInitializer(Init);
5719 } else {
5720 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5721 llvm::GlobalValue::WeakAnyLinkage,
5722 Init,
5723 (std::string("OBJC_EHTYPE_$_") +
5724 ID->getIdentifier()->getName()),
5725 &CGM.getModule());
5726 }
5727
Daniel Dunbar04d40782009-04-14 06:00:08 +00005728 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005729 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005730 Entry->setAlignment(8);
5731
5732 if (ForDefinition) {
5733 Entry->setSection("__DATA,__objc_const");
5734 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5735 } else {
5736 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5737 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005738
5739 return Entry;
5740}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005741
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005742/* *** */
5743
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005744CodeGen::CGObjCRuntime *
5745CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005746 return new CGObjCMac(CGM);
5747}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005748
5749CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005750CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005751 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005752}