blob: 38a9f2f8ebf5adad52b5f6251ee93d6b528aeff6 [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;
50 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(),
51 IVE = OID->ivar_end(); IVI != IVE; ++IVI, ++Index)
52 if (OIVD == *IVI)
53 return OID;
54
55 // Also look in synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +000056 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
57 Context.CollectSynthesizedIvars(OID, Ivars);
58 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
59 if (OIVD == Ivars[k])
60 return OID;
61 ++Index;
Daniel Dunbara80a0f62009-04-22 17:43:55 +000062 }
Fariborz Jahanian98200742009-05-12 18:14:29 +000063
Daniel Dunbar532d4da2009-05-03 13:15:50 +000064 // Otherwise check in the super class.
Daniel Dunbara81419d2009-05-05 00:36:57 +000065 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Daniel Dunbar532d4da2009-05-03 13:15:50 +000066 return FindIvarInterface(Context, Super, OIVD, Index);
67
68 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000069}
70
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000071static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
72 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000073 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000074 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000075 unsigned Index;
76 const ObjCInterfaceDecl *Container =
77 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
78 assert(Container && "Unable to find ivar container");
79
80 // If we know have an implementation (and the ivar is in it) then
81 // look up in the implementation layout.
82 const ASTRecordLayout *RL;
83 if (ID && ID->getClassInterface() == Container)
84 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
85 else
86 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
87 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000088}
89
90uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
91 const ObjCInterfaceDecl *OID,
92 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000093 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
94}
95
96uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
97 const ObjCImplementationDecl *OID,
98 const ObjCIvarDecl *Ivar) {
99 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +0000100}
101
102LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
103 const ObjCInterfaceDecl *OID,
104 llvm::Value *BaseValue,
105 const ObjCIvarDecl *Ivar,
106 unsigned CVRQualifiers,
107 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000108 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000109 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000110 QualType IvarTy = Ivar->getType();
111 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000112 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000113 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000114 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000115
116 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000117 // We need to compute the bit offset for the bit-field, the offset
118 // is to the byte. Note, there is a subtle invariant here: we can
119 // only call this routine on non-sythesized ivars but we may be
120 // called for synthesized ivars. However, a synthesized ivar can
121 // never be a bit-field so this is safe.
122 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
123
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000124 uint64_t BitFieldSize =
125 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
126 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000127 IvarTy->isSignedIntegerType(),
128 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000129 }
130
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000131 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
132 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000133 LValue::SetObjCIvar(LV, true);
134 return LV;
135}
136
137///
138
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000139namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000140
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000141 typedef std::vector<llvm::Constant*> ConstantVector;
142
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000143 // FIXME: We should find a nicer way to make the labels for
144 // metadata, string concatenation is lame.
145
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000146class ObjCCommonTypesHelper {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000147private:
148 llvm::Constant *getMessageSendFn() const {
149 // id objc_msgSend (id, SEL, ...)
150 std::vector<const llvm::Type*> Params;
151 Params.push_back(ObjectPtrTy);
152 Params.push_back(SelectorPtrTy);
153 return
154 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
155 Params, true),
156 "objc_msgSend");
157 }
158
159 llvm::Constant *getMessageSendStretFn() const {
160 // id objc_msgSend_stret (id, SEL, ...)
161 std::vector<const llvm::Type*> Params;
162 Params.push_back(ObjectPtrTy);
163 Params.push_back(SelectorPtrTy);
164 return
165 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
166 Params, true),
167 "objc_msgSend_stret");
168
169 }
170
171 llvm::Constant *getMessageSendFpretFn() const {
172 // FIXME: This should be long double on x86_64?
173 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
174 std::vector<const llvm::Type*> Params;
175 Params.push_back(ObjectPtrTy);
176 Params.push_back(SelectorPtrTy);
177 return
178 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
179 Params,
180 true),
181 "objc_msgSend_fpret");
182
183 }
184
185 llvm::Constant *getMessageSendSuperFn() const {
186 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
187 const char *SuperName = "objc_msgSendSuper";
188 std::vector<const llvm::Type*> Params;
189 Params.push_back(SuperPtrTy);
190 Params.push_back(SelectorPtrTy);
191 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
192 Params, true),
193 SuperName);
194 }
195
196 llvm::Constant *getMessageSendSuperFn2() const {
197 // id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
198 const char *SuperName = "objc_msgSendSuper2";
199 std::vector<const llvm::Type*> Params;
200 Params.push_back(SuperPtrTy);
201 Params.push_back(SelectorPtrTy);
202 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
203 Params, true),
204 SuperName);
205 }
206
207 llvm::Constant *getMessageSendSuperStretFn() const {
208 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
209 // SEL op, ...)
210 std::vector<const llvm::Type*> Params;
211 Params.push_back(Int8PtrTy);
212 Params.push_back(SuperPtrTy);
213 Params.push_back(SelectorPtrTy);
214 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
215 Params, true),
216 "objc_msgSendSuper_stret");
217 }
218
219 llvm::Constant *getMessageSendSuperStretFn2() const {
220 // void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
221 // SEL op, ...)
222 std::vector<const llvm::Type*> Params;
223 Params.push_back(Int8PtrTy);
224 Params.push_back(SuperPtrTy);
225 Params.push_back(SelectorPtrTy);
226 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
227 Params, true),
228 "objc_msgSendSuper2_stret");
229 }
230
231 llvm::Constant *getMessageSendSuperFpretFn() const {
232 // There is no objc_msgSendSuper_fpret? How can that work?
233 return getMessageSendSuperFn();
234 }
235
236 llvm::Constant *getMessageSendSuperFpretFn2() const {
237 // There is no objc_msgSendSuper_fpret? How can that work?
238 return getMessageSendSuperFn2();
239 }
240
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000241protected:
242 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000243
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000244public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000245 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000246 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000247
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000248 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
249 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000250
251 /// PtrObjectPtrTy - LLVM type for id *
252 const llvm::Type *PtrObjectPtrTy;
253
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000254 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000255 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000256 /// ProtocolPtrTy - LLVM type for external protocol handles
257 /// (typeof(Protocol))
258 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000259
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000260 // SuperCTy - clang type for struct objc_super.
261 QualType SuperCTy;
262 // SuperPtrCTy - clang type for struct objc_super *.
263 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000264
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000265 /// SuperTy - LLVM type for struct objc_super.
266 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000267 /// SuperPtrTy - LLVM type for struct objc_super *.
268 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000269
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000270 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
271 /// in GCC parlance).
272 const llvm::StructType *PropertyTy;
273
274 /// PropertyListTy - LLVM type for struct objc_property_list
275 /// (_prop_list_t in GCC parlance).
276 const llvm::StructType *PropertyListTy;
277 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
278 const llvm::Type *PropertyListPtrTy;
279
280 // MethodTy - LLVM type for struct objc_method.
281 const llvm::StructType *MethodTy;
282
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000283 /// CacheTy - LLVM type for struct objc_cache.
284 const llvm::Type *CacheTy;
285 /// CachePtrTy - LLVM type for struct objc_cache *.
286 const llvm::Type *CachePtrTy;
287
Chris Lattner72db6c32009-04-22 02:44:54 +0000288 llvm::Constant *getGetPropertyFn() {
289 CodeGen::CodeGenTypes &Types = CGM.getTypes();
290 ASTContext &Ctx = CGM.getContext();
291 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
292 llvm::SmallVector<QualType,16> Params;
293 QualType IdType = Ctx.getObjCIdType();
294 QualType SelType = Ctx.getObjCSelType();
295 Params.push_back(IdType);
296 Params.push_back(SelType);
297 Params.push_back(Ctx.LongTy);
298 Params.push_back(Ctx.BoolTy);
299 const llvm::FunctionType *FTy =
300 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
301 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
302 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000303
Chris Lattner72db6c32009-04-22 02:44:54 +0000304 llvm::Constant *getSetPropertyFn() {
305 CodeGen::CodeGenTypes &Types = CGM.getTypes();
306 ASTContext &Ctx = CGM.getContext();
307 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
308 llvm::SmallVector<QualType,16> Params;
309 QualType IdType = Ctx.getObjCIdType();
310 QualType SelType = Ctx.getObjCSelType();
311 Params.push_back(IdType);
312 Params.push_back(SelType);
313 Params.push_back(Ctx.LongTy);
314 Params.push_back(IdType);
315 Params.push_back(Ctx.BoolTy);
316 Params.push_back(Ctx.BoolTy);
317 const llvm::FunctionType *FTy =
318 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
319 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
320 }
321
322 llvm::Constant *getEnumerationMutationFn() {
323 // void objc_enumerationMutation (id)
324 std::vector<const llvm::Type*> Args;
325 Args.push_back(ObjectPtrTy);
326 llvm::FunctionType *FTy =
327 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
328 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
329 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000330
331 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000332 llvm::Constant *getGcReadWeakFn() {
333 // id objc_read_weak (id *)
334 std::vector<const llvm::Type*> Args;
335 Args.push_back(ObjectPtrTy->getPointerTo());
336 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
337 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
338 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000339
340 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000341 llvm::Constant *getGcAssignWeakFn() {
342 // id objc_assign_weak (id, id *)
343 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
344 Args.push_back(ObjectPtrTy->getPointerTo());
345 llvm::FunctionType *FTy =
346 llvm::FunctionType::get(ObjectPtrTy, Args, false);
347 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
348 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000349
350 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000351 llvm::Constant *getGcAssignGlobalFn() {
352 // id objc_assign_global(id, id *)
353 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
354 Args.push_back(ObjectPtrTy->getPointerTo());
355 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
356 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
357 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000358
359 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000360 llvm::Constant *getGcAssignIvarFn() {
361 // id objc_assign_ivar(id, id *)
362 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
363 Args.push_back(ObjectPtrTy->getPointerTo());
364 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
365 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
366 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000367
368 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000369 llvm::Constant *getGcAssignStrongCastFn() {
370 // id objc_assign_global(id, id *)
371 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
372 Args.push_back(ObjectPtrTy->getPointerTo());
373 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
374 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
375 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000376
377 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000378 llvm::Constant *getExceptionThrowFn() {
379 // void objc_exception_throw(id)
380 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
381 llvm::FunctionType *FTy =
382 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
383 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
384 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000385
Daniel Dunbar1c566672009-02-24 01:43:46 +0000386 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000387 llvm::Constant *getSyncEnterFn() {
388 // void objc_sync_enter (id)
389 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
390 llvm::FunctionType *FTy =
391 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
392 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
393 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000394
395 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000396 llvm::Constant *getSyncExitFn() {
397 // void objc_sync_exit (id)
398 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
399 llvm::FunctionType *FTy =
400 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
401 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
402 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000403
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000404 llvm::Constant *getSendFn(bool IsSuper) const {
405 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
406 }
407
408 llvm::Constant *getSendFn2(bool IsSuper) const {
409 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
410 }
411
412 llvm::Constant *getSendStretFn(bool IsSuper) const {
413 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
414 }
415
416 llvm::Constant *getSendStretFn2(bool IsSuper) const {
417 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
418 }
419
420 llvm::Constant *getSendFpretFn(bool IsSuper) const {
421 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
422 }
423
424 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
425 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
426 }
427
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000428 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
429 ~ObjCCommonTypesHelper(){}
430};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000431
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000432/// ObjCTypesHelper - Helper class that encapsulates lazy
433/// construction of varies types used during ObjC generation.
434class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000435public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000436 /// SymtabTy - LLVM type for struct objc_symtab.
437 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000438 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
439 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000440 /// ModuleTy - LLVM type for struct objc_module.
441 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000442
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000443 /// ProtocolTy - LLVM type for struct objc_protocol.
444 const llvm::StructType *ProtocolTy;
445 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
446 const llvm::Type *ProtocolPtrTy;
447 /// ProtocolExtensionTy - LLVM type for struct
448 /// objc_protocol_extension.
449 const llvm::StructType *ProtocolExtensionTy;
450 /// ProtocolExtensionTy - LLVM type for struct
451 /// objc_protocol_extension *.
452 const llvm::Type *ProtocolExtensionPtrTy;
453 /// MethodDescriptionTy - LLVM type for struct
454 /// objc_method_description.
455 const llvm::StructType *MethodDescriptionTy;
456 /// MethodDescriptionListTy - LLVM type for struct
457 /// objc_method_description_list.
458 const llvm::StructType *MethodDescriptionListTy;
459 /// MethodDescriptionListPtrTy - LLVM type for struct
460 /// objc_method_description_list *.
461 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000462 /// ProtocolListTy - LLVM type for struct objc_property_list.
463 const llvm::Type *ProtocolListTy;
464 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
465 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000466 /// CategoryTy - LLVM type for struct objc_category.
467 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000468 /// ClassTy - LLVM type for struct objc_class.
469 const llvm::StructType *ClassTy;
470 /// ClassPtrTy - LLVM type for struct objc_class *.
471 const llvm::Type *ClassPtrTy;
472 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
473 const llvm::StructType *ClassExtensionTy;
474 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
475 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000476 // IvarTy - LLVM type for struct objc_ivar.
477 const llvm::StructType *IvarTy;
478 /// IvarListTy - LLVM type for struct objc_ivar_list.
479 const llvm::Type *IvarListTy;
480 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
481 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000482 /// MethodListTy - LLVM type for struct objc_method_list.
483 const llvm::Type *MethodListTy;
484 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
485 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000486
487 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
488 const llvm::Type *ExceptionDataTy;
489
Anders Carlsson124526b2008-09-09 10:10:21 +0000490 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000491 llvm::Constant *getExceptionTryEnterFn() {
492 std::vector<const llvm::Type*> Params;
493 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
494 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
495 Params, false),
496 "objc_exception_try_enter");
497 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000498
499 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000500 llvm::Constant *getExceptionTryExitFn() {
501 std::vector<const llvm::Type*> Params;
502 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
503 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
504 Params, false),
505 "objc_exception_try_exit");
506 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000507
508 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000509 llvm::Constant *getExceptionExtractFn() {
510 std::vector<const llvm::Type*> Params;
511 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
512 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
513 Params, false),
514 "objc_exception_extract");
515
516 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000517
518 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000519 llvm::Constant *getExceptionMatchFn() {
520 std::vector<const llvm::Type*> Params;
521 Params.push_back(ClassPtrTy);
522 Params.push_back(ObjectPtrTy);
523 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
524 Params, false),
525 "objc_exception_match");
526
527 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000528
529 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000530 llvm::Constant *getSetJmpFn() {
531 std::vector<const llvm::Type*> Params;
532 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
533 return
534 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
535 Params, false),
536 "_setjmp");
537
538 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000539
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000540public:
541 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000542 ~ObjCTypesHelper() {}
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000543};
544
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000545/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000546/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000547class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000548public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000549
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000550 // MethodListnfABITy - LLVM for struct _method_list_t
551 const llvm::StructType *MethodListnfABITy;
552
553 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
554 const llvm::Type *MethodListnfABIPtrTy;
555
556 // ProtocolnfABITy = LLVM for struct _protocol_t
557 const llvm::StructType *ProtocolnfABITy;
558
Daniel Dunbar948e2582009-02-15 07:36:20 +0000559 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
560 const llvm::Type *ProtocolnfABIPtrTy;
561
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000562 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
563 const llvm::StructType *ProtocolListnfABITy;
564
565 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
566 const llvm::Type *ProtocolListnfABIPtrTy;
567
568 // ClassnfABITy - LLVM for struct _class_t
569 const llvm::StructType *ClassnfABITy;
570
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000571 // ClassnfABIPtrTy - LLVM for struct _class_t*
572 const llvm::Type *ClassnfABIPtrTy;
573
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000574 // IvarnfABITy - LLVM for struct _ivar_t
575 const llvm::StructType *IvarnfABITy;
576
577 // IvarListnfABITy - LLVM for struct _ivar_list_t
578 const llvm::StructType *IvarListnfABITy;
579
580 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
581 const llvm::Type *IvarListnfABIPtrTy;
582
583 // ClassRonfABITy - LLVM for struct _class_ro_t
584 const llvm::StructType *ClassRonfABITy;
585
586 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
587 const llvm::Type *ImpnfABITy;
588
589 // CategorynfABITy - LLVM for struct _category_t
590 const llvm::StructType *CategorynfABITy;
591
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000592 // New types for nonfragile abi messaging.
593
594 // MessageRefTy - LLVM for:
595 // struct _message_ref_t {
596 // IMP messenger;
597 // SEL name;
598 // };
599 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000600 // MessageRefCTy - clang type for struct _message_ref_t
601 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000602
603 // MessageRefPtrTy - LLVM for struct _message_ref_t*
604 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000605 // MessageRefCPtrTy - clang type for struct _message_ref_t*
606 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000607
Fariborz Jahanianef163782009-02-05 01:13:09 +0000608 // MessengerTy - Type of the messenger (shown as IMP above)
609 const llvm::FunctionType *MessengerTy;
610
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000611 // SuperMessageRefTy - LLVM for:
612 // struct _super_message_ref_t {
613 // SUPER_IMP messenger;
614 // SEL name;
615 // };
616 const llvm::StructType *SuperMessageRefTy;
617
618 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
619 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000620
Chris Lattner1c02f862009-04-22 02:53:24 +0000621 llvm::Constant *getMessageSendFixupFn() {
622 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
623 std::vector<const llvm::Type*> Params;
624 Params.push_back(ObjectPtrTy);
625 Params.push_back(MessageRefPtrTy);
626 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
627 Params, true),
628 "objc_msgSend_fixup");
629 }
630
631 llvm::Constant *getMessageSendFpretFixupFn() {
632 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
633 std::vector<const llvm::Type*> Params;
634 Params.push_back(ObjectPtrTy);
635 Params.push_back(MessageRefPtrTy);
636 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
637 Params, true),
638 "objc_msgSend_fpret_fixup");
639 }
640
641 llvm::Constant *getMessageSendStretFixupFn() {
642 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
643 std::vector<const llvm::Type*> Params;
644 Params.push_back(ObjectPtrTy);
645 Params.push_back(MessageRefPtrTy);
646 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
647 Params, true),
648 "objc_msgSend_stret_fixup");
649 }
650
651 llvm::Constant *getMessageSendIdFixupFn() {
652 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
653 std::vector<const llvm::Type*> Params;
654 Params.push_back(ObjectPtrTy);
655 Params.push_back(MessageRefPtrTy);
656 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
657 Params, true),
658 "objc_msgSendId_fixup");
659 }
660
661 llvm::Constant *getMessageSendIdStretFixupFn() {
662 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
663 std::vector<const llvm::Type*> Params;
664 Params.push_back(ObjectPtrTy);
665 Params.push_back(MessageRefPtrTy);
666 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
667 Params, true),
668 "objc_msgSendId_stret_fixup");
669 }
670 llvm::Constant *getMessageSendSuper2FixupFn() {
671 // id objc_msgSendSuper2_fixup (struct objc_super *,
672 // struct _super_message_ref_t*, ...)
673 std::vector<const llvm::Type*> Params;
674 Params.push_back(SuperPtrTy);
675 Params.push_back(SuperMessageRefPtrTy);
676 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
677 Params, true),
678 "objc_msgSendSuper2_fixup");
679 }
680
681 llvm::Constant *getMessageSendSuper2StretFixupFn() {
682 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
683 // struct _super_message_ref_t*, ...)
684 std::vector<const llvm::Type*> Params;
685 Params.push_back(SuperPtrTy);
686 Params.push_back(SuperMessageRefPtrTy);
687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
688 Params, true),
689 "objc_msgSendSuper2_stret_fixup");
690 }
691
692
693
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000694 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
695 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000696 llvm::Value *getEHPersonalityPtr() {
697 llvm::Constant *Personality =
698 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
699 std::vector<const llvm::Type*>(),
700 true),
701 "__objc_personality_v0");
702 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
703 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000704
Chris Lattner8a569112009-04-22 02:15:23 +0000705 llvm::Constant *getUnwindResumeOrRethrowFn() {
706 std::vector<const llvm::Type*> Params;
707 Params.push_back(Int8PtrTy);
708 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
709 Params, false),
710 "_Unwind_Resume_or_Rethrow");
711 }
712
713 llvm::Constant *getObjCEndCatchFn() {
714 std::vector<const llvm::Type*> Params;
715 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
716 Params, false),
717 "objc_end_catch");
718
719 }
720
721 llvm::Constant *getObjCBeginCatchFn() {
722 std::vector<const llvm::Type*> Params;
723 Params.push_back(Int8PtrTy);
724 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
725 Params, false),
726 "objc_begin_catch");
727 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000728
729 const llvm::StructType *EHTypeTy;
730 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000731
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000732 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
733 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000734};
735
736class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000737public:
738 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000739 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000740 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000741 unsigned ivar_bytepos;
742 unsigned ivar_size;
743 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
744 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000745
746 // Allow sorting based on byte pos.
747 bool operator<(const GC_IVAR &b) const {
748 return ivar_bytepos < b.ivar_bytepos;
749 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000750 };
751
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000752 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000753 public:
754 unsigned skip;
755 unsigned scan;
756 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
757 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000758 };
759
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000760protected:
761 CodeGen::CodeGenModule &CGM;
762 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000763 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000764
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000765 // gc ivar layout bitmap calculation helper caches.
766 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
767 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000768
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000769 /// LazySymbols - Symbols to generate a lazy reference for. See
770 /// DefinedSymbols and FinishModule().
771 std::set<IdentifierInfo*> LazySymbols;
772
773 /// DefinedSymbols - External symbols which are defined by this
774 /// module. The symbols in this list and LazySymbols are used to add
775 /// special linker symbols which ensure that Objective-C modules are
776 /// linked properly.
777 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000778
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000779 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000780 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000781
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000782 /// MethodVarNames - uniqued method variable names.
783 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000784
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000785 /// MethodVarTypes - uniqued method type signatures. We have to use
786 /// a StringMap here because have no other unique reference.
787 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000788
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000789 /// MethodDefinitions - map of methods which have been defined in
790 /// this translation unit.
791 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000792
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000793 /// PropertyNames - uniqued method variable names.
794 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000795
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000796 /// ClassReferences - uniqued class references.
797 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000798
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000799 /// SelectorReferences - uniqued selector references.
800 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000801
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000802 /// Protocols - Protocols for which an objc_protocol structure has
803 /// been emitted. Forward declarations are handled by creating an
804 /// empty structure whose initializer is filled in when/if defined.
805 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000806
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000807 /// DefinedProtocols - Protocols which have actually been
808 /// defined. We should not need this, see FIXME in GenerateProtocol.
809 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000810
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000811 /// DefinedClasses - List of defined classes.
812 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000813
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000814 /// DefinedCategories - List of defined categories.
815 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000816
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
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000905 /// GetNamedIvarList - Return the list of ivars in the interface
906 /// itself (not including super classes and not including unnamed
907 /// bitfields).
908 ///
909 /// For the non-fragile ABI, this also includes synthesized property
910 /// ivars.
911 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
912 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000913
914 CodeGen::RValue EmitLegacyMessageSend(CodeGen::CodeGenFunction &CGF,
915 QualType ResultType,
916 llvm::Value *Sel,
917 llvm::Value *Arg0,
918 QualType Arg0Ty,
919 bool IsSuper,
920 const CallArgList &CallArgs,
921 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000922
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000923public:
924 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
925 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000926
Steve Naroff33fdb732009-03-31 16:53:37 +0000927 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000928
929 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
930 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000931
932 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
933
934 /// GetOrEmitProtocol - Get the protocol object for the given
935 /// declaration, emitting it if necessary. The return value has type
936 /// ProtocolPtrTy.
937 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
938
939 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
940 /// object for the given declaration, emitting it if needed. These
941 /// forward references will be filled in with empty bodies if no
942 /// definition is seen. The return value has type ProtocolPtrTy.
943 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000944};
945
946class CGObjCMac : public CGObjCCommonMac {
947private:
948 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000949 /// EmitImageInfo - Emit the image info marker used to encode some module
950 /// level information.
951 void EmitImageInfo();
952
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000953 /// EmitModuleInfo - Another marker encoding module level
954 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000955 void EmitModuleInfo();
956
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000957 /// EmitModuleSymols - Emit module symbols, the list of defined
958 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000959 llvm::Constant *EmitModuleSymbols();
960
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000961 /// FinishModule - Write out global data structures at the end of
962 /// processing a translation unit.
963 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000964
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000965 /// EmitClassExtension - Generate the class extension structure used
966 /// to store the weak ivar layout and properties. The return value
967 /// has type ClassExtensionPtrTy.
968 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
969
970 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
971 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000972 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000973 const ObjCInterfaceDecl *ID);
974
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000975 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000976 QualType ResultType,
977 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000978 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000979 QualType Arg0Ty,
980 bool IsSuper,
981 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000982
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000983 /// EmitIvarList - Emit the ivar list for the given
984 /// implementation. If ForClass is true the list of class ivars
985 /// (i.e. metaclass ivars) is emitted, otherwise the list of
986 /// interface ivars will be emitted. The return value has type
987 /// IvarListPtrTy.
988 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000989 bool ForClass);
990
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000991 /// EmitMetaClass - Emit a forward reference to the class structure
992 /// for the metaclass of the given interface. The return value has
993 /// type ClassPtrTy.
994 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
995
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000996 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000997 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000998 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
999 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001000 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001001
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001002 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001003
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001004 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001005
1006 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001007 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001008 llvm::Constant *EmitMethodList(const std::string &Name,
1009 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001010 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001011
1012 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001013 /// method declarations.
1014 /// - TypeName: The name for the type containing the methods.
1015 /// - IsProtocol: True iff these methods are for a protocol.
1016 /// - ClassMethds: True iff these are class methods.
1017 /// - Required: When true, only "required" methods are
1018 /// listed. Similarly, when false only "optional" methods are
1019 /// listed. For classes this should always be true.
1020 /// - begin, end: The method list to output.
1021 ///
1022 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001023 llvm::Constant *EmitMethodDescList(const std::string &Name,
1024 const char *Section,
1025 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001026
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001027 /// GetOrEmitProtocol - Get the protocol object for the given
1028 /// declaration, emitting it if necessary. The return value has type
1029 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001030 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001031
1032 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1033 /// object for the given declaration, emitting it if needed. These
1034 /// forward references will be filled in with empty bodies if no
1035 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001036 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001037
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001038 /// EmitProtocolExtension - Generate the protocol extension
1039 /// structure used to store optional instance and class methods, and
1040 /// protocol properties. The return value has type
1041 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001042 llvm::Constant *
1043 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1044 const ConstantVector &OptInstanceMethods,
1045 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001046
1047 /// EmitProtocolList - Generate the list of referenced
1048 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001049 llvm::Constant *EmitProtocolList(const std::string &Name,
1050 ObjCProtocolDecl::protocol_iterator begin,
1051 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001052
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001053 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1054 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001055 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001056
Fariborz Jahanianda320092009-01-29 19:24:30 +00001057 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001058 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001059
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001060 virtual llvm::Function *ModuleInitFunction();
1061
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001062 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001063 QualType ResultType,
1064 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001065 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001066 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001067 const CallArgList &CallArgs,
1068 const ObjCMethodDecl *Method);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001069
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001070 virtual CodeGen::RValue
1071 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001072 QualType ResultType,
1073 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001074 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001075 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001076 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001077 bool IsClassMessage,
1078 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001079
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001080 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001081 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001082
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001083 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001084
1085 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1086 /// untyped one.
1087 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1088 const ObjCMethodDecl *Method);
1089
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001090 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001091
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001092 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001093
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001094 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001095 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001096
Chris Lattner74391b42009-03-22 21:03:39 +00001097 virtual llvm::Constant *GetPropertyGetFunction();
1098 virtual llvm::Constant *GetPropertySetFunction();
1099 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001100
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001101 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1102 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001103 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1104 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001105 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001106 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001107 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1108 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001109 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1110 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001111 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1112 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001113 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1114 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001115
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001116 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1117 QualType ObjectTy,
1118 llvm::Value *BaseValue,
1119 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001120 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001121 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001122 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001123 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001124};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001125
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001126class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001127private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001128 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001129 llvm::GlobalVariable* ObjCEmptyCacheVar;
1130 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001131
Daniel Dunbar11394522009-04-18 08:51:00 +00001132 /// SuperClassReferences - uniqued super class references.
1133 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1134
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001135 /// MetaClassReferences - uniqued meta class references.
1136 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001137
1138 /// EHTypeReferences - uniqued class ehtype references.
1139 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001140
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001141 /// NonLegacyDispatchMethods - List of methods for which we do *not* generate
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001142 /// legacy messaging dispatch.
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001143 llvm::DenseSet<Selector> NonLegacyDispatchMethods;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001144
1145 /// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001146 /// NonLegacyDispatchMethods; false otherwise.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001147 bool LegacyDispatchedSelector(Selector Sel);
1148
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001149 /// FinishNonFragileABIModule - Write out global data structures at the end of
1150 /// processing a translation unit.
1151 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001152
Daniel Dunbar463b8762009-05-15 21:48:48 +00001153 /// AddModuleClassList - Add the given list of class pointers to the
1154 /// module with the provided symbol and section names.
1155 void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
1156 const char *SymbolName,
1157 const char *SectionName);
1158
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001159 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1160 unsigned InstanceStart,
1161 unsigned InstanceSize,
1162 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001163 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1164 llvm::Constant *IsAGV,
1165 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001166 llvm::Constant *ClassRoGV,
1167 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001168
1169 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1170
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001171 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1172
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001173 /// EmitMethodList - Emit the method list for the given
1174 /// implementation. The return value has type MethodListnfABITy.
1175 llvm::Constant *EmitMethodList(const std::string &Name,
1176 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001177 const ConstantVector &Methods);
1178 /// EmitIvarList - Emit the ivar list for the given
1179 /// implementation. If ForClass is true the list of class ivars
1180 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1181 /// interface ivars will be emitted. The return value has type
1182 /// IvarListnfABIPtrTy.
1183 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001184
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001185 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001186 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001187 unsigned long int offset);
1188
Fariborz Jahanianda320092009-01-29 19:24:30 +00001189 /// GetOrEmitProtocol - Get the protocol object for the given
1190 /// declaration, emitting it if necessary. The return value has type
1191 /// ProtocolPtrTy.
1192 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1193
1194 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1195 /// object for the given declaration, emitting it if needed. These
1196 /// forward references will be filled in with empty bodies if no
1197 /// definition is seen. The return value has type ProtocolPtrTy.
1198 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1199
1200 /// EmitProtocolList - Generate the list of referenced
1201 /// protocols. The return value has type ProtocolListPtrTy.
1202 llvm::Constant *EmitProtocolList(const std::string &Name,
1203 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001204 ObjCProtocolDecl::protocol_iterator end);
1205
1206 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1207 QualType ResultType,
1208 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001209 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001210 QualType Arg0Ty,
1211 bool IsSuper,
1212 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001213
1214 /// GetClassGlobal - Return the global variable for the Objective-C
1215 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001216 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1217
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001218 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001219 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001220 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001221 const ObjCInterfaceDecl *ID);
1222
1223 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1224 /// for the given super class reference.
1225 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1226 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001227
1228 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1229 /// meta-data
1230 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1231 const ObjCInterfaceDecl *ID);
1232
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001233 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1234 /// the given ivar.
1235 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001236 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001237 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001238 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001239
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001240 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1241 /// for the given selector.
1242 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001243
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001244 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001245 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001246 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1247 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001248
1249 const char *getMetaclassSymbolPrefix() const {
1250 return "OBJC_METACLASS_$_";
1251 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001252
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001253 const char *getClassSymbolPrefix() const {
1254 return "OBJC_CLASS_$_";
1255 }
1256
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001257 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001258 uint32_t &InstanceStart,
1259 uint32_t &InstanceSize);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001260
1261 // Shamelessly stolen from Analysis/CFRefCount.cpp
1262 Selector GetNullarySelector(const char* name) {
1263 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1264 return CGM.getContext().Selectors.getSelector(0, &II);
1265 }
1266
1267 Selector GetUnarySelector(const char* name) {
1268 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1269 return CGM.getContext().Selectors.getSelector(1, &II);
1270 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001271
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001272public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001273 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001274 // FIXME. All stubs for now!
1275 virtual llvm::Function *ModuleInitFunction();
1276
1277 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1278 QualType ResultType,
1279 Selector Sel,
1280 llvm::Value *Receiver,
1281 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001282 const CallArgList &CallArgs,
1283 const ObjCMethodDecl *Method);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001284
1285 virtual CodeGen::RValue
1286 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1287 QualType ResultType,
1288 Selector Sel,
1289 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001290 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001291 llvm::Value *Receiver,
1292 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001293 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001294
1295 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001296 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001297
1298 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001299 { return EmitSelector(Builder, Sel); }
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001300
1301 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1302 /// untyped one.
1303 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1304 const ObjCMethodDecl *Method)
1305 { return EmitSelector(Builder, Method->getSelector()); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001306
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001307 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001308
1309 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001310 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001311 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001312
Chris Lattner74391b42009-03-22 21:03:39 +00001313 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001314 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001315 }
Chris Lattner74391b42009-03-22 21:03:39 +00001316 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001317 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001318 }
Chris Lattner74391b42009-03-22 21:03:39 +00001319 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001320 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001321 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001322
1323 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001324 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001325 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001326 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001327 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001328 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001329 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001330 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001331 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001332 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001333 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001334 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001335 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001336 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001337 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1338 QualType ObjectTy,
1339 llvm::Value *BaseValue,
1340 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001341 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001342 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001343 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001344 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001345};
1346
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001347} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001348
1349/* *** Helper Functions *** */
1350
1351/// getConstantGEP() - Help routine to construct simple GEPs.
1352static llvm::Constant *getConstantGEP(llvm::Constant *C,
1353 unsigned idx0,
1354 unsigned idx1) {
1355 llvm::Value *Idxs[] = {
1356 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1357 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1358 };
1359 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1360}
1361
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001362/// hasObjCExceptionAttribute - Return true if this class or any super
1363/// class has the __objc_exception__ attribute.
1364static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001365 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001366 return true;
1367 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1368 return hasObjCExceptionAttribute(Super);
1369 return false;
1370}
1371
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001372/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001373
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001374CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1375 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001376{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001377 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001378 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001379}
1380
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001381/// GetClass - Return a reference to the class for the given interface
1382/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001383llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001384 const ObjCInterfaceDecl *ID) {
1385 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001386}
1387
1388/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001389llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001390 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001391}
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001392llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1393 *Method) {
1394 return EmitSelector(Builder, Method->getSelector());
1395}
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001396
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001397/// Generate a constant CFString object.
1398/*
1399 struct __builtin_CFString {
1400 const int *isa; // point to __CFConstantStringClassReference
1401 int flags;
1402 const char *str;
1403 long length;
1404 };
1405*/
1406
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001407llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001408 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001409 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001410}
1411
1412/// Generates a message send where the super is the receiver. This is
1413/// a message send to self with special delivery semantics indicating
1414/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001415CodeGen::RValue
1416CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001417 QualType ResultType,
1418 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001419 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001420 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001421 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001422 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001423 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001424 // Create and init a super structure; this is a (receiver, class)
1425 // pair we will pass to objc_msgSendSuper.
1426 llvm::Value *ObjCSuper =
1427 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1428 llvm::Value *ReceiverAsObject =
1429 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1430 CGF.Builder.CreateStore(ReceiverAsObject,
1431 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001432
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001433 // If this is a class message the metaclass is passed as the target.
1434 llvm::Value *Target;
1435 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001436 if (isCategoryImpl) {
1437 // Message sent to 'super' in a class method defined in a category
1438 // implementation requires an odd treatment.
1439 // If we are in a class method, we must retrieve the
1440 // _metaclass_ for the current class, pointed at by
1441 // the class's "isa" pointer. The following assumes that
1442 // isa" is the first ivar in a class (which it must be).
1443 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1444 Target = CGF.Builder.CreateStructGEP(Target, 0);
1445 Target = CGF.Builder.CreateLoad(Target);
1446 }
1447 else {
1448 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1449 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1450 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1451 Target = Super;
1452 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001453 } else {
1454 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1455 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001456 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1457 // and ObjCTypes types.
1458 const llvm::Type *ClassTy =
1459 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001460 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001461 CGF.Builder.CreateStore(Target,
1462 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001463 return EmitLegacyMessageSend(CGF, ResultType,
1464 EmitSelector(CGF.Builder, Sel),
1465 ObjCSuper, ObjCTypes.SuperPtrCTy,
1466 true, CallArgs, ObjCTypes);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001467}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001468
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001469/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001470CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001471 QualType ResultType,
1472 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001473 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001474 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001475 const CallArgList &CallArgs,
1476 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001477 return EmitLegacyMessageSend(CGF, ResultType,
1478 EmitSelector(CGF.Builder, Sel),
1479 Receiver, CGF.getContext().getObjCIdType(),
1480 false, CallArgs, ObjCTypes);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001481}
1482
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001483CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1484 CodeGen::CodeGenFunction &CGF,
1485 QualType ResultType,
1486 llvm::Value *Sel,
1487 llvm::Value *Arg0,
1488 QualType Arg0Ty,
1489 bool IsSuper,
1490 const CallArgList &CallArgs,
1491 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001492 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001493 if (!IsSuper)
1494 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001495 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001496 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001497 CGF.getContext().getObjCSelType()));
1498 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001499
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001500 CodeGenTypes &Types = CGM.getTypes();
1501 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001502 // In 64bit ABI, type must be assumed VARARG. In 32bit abi,
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001503 // it seems not to matter.
1504 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1505
1506 llvm::Constant *Fn = NULL;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001507 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001508 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1509 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001510 } else if (ResultType->isFloatingType()) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001511 if (ObjCABI == 2) {
1512 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1513 BuiltinType::Kind k = BT->getKind();
1514 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1515 : ObjCTypes.getSendFn2(IsSuper);
1516 }
1517 }
1518 else
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001519 // FIXME. This currently matches gcc's API for x86-32. May need
1520 // to change for others if we have their API.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001521 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001522 } else {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001523 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1524 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001525 }
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001526 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001527 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001528 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001529}
1530
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001531llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001532 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001533 // FIXME: I don't understand why gcc generates this, or where it is
1534 // resolved. Investigate. Its also wasteful to look this up over and
1535 // over.
1536 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1537
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001538 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1539 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001540}
1541
Fariborz Jahanianda320092009-01-29 19:24:30 +00001542void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001543 // FIXME: We shouldn't need this, the protocol decl should contain
1544 // enough information to tell us whether this was a declaration or a
1545 // definition.
1546 DefinedProtocols.insert(PD->getIdentifier());
1547
1548 // If we have generated a forward reference to this protocol, emit
1549 // it now. Otherwise do nothing, the protocol objects are lazily
1550 // emitted.
1551 if (Protocols.count(PD->getIdentifier()))
1552 GetOrEmitProtocol(PD);
1553}
1554
Fariborz Jahanianda320092009-01-29 19:24:30 +00001555llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001556 if (DefinedProtocols.count(PD->getIdentifier()))
1557 return GetOrEmitProtocol(PD);
1558 return GetOrEmitProtocolRef(PD);
1559}
1560
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001561/*
1562 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1563 struct _objc_protocol {
1564 struct _objc_protocol_extension *isa;
1565 char *protocol_name;
1566 struct _objc_protocol_list *protocol_list;
1567 struct _objc__method_prototype_list *instance_methods;
1568 struct _objc__method_prototype_list *class_methods
1569 };
1570
1571 See EmitProtocolExtension().
1572*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001573llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1574 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1575
1576 // Early exit if a defining object has already been generated.
1577 if (Entry && Entry->hasInitializer())
1578 return Entry;
1579
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001580 // FIXME: I don't understand why gcc generates this, or where it is
1581 // resolved. Investigate. Its also wasteful to look this up over and
1582 // over.
1583 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1584
Chris Lattner8ec03f52008-11-24 03:54:41 +00001585 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001586
1587 // Construct method lists.
1588 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1589 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001590 for (ObjCProtocolDecl::instmeth_iterator
1591 i = PD->instmeth_begin(CGM.getContext()),
1592 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001593 ObjCMethodDecl *MD = *i;
1594 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1595 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1596 OptInstanceMethods.push_back(C);
1597 } else {
1598 InstanceMethods.push_back(C);
1599 }
1600 }
1601
Douglas Gregor6ab35242009-04-09 21:40:53 +00001602 for (ObjCProtocolDecl::classmeth_iterator
1603 i = PD->classmeth_begin(CGM.getContext()),
1604 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001605 ObjCMethodDecl *MD = *i;
1606 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1607 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1608 OptClassMethods.push_back(C);
1609 } else {
1610 ClassMethods.push_back(C);
1611 }
1612 }
1613
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001614 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001615 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001616 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001617 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001618 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001619 PD->protocol_begin(),
1620 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001621 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001622 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1623 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001624 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1625 InstanceMethods);
1626 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001627 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1628 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001629 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1630 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001631 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1632 Values);
1633
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001634 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001635 // Already created, fix the linkage and update the initializer.
1636 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001637 Entry->setInitializer(Init);
1638 } else {
1639 Entry =
1640 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1641 llvm::GlobalValue::InternalLinkage,
1642 Init,
1643 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1644 &CGM.getModule());
1645 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001646 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001647 UsedGlobals.push_back(Entry);
1648 // FIXME: Is this necessary? Why only for protocol?
1649 Entry->setAlignment(4);
1650 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001651
1652 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001653}
1654
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001655llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001656 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1657
1658 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001659 // We use the initializer as a marker of whether this is a forward
1660 // reference or not. At module finalization we add the empty
1661 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001662 Entry =
1663 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001664 llvm::GlobalValue::ExternalLinkage,
1665 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001666 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001667 &CGM.getModule());
1668 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001669 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001670 UsedGlobals.push_back(Entry);
1671 // FIXME: Is this necessary? Why only for protocol?
1672 Entry->setAlignment(4);
1673 }
1674
1675 return Entry;
1676}
1677
1678/*
1679 struct _objc_protocol_extension {
1680 uint32_t size;
1681 struct objc_method_description_list *optional_instance_methods;
1682 struct objc_method_description_list *optional_class_methods;
1683 struct objc_property_list *instance_properties;
1684 };
1685*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001686llvm::Constant *
1687CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1688 const ConstantVector &OptInstanceMethods,
1689 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001690 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001691 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001692 std::vector<llvm::Constant*> Values(4);
1693 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001694 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001695 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1696 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001697 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1698 OptInstanceMethods);
1699 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001700 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1701 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001702 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1703 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001704 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1705 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001706 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001707
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001708 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001709 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1710 Values[3]->isNullValue())
1711 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1712
1713 llvm::Constant *Init =
1714 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001715
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001716 // No special section, but goes in llvm.used
1717 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1718 Init,
1719 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001720}
1721
1722/*
1723 struct objc_protocol_list {
1724 struct objc_protocol_list *next;
1725 long count;
1726 Protocol *list[];
1727 };
1728*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001729llvm::Constant *
1730CGObjCMac::EmitProtocolList(const std::string &Name,
1731 ObjCProtocolDecl::protocol_iterator begin,
1732 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001733 std::vector<llvm::Constant*> ProtocolRefs;
1734
Daniel Dunbardbc933702008-08-21 21:57:41 +00001735 for (; begin != end; ++begin)
1736 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001737
1738 // Just return null for empty protocol lists
1739 if (ProtocolRefs.empty())
1740 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1741
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001742 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001743 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1744
1745 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001746 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001747 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1748 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1749 Values[2] =
1750 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1751 ProtocolRefs.size()),
1752 ProtocolRefs);
1753
1754 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1755 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001756 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001757 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001758 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1759}
1760
1761/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001762 struct _objc_property {
1763 const char * const name;
1764 const char * const attributes;
1765 };
1766
1767 struct _objc_property_list {
1768 uint32_t entsize; // sizeof (struct _objc_property)
1769 uint32_t prop_count;
1770 struct _objc_property[prop_count];
1771 };
1772*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001773llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1774 const Decl *Container,
1775 const ObjCContainerDecl *OCD,
1776 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001777 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001778 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1779 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001780 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001781 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001782 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001783 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1784 Prop));
1785 }
1786
1787 // Return null for empty list.
1788 if (Properties.empty())
1789 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1790
1791 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001792 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001793 std::vector<llvm::Constant*> Values(3);
1794 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1795 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1796 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1797 Properties.size());
1798 Values[2] = llvm::ConstantArray::get(AT, Properties);
1799 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1800
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001801 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001802 CreateMetadataVar(Name, Init,
1803 (ObjCABI == 2) ? "__DATA, __objc_const" :
1804 "__OBJC,__property,regular,no_dead_strip",
1805 (ObjCABI == 2) ? 8 : 4,
1806 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001807 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001808}
1809
1810/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001811 struct objc_method_description_list {
1812 int count;
1813 struct objc_method_description list[];
1814 };
1815*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001816llvm::Constant *
1817CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1818 std::vector<llvm::Constant*> Desc(2);
1819 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1820 ObjCTypes.SelectorPtrTy);
1821 Desc[1] = GetMethodVarType(MD);
1822 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1823 Desc);
1824}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001825
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001826llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1827 const char *Section,
1828 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001829 // Return null for empty list.
1830 if (Methods.empty())
1831 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1832
1833 std::vector<llvm::Constant*> Values(2);
1834 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1835 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1836 Methods.size());
1837 Values[1] = llvm::ConstantArray::get(AT, Methods);
1838 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1839
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001840 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001841 return llvm::ConstantExpr::getBitCast(GV,
1842 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001843}
1844
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001845/*
1846 struct _objc_category {
1847 char *category_name;
1848 char *class_name;
1849 struct _objc_method_list *instance_methods;
1850 struct _objc_method_list *class_methods;
1851 struct _objc_protocol_list *protocols;
1852 uint32_t size; // <rdar://4585769>
1853 struct _objc_property_list *instance_properties;
1854 };
1855 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001856void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001857 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001858
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001859 // FIXME: This is poor design, the OCD should have a pointer to the
1860 // category decl. Additionally, note that Category can be null for
1861 // the @implementation w/o an @interface case. Sema should just
1862 // create one for us as it does for @implementation so everyone else
1863 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001864 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001865 const ObjCCategoryDecl *Category =
1866 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001867 std::string ExtName(Interface->getNameAsString() + "_" +
1868 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001869
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001870 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001871 for (ObjCCategoryImplDecl::instmeth_iterator
1872 i = OCD->instmeth_begin(CGM.getContext()),
1873 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001874 // Instance methods should always be defined.
1875 InstanceMethods.push_back(GetMethodConstant(*i));
1876 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001877 for (ObjCCategoryImplDecl::classmeth_iterator
1878 i = OCD->classmeth_begin(CGM.getContext()),
1879 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001880 // Class methods should always be defined.
1881 ClassMethods.push_back(GetMethodConstant(*i));
1882 }
1883
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001884 std::vector<llvm::Constant*> Values(7);
1885 Values[0] = GetClassName(OCD->getIdentifier());
1886 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001887 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001888 Values[2] =
1889 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1890 ExtName,
1891 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001892 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001893 Values[3] =
1894 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001895 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001896 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001897 if (Category) {
1898 Values[4] =
1899 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1900 Category->protocol_begin(),
1901 Category->protocol_end());
1902 } else {
1903 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1904 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001905 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001906
1907 // If there is no category @interface then there can be no properties.
1908 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001909 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001910 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001911 } else {
1912 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1913 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001914
1915 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1916 Values);
1917
1918 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001919 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1920 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001921 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001922 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001923}
1924
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001925// FIXME: Get from somewhere?
1926enum ClassFlags {
1927 eClassFlags_Factory = 0x00001,
1928 eClassFlags_Meta = 0x00002,
1929 // <rdr://5142207>
1930 eClassFlags_HasCXXStructors = 0x02000,
1931 eClassFlags_Hidden = 0x20000,
1932 eClassFlags_ABI2_Hidden = 0x00010,
1933 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1934};
1935
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001936/*
1937 struct _objc_class {
1938 Class isa;
1939 Class super_class;
1940 const char *name;
1941 long version;
1942 long info;
1943 long instance_size;
1944 struct _objc_ivar_list *ivars;
1945 struct _objc_method_list *methods;
1946 struct _objc_cache *cache;
1947 struct _objc_protocol_list *protocols;
1948 // Objective-C 1.0 extensions (<rdr://4585769>)
1949 const char *ivar_layout;
1950 struct _objc_class_ext *ext;
1951 };
1952
1953 See EmitClassExtension();
1954 */
1955void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001956 DefinedSymbols.insert(ID->getIdentifier());
1957
Chris Lattner8ec03f52008-11-24 03:54:41 +00001958 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001959 // FIXME: Gross
1960 ObjCInterfaceDecl *Interface =
1961 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001962 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001963 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001964 Interface->protocol_begin(),
1965 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001966 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001967 unsigned Size =
1968 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001969
1970 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001971 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001972 Flags |= eClassFlags_Hidden;
1973
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001974 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001975 for (ObjCImplementationDecl::instmeth_iterator
1976 i = ID->instmeth_begin(CGM.getContext()),
1977 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001978 // Instance methods should always be defined.
1979 InstanceMethods.push_back(GetMethodConstant(*i));
1980 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001981 for (ObjCImplementationDecl::classmeth_iterator
1982 i = ID->classmeth_begin(CGM.getContext()),
1983 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001984 // Class methods should always be defined.
1985 ClassMethods.push_back(GetMethodConstant(*i));
1986 }
1987
Douglas Gregor653f1b12009-04-23 01:02:12 +00001988 for (ObjCImplementationDecl::propimpl_iterator
1989 i = ID->propimpl_begin(CGM.getContext()),
1990 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001991 ObjCPropertyImplDecl *PID = *i;
1992
1993 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1994 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1995
1996 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1997 if (llvm::Constant *C = GetMethodConstant(MD))
1998 InstanceMethods.push_back(C);
1999 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
2000 if (llvm::Constant *C = GetMethodConstant(MD))
2001 InstanceMethods.push_back(C);
2002 }
2003 }
2004
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002005 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00002006 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002007 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002008 // Record a reference to the super class.
2009 LazySymbols.insert(Super->getIdentifier());
2010
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002011 Values[ 1] =
2012 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2013 ObjCTypes.ClassPtrTy);
2014 } else {
2015 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2016 }
2017 Values[ 2] = GetClassName(ID->getIdentifier());
2018 // Version is always 0.
2019 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2020 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2021 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002022 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002023 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002024 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002025 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002026 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002027 // cache is always NULL.
2028 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2029 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002030 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002031 Values[11] = EmitClassExtension(ID);
2032 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2033 Values);
2034
2035 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002036 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2037 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002038 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002039 DefinedClasses.push_back(GV);
2040}
2041
2042llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2043 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002044 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002045 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002046 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002047
Daniel Dunbar04d40782009-04-14 06:00:08 +00002048 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002049 Flags |= eClassFlags_Hidden;
2050
2051 std::vector<llvm::Constant*> Values(12);
2052 // The isa for the metaclass is the root of the hierarchy.
2053 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2054 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2055 Root = Super;
2056 Values[ 0] =
2057 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2058 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002059 // The super class for the metaclass is emitted as the name of the
2060 // super class. The runtime fixes this up to point to the
2061 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002062 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2063 Values[ 1] =
2064 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2065 ObjCTypes.ClassPtrTy);
2066 } else {
2067 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2068 }
2069 Values[ 2] = GetClassName(ID->getIdentifier());
2070 // Version is always 0.
2071 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2072 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2073 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002074 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002075 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002076 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002077 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002078 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002079 // cache is always NULL.
2080 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2081 Values[ 9] = Protocols;
2082 // ivar_layout for metaclass is always NULL.
2083 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2084 // The class extension is always unused for metaclasses.
2085 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2086 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2087 Values);
2088
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002089 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002090 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002091
2092 // Check for a forward reference.
2093 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2094 if (GV) {
2095 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2096 "Forward metaclass reference has incorrect type.");
2097 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2098 GV->setInitializer(Init);
2099 } else {
2100 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2101 llvm::GlobalValue::InternalLinkage,
2102 Init, Name,
2103 &CGM.getModule());
2104 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002106 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002107 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002108
2109 return GV;
2110}
2111
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002112llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002113 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002114
2115 // FIXME: Should we look these up somewhere other than the
2116 // module. Its a bit silly since we only generate these while
2117 // processing an implementation, so exactly one pointer would work
2118 // if know when we entered/exitted an implementation block.
2119
2120 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002121 // Previously, metaclass with internal linkage may have been defined.
2122 // pass 'true' as 2nd argument so it is returned.
2123 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002124 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2125 "Forward metaclass reference has incorrect type.");
2126 return GV;
2127 } else {
2128 // Generate as an external reference to keep a consistent
2129 // module. This will be patched up when we emit the metaclass.
2130 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2131 llvm::GlobalValue::ExternalLinkage,
2132 0,
2133 Name,
2134 &CGM.getModule());
2135 }
2136}
2137
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002138/*
2139 struct objc_class_ext {
2140 uint32_t size;
2141 const char *weak_ivar_layout;
2142 struct _objc_property_list *properties;
2143 };
2144*/
2145llvm::Constant *
2146CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2147 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002148 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002149
2150 std::vector<llvm::Constant*> Values(3);
2151 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002152 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002153 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002154 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002155
2156 // Return null if no extension bits are used.
2157 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2158 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2159
2160 llvm::Constant *Init =
2161 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002162 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002163 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2164 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002165}
2166
2167/*
2168 struct objc_ivar {
2169 char *ivar_name;
2170 char *ivar_type;
2171 int ivar_offset;
2172 };
2173
2174 struct objc_ivar_list {
2175 int ivar_count;
2176 struct objc_ivar list[count];
2177 };
2178 */
2179llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002180 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002181 std::vector<llvm::Constant*> Ivars, Ivar(3);
2182
2183 // When emitting the root class GCC emits ivar entries for the
2184 // actual class structure. It is not clear if we need to follow this
2185 // behavior; for now lets try and get away with not doing it. If so,
2186 // the cleanest solution would be to make up an ObjCInterfaceDecl
2187 // for the class.
2188 if (ForClass)
2189 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002190
2191 ObjCInterfaceDecl *OID =
2192 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002193
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002194 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2195 GetNamedIvarList(OID, OIvars);
2196
2197 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2198 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002199 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2200 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002201 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002202 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002203 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002204 }
2205
2206 // Return null for empty list.
2207 if (Ivars.empty())
2208 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2209
2210 std::vector<llvm::Constant*> Values(2);
2211 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2212 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2213 Ivars.size());
2214 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2215 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2216
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002217 llvm::GlobalVariable *GV;
2218 if (ForClass)
2219 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002220 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2221 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002222 else
2223 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2224 + ID->getNameAsString(),
2225 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002226 4, true);
2227 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002228}
2229
2230/*
2231 struct objc_method {
2232 SEL method_name;
2233 char *method_types;
2234 void *method;
2235 };
2236
2237 struct objc_method_list {
2238 struct objc_method_list *obsolete;
2239 int count;
2240 struct objc_method methods_list[count];
2241 };
2242*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002243
2244/// GetMethodConstant - Return a struct objc_method constant for the
2245/// given method if it has been defined. The result is null if the
2246/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002247llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002248 // FIXME: Use DenseMap::lookup
2249 llvm::Function *Fn = MethodDefinitions[MD];
2250 if (!Fn)
2251 return 0;
2252
2253 std::vector<llvm::Constant*> Method(3);
2254 Method[0] =
2255 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2256 ObjCTypes.SelectorPtrTy);
2257 Method[1] = GetMethodVarType(MD);
2258 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2259 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2260}
2261
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002262llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2263 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002264 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002265 // Return null for empty list.
2266 if (Methods.empty())
2267 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2268
2269 std::vector<llvm::Constant*> Values(3);
2270 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2271 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2272 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2273 Methods.size());
2274 Values[2] = llvm::ConstantArray::get(AT, Methods);
2275 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2276
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002277 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002278 return llvm::ConstantExpr::getBitCast(GV,
2279 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002280}
2281
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002282llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002283 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002284 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002285 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002286
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002287 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002288 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002289 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002290 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002291 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002292 llvm::GlobalValue::InternalLinkage,
2293 Name,
2294 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002295 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002296
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002297 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002298}
2299
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002300llvm::GlobalVariable *
2301CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2302 llvm::Constant *Init,
2303 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002304 unsigned Align,
2305 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002306 const llvm::Type *Ty = Init->getType();
2307 llvm::GlobalVariable *GV =
2308 new llvm::GlobalVariable(Ty, false,
2309 llvm::GlobalValue::InternalLinkage,
2310 Init,
2311 Name,
2312 &CGM.getModule());
2313 if (Section)
2314 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002315 if (Align)
2316 GV->setAlignment(Align);
2317 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002318 UsedGlobals.push_back(GV);
2319 return GV;
2320}
2321
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002322llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002323 // Abuse this interface function as a place to finalize.
2324 FinishModule();
2325
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002326 return NULL;
2327}
2328
Chris Lattner74391b42009-03-22 21:03:39 +00002329llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002330 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002331}
2332
Chris Lattner74391b42009-03-22 21:03:39 +00002333llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002334 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002335}
2336
Chris Lattner74391b42009-03-22 21:03:39 +00002337llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002338 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002339}
2340
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002341/*
2342
2343Objective-C setjmp-longjmp (sjlj) Exception Handling
2344--
2345
2346The basic framework for a @try-catch-finally is as follows:
2347{
2348 objc_exception_data d;
2349 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002350 bool _call_try_exit = true;
2351
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002352 objc_exception_try_enter(&d);
2353 if (!setjmp(d.jmp_buf)) {
2354 ... try body ...
2355 } else {
2356 // exception path
2357 id _caught = objc_exception_extract(&d);
2358
2359 // enter new try scope for handlers
2360 if (!setjmp(d.jmp_buf)) {
2361 ... match exception and execute catch blocks ...
2362
2363 // fell off end, rethrow.
2364 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002365 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002366 } else {
2367 // exception in catch block
2368 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002369 _call_try_exit = false;
2370 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002371 }
2372 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002373 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002374
2375finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002376 if (_call_try_exit)
2377 objc_exception_try_exit(&d);
2378
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002379 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002380 ... dispatch to finally destination ...
2381
2382finally_rethrow:
2383 objc_exception_throw(_rethrow);
2384
2385finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002386}
2387
2388This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002389uses _rethrow to determine if objc_exception_try_exit should be called
2390and if the object should be rethrown. This breaks in the face of
2391throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002392
2393We specialize this framework for a few particular circumstances:
2394
2395 - If there are no catch blocks, then we avoid emitting the second
2396 exception handling context.
2397
2398 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2399 e)) we avoid emitting the code to rethrow an uncaught exception.
2400
2401 - FIXME: If there is no @finally block we can do a few more
2402 simplifications.
2403
2404Rethrows and Jumps-Through-Finally
2405--
2406
2407Support for implicit rethrows and jumping through the finally block is
2408handled by storing the current exception-handling context in
2409ObjCEHStack.
2410
Daniel Dunbar898d5082008-09-30 01:06:03 +00002411In order to implement proper @finally semantics, we support one basic
2412mechanism for jumping through the finally block to an arbitrary
2413destination. Constructs which generate exits from a @try or @catch
2414block use this mechanism to implement the proper semantics by chaining
2415jumps, as necessary.
2416
2417This mechanism works like the one used for indirect goto: we
2418arbitrarily assign an ID to each destination and store the ID for the
2419destination in a variable prior to entering the finally block. At the
2420end of the finally block we simply create a switch to the proper
2421destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002422
2423Code gen for @synchronized(expr) stmt;
2424Effectively generating code for:
2425objc_sync_enter(expr);
2426@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002427*/
2428
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002429void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2430 const Stmt &S) {
2431 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002432 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002433 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002434 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002435 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2436 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2437 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002438
2439 // For @synchronized, call objc_sync_enter(sync.expr). The
2440 // evaluation of the expression must occur before we enter the
2441 // @synchronized. We can safely avoid a temp here because jumps into
2442 // @synchronized are illegal & this will dominate uses.
2443 llvm::Value *SyncArg = 0;
2444 if (!isTry) {
2445 SyncArg =
2446 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2447 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002448 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002449 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002450
2451 // Push an EH context entry, used for handling rethrows and jumps
2452 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002453 CGF.PushCleanupBlock(FinallyBlock);
2454
Anders Carlsson273558f2009-02-07 21:37:21 +00002455 CGF.ObjCEHValueStack.push_back(0);
2456
Daniel Dunbar898d5082008-09-30 01:06:03 +00002457 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002458 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2459 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002460 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2461 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002462 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2463 "_call_try_exit");
2464 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2465
Anders Carlsson80f25672008-09-09 17:59:25 +00002466 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002467 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002468 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2469 "jmpbufarray");
2470 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002471 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002472 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002473
Daniel Dunbar55e87422008-11-11 02:29:29 +00002474 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2475 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002476 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002477 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002478
2479 // Emit the @try block.
2480 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002481 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2482 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002483 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002484
2485 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002486 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002487
2488 // Retrieve the exception object. We may emit multiple blocks but
2489 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002490 llvm::Value *Caught =
2491 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2492 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002493 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002494 if (!isTry)
2495 {
2496 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002497 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002498 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002499 }
2500 else if (const ObjCAtCatchStmt* CatchStmt =
2501 cast<ObjCAtTryStmt>(S).getCatchStmts())
2502 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002503 // Enter a new exception try block (in case a @catch block throws
2504 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002505 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002506
Chris Lattner34b02a12009-04-22 02:26:14 +00002507 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002508 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002509 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002510
Daniel Dunbar55e87422008-11-11 02:29:29 +00002511 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2512 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002513 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002514
2515 CGF.EmitBlock(CatchBlock);
2516
Daniel Dunbar55e40722008-09-27 07:03:52 +00002517 // Handle catch list. As a special case we check if everything is
2518 // matched and avoid generating code for falling off the end if
2519 // so.
2520 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002521 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002522 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002523
Steve Naroff7ba138a2009-03-03 19:52:17 +00002524 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002525 const PointerType *PT = 0;
2526
Anders Carlsson80f25672008-09-09 17:59:25 +00002527 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002528 if (!CatchParam) {
2529 AllMatched = true;
2530 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002531 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002532
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002533 // catch(id e) always matches.
2534 // FIXME: For the time being we also match id<X>; this should
2535 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002536 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002537 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002538 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002539 }
2540
Daniel Dunbar55e40722008-09-27 07:03:52 +00002541 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002542 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002543 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002544 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002545 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002546 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002547
Anders Carlssondde0a942008-09-11 09:15:33 +00002548 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002549 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002550 break;
2551 }
2552
Daniel Dunbar129271a2008-09-27 07:36:24 +00002553 assert(PT && "Unexpected non-pointer type in @catch");
2554 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002555 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002556 assert(ObjCType && "Catch parameter must have Objective-C type!");
2557
2558 // Check if the @catch block matches the exception object.
2559 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2560
Chris Lattner34b02a12009-04-22 02:26:14 +00002561 llvm::Value *Match =
2562 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2563 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002564
Daniel Dunbar55e87422008-11-11 02:29:29 +00002565 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002566
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002567 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002568 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002569
2570 // Emit the @catch block.
2571 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002572 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002573 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002574
2575 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002576 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002577 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002578 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002579
2580 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002581 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002582
2583 CGF.EmitBlock(NextCatchBlock);
2584 }
2585
Daniel Dunbar55e40722008-09-27 07:03:52 +00002586 if (!AllMatched) {
2587 // None of the handlers caught the exception, so store it to be
2588 // rethrown at the end of the @finally block.
2589 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002590 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002591 }
2592
2593 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002594 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002595 CGF.Builder.CreateStore(
2596 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2597 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002598 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002599 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002600 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002601 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002602 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002603 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002604 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002605 }
2606
Daniel Dunbar898d5082008-09-30 01:06:03 +00002607 // Pop the exception-handling stack entry. It is important to do
2608 // this now, because the code in the @finally block is not in this
2609 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002610 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2611
Anders Carlsson273558f2009-02-07 21:37:21 +00002612 CGF.ObjCEHValueStack.pop_back();
2613
Anders Carlsson80f25672008-09-09 17:59:25 +00002614 // Emit the @finally block.
2615 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002616 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2617
2618 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2619
2620 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002621 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002622
2623 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002624 if (isTry) {
2625 if (const ObjCAtFinallyStmt* FinallyStmt =
2626 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2627 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002628 } else {
2629 // Emit objc_sync_exit(expr); as finally's sole statement for
2630 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002631 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002632 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002633
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002634 // Emit the switch block
2635 if (Info.SwitchBlock)
2636 CGF.EmitBlock(Info.SwitchBlock);
2637 if (Info.EndBlock)
2638 CGF.EmitBlock(Info.EndBlock);
2639
Daniel Dunbar898d5082008-09-30 01:06:03 +00002640 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002641 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002642 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002643 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002644
2645 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002646}
2647
2648void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002649 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002650 llvm::Value *ExceptionAsObject;
2651
2652 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2653 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2654 ExceptionAsObject =
2655 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2656 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002657 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002658 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002659 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002660 }
2661
Chris Lattnerbbccd612009-04-22 02:38:11 +00002662 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002663 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002664
2665 // Clear the insertion point to indicate we are in unreachable code.
2666 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002667}
2668
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002669/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002670/// object: objc_read_weak (id *src)
2671///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002672llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002673 llvm::Value *AddrWeakObj)
2674{
Eli Friedman8339b352009-03-07 03:57:15 +00002675 const llvm::Type* DestTy =
2676 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002677 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002678 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002679 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002680 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002681 return read_weak;
2682}
2683
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002684/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2685/// objc_assign_weak (id src, id *dst)
2686///
2687void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2688 llvm::Value *src, llvm::Value *dst)
2689{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002690 const llvm::Type * SrcTy = src->getType();
2691 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002692 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002693 assert(Size <= 8 && "does not support size > 8");
2694 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2695 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002696 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2697 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002698 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2699 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002700 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002701 src, dst, "weakassign");
2702 return;
2703}
2704
Fariborz Jahanian58626502008-11-19 00:59:10 +00002705/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2706/// objc_assign_global (id src, id *dst)
2707///
2708void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2709 llvm::Value *src, llvm::Value *dst)
2710{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002711 const llvm::Type * SrcTy = src->getType();
2712 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002713 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002714 assert(Size <= 8 && "does not support size > 8");
2715 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2716 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002717 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2718 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002719 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2720 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002721 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002722 src, dst, "globalassign");
2723 return;
2724}
2725
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002726/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2727/// objc_assign_ivar (id src, id *dst)
2728///
2729void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2730 llvm::Value *src, llvm::Value *dst)
2731{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002732 const llvm::Type * SrcTy = src->getType();
2733 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002734 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002735 assert(Size <= 8 && "does not support size > 8");
2736 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2737 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002738 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2739 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002740 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2741 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002742 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002743 src, dst, "assignivar");
2744 return;
2745}
2746
Fariborz Jahanian58626502008-11-19 00:59:10 +00002747/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2748/// objc_assign_strongCast (id src, id *dst)
2749///
2750void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2751 llvm::Value *src, llvm::Value *dst)
2752{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002753 const llvm::Type * SrcTy = src->getType();
2754 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002755 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002756 assert(Size <= 8 && "does not support size > 8");
2757 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2758 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002759 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2760 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002761 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2762 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002763 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002764 src, dst, "weakassign");
2765 return;
2766}
2767
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002768/// EmitObjCValueForIvar - Code Gen for ivar reference.
2769///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002770LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2771 QualType ObjectTy,
2772 llvm::Value *BaseValue,
2773 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002774 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002775 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002776 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2777 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002778}
2779
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002780llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002781 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002782 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002783 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002784 return llvm::ConstantInt::get(
2785 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2786 Offset);
2787}
2788
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002789/* *** Private Interface *** */
2790
2791/// EmitImageInfo - Emit the image info marker used to encode some module
2792/// level information.
2793///
2794/// See: <rdr://4810609&4810587&4810587>
2795/// struct IMAGE_INFO {
2796/// unsigned version;
2797/// unsigned flags;
2798/// };
2799enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002800 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2801 // this implies.
2802 eImageInfo_GarbageCollected = (1 << 1),
2803 eImageInfo_GCOnly = (1 << 2),
2804 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2805
2806 // A flag indicating that the module has no instances of an
2807 // @synthesize of a superclass variable. <rdar://problem/6803242>
2808 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002809};
2810
2811void CGObjCMac::EmitImageInfo() {
2812 unsigned version = 0; // Version is unused?
2813 unsigned flags = 0;
2814
2815 // FIXME: Fix and continue?
2816 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2817 flags |= eImageInfo_GarbageCollected;
2818 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2819 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002820
2821 // We never allow @synthesize of a superclass property.
2822 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002823
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002824 // Emitted as int[2];
2825 llvm::Constant *values[2] = {
2826 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2827 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2828 };
2829 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002830
2831 const char *Section;
2832 if (ObjCABI == 1)
2833 Section = "__OBJC, __image_info,regular";
2834 else
2835 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002836 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002837 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2838 llvm::ConstantArray::get(AT, values, 2),
2839 Section,
2840 0,
2841 true);
2842 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002843}
2844
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002845
2846// struct objc_module {
2847// unsigned long version;
2848// unsigned long size;
2849// const char *name;
2850// Symtab symtab;
2851// };
2852
2853// FIXME: Get from somewhere
2854static const int ModuleVersion = 7;
2855
2856void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002857 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002858
2859 std::vector<llvm::Constant*> Values(4);
2860 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2861 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002862 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002863 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002864 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002865 CreateMetadataVar("\01L_OBJC_MODULES",
2866 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2867 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002868 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002869}
2870
2871llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002872 unsigned NumClasses = DefinedClasses.size();
2873 unsigned NumCategories = DefinedCategories.size();
2874
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002875 // Return null if no symbols were defined.
2876 if (!NumClasses && !NumCategories)
2877 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2878
2879 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002880 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2881 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2882 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2883 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2884
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002885 // The runtime expects exactly the list of defined classes followed
2886 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002887 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002888 for (unsigned i=0; i<NumClasses; i++)
2889 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2890 ObjCTypes.Int8PtrTy);
2891 for (unsigned i=0; i<NumCategories; i++)
2892 Symbols[NumClasses + i] =
2893 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2894 ObjCTypes.Int8PtrTy);
2895
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002896 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002897 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002898 NumClasses + NumCategories),
2899 Symbols);
2900
2901 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2902
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002903 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002904 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2905 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002906 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002907 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2908}
2909
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002910llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002911 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002912 LazySymbols.insert(ID->getIdentifier());
2913
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002914 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2915
2916 if (!Entry) {
2917 llvm::Constant *Casted =
2918 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2919 ObjCTypes.ClassPtrTy);
2920 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002921 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2922 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002923 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002924 }
2925
2926 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002927}
2928
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002929llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002930 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2931
2932 if (!Entry) {
2933 llvm::Constant *Casted =
2934 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2935 ObjCTypes.SelectorPtrTy);
2936 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002937 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2938 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002939 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002940 }
2941
2942 return Builder.CreateLoad(Entry, false, "tmp");
2943}
2944
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002945llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002946 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002947
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002948 if (!Entry)
2949 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2950 llvm::ConstantArray::get(Ident->getName()),
2951 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002952 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002953
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002954 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002955}
2956
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002957/// GetIvarLayoutName - Returns a unique constant for the given
2958/// ivar layout bitmap.
2959llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2960 const ObjCCommonTypesHelper &ObjCTypes) {
2961 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2962}
2963
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002964static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2965 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002966 if (FQT.isObjCGCStrong())
2967 return QualType::Strong;
2968
2969 if (FQT.isObjCGCWeak())
2970 return QualType::Weak;
2971
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002972 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002973 return QualType::Strong;
2974
2975 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002976 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002977
2978 return QualType::GCNone;
2979}
2980
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002981void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2982 unsigned int BytePos,
2983 bool ForStrongLayout,
2984 bool &HasUnion) {
2985 const RecordDecl *RD = RT->getDecl();
2986 // FIXME - Use iterator.
2987 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2988 RD->field_end(CGM.getContext()));
2989 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2990 const llvm::StructLayout *RecLayout =
2991 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2992
2993 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2994 ForStrongLayout, HasUnion);
2995}
2996
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002997void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002998 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002999 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00003000 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003001 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003002 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003003 bool IsUnion = (RD && RD->isUnion());
3004 uint64_t MaxUnionIvarSize = 0;
3005 uint64_t MaxSkippedUnionIvarSize = 0;
3006 FieldDecl *MaxField = 0;
3007 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003008 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003009 uint64_t MaxFieldOffset = 0;
3010 uint64_t MaxSkippedFieldOffset = 0;
3011 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003012
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003013 if (RecFields.empty())
3014 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003015 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3016 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3017
Chris Lattnerf1690852009-03-31 08:48:01 +00003018 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003019 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003020 uint64_t FieldOffset;
3021 if (RD)
3022 FieldOffset =
3023 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3024 else
3025 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003026
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003027 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003028 if (!Field->getIdentifier() || Field->isBitField()) {
3029 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003030 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003031 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003032 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003033
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003034 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003035 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003036 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003037 if (FQT->isUnionType())
3038 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003039
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003040 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003041 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003042 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003043 continue;
3044 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003045
3046 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003047 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 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003050 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003051 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003052 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3053 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003054 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003055 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003056 FQT = CArray->getElementType();
3057 }
3058
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003059 assert(!FQT->isUnionType() &&
3060 "layout for array of unions not supported");
3061 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003062 int OldIndex = IvarsInfo.size() - 1;
3063 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003064
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003065 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003066 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003067 ForStrongLayout, HasUnion);
3068
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003069 // Replicate layout information for each array element. Note that
3070 // one element is already done.
3071 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003072 for (int FirstIndex = IvarsInfo.size() - 1,
3073 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003074 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003075 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3076 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3077 IvarsInfo[i].ivar_size));
3078 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3079 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3080 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003081 }
3082 continue;
3083 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003084 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003085 // At this point, we are done with Record/Union and array there of.
3086 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003087 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003088
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003089 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003090 if ((ForStrongLayout && GCAttr == QualType::Strong)
3091 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003092 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003093 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003094 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003095 MaxUnionIvarSize = UnionIvarSize;
3096 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003097 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003098 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003099 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003100 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003101 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003102 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003103 } else if ((ForStrongLayout &&
3104 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3105 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3106 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003107 // FIXME: Why the asymmetry? We divide by word size in bits on
3108 // other side.
3109 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003110 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003111 MaxSkippedUnionIvarSize = UnionIvarSize;
3112 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003113 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003114 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003115 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003116 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003117 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003118 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003119 }
3120 }
3121 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003122
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003123 if (LastFieldBitfield) {
3124 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003125 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3126 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003127 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003128 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003129 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003130 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3131 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003132 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003133 }
3134
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003135 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003136 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003137 MaxUnionIvarSize));
3138 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003139 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003140 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003141}
3142
3143/// BuildIvarLayout - Builds ivar layout bitmap for the class
3144/// implementation for the __strong or __weak case.
3145/// The layout map displays which words in ivar list must be skipped
3146/// and which must be scanned by GC (see below). String is built of bytes.
3147/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3148/// of words to skip and right nibble is count of words to scan. So, each
3149/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3150/// represented by a 0x00 byte which also ends the string.
3151/// 1. when ForStrongLayout is true, following ivars are scanned:
3152/// - id, Class
3153/// - object *
3154/// - __strong anything
3155///
3156/// 2. When ForStrongLayout is false, following ivars are scanned:
3157/// - __weak anything
3158///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003159llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003160 const ObjCImplementationDecl *OMD,
3161 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003162 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003163
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003164 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003165 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3166 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3167 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003168
Chris Lattnerf1690852009-03-31 08:48:01 +00003169 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003170 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003171 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003172
Daniel Dunbar37153282009-05-04 04:10:48 +00003173 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003174 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3175 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3176 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3177 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3178
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003179 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003180 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003181
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003182 SkipIvars.clear();
3183 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003184
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003185 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003186 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003187 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003188
3189 // Sort on byte position in case we encounterred a union nested in
3190 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003191 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003192 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003193 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003194 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003195
3196 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003197 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003198 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003199 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003200 if (IvarsInfo[0].ivar_bytepos == 0) {
3201 WordsToSkip = 0;
3202 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003203 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003204 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3205 WordsToScan = IvarsInfo[0].ivar_size;
3206 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003207 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 unsigned int TailPrevGCObjC =
3209 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003210 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003211 // consecutive 'scanned' object pointers.
3212 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003213 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003214 // Skip over 'gc'able object pointer which lay over each other.
3215 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3216 continue;
3217 // Must skip over 1 or more words. We save current skip/scan values
3218 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003219 SKIP_SCAN SkScan;
3220 SkScan.skip = WordsToSkip;
3221 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003222 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003223
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003224 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003225 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3226 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003227 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003228 WordsToSkip = 0;
3229 WordsToScan = IvarsInfo[i].ivar_size;
3230 }
3231 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003232 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003233 SKIP_SCAN SkScan;
3234 SkScan.skip = WordsToSkip;
3235 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003236 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003237 }
3238
3239 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003240 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003241 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003242 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003243 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3244 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003245 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003246 IvarsInfo[LastIndex].ivar_bytepos +
3247 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003248 BytesSkipped = (LastByteSkipped > LastByteScanned);
3249 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003250 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003251 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003252 SKIP_SCAN SkScan;
3253 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3254 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003255 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003256 }
3257 }
3258 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3259 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003260 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003261 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003262 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3263 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3264 // 0xM0 followed by 0x0N detected.
3265 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3266 for (int j = i+1; j < SkipScan; j++)
3267 SkipScanIvars[j] = SkipScanIvars[j+1];
3268 --SkipScan;
3269 }
3270 }
3271
3272 // Generate the string.
3273 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003274 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003275 unsigned char byte;
3276 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3277 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3278 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3279 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3280
3281 if (skip_small > 0 || skip_big > 0)
3282 BytesSkipped = true;
3283 // first skip big.
3284 for (unsigned int ix = 0; ix < skip_big; ix++)
3285 BitMap += (unsigned char)(0xf0);
3286
3287 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003288 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003289 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003290 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003291 byte |= 0xf;
3292 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003293 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003294 byte |= scan_small;
3295 scan_small = 0;
3296 }
3297 BitMap += byte;
3298 }
3299 // next scan big
3300 for (unsigned int ix = 0; ix < scan_big; ix++)
3301 BitMap += (unsigned char)(0x0f);
3302 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003303 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003304 byte = scan_small;
3305 BitMap += byte;
3306 }
3307 }
3308 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003309 unsigned char zero = 0;
3310 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003311
3312 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3313 printf("\n%s ivar layout for class '%s': ",
3314 ForStrongLayout ? "strong" : "weak",
3315 OMD->getClassInterface()->getNameAsCString());
3316 const unsigned char *s = (unsigned char*)BitMap.c_str();
3317 for (unsigned i = 0; i < BitMap.size(); i++)
3318 if (!(s[i] & 0xf0))
3319 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3320 else
3321 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3322 printf("\n");
3323 }
3324
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003325 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3326 // final layout.
3327 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003328 return llvm::Constant::getNullValue(PtrTy);
3329 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3330 llvm::ConstantArray::get(BitMap.c_str()),
3331 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003332 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003333 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003334}
3335
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003336llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003337 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3338
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003339 // FIXME: Avoid std::string copying.
3340 if (!Entry)
3341 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3342 llvm::ConstantArray::get(Sel.getAsString()),
3343 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003344 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003345
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003346 return getConstantGEP(Entry, 0, 0);
3347}
3348
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003349// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003350llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003351 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3352}
3353
3354// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003355llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003356 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3357}
3358
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003359llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003360 std::string TypeStr;
3361 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3362
3363 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003364
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003365 if (!Entry)
3366 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3367 llvm::ConstantArray::get(TypeStr),
3368 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003369 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003370
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003371 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003372}
3373
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003374llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003375 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003376 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3377 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003378
3379 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3380
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003381 if (!Entry)
3382 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3383 llvm::ConstantArray::get(TypeStr),
3384 "__TEXT,__cstring,cstring_literals",
3385 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003386
3387 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003388}
3389
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003390// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003391llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003392 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3393
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003394 if (!Entry)
3395 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3396 llvm::ConstantArray::get(Ident->getName()),
3397 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003398 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003399
3400 return getConstantGEP(Entry, 0, 0);
3401}
3402
3403// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003404// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003405llvm::Constant *
3406 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3407 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003408 std::string TypeStr;
3409 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003410 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3411}
3412
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003413void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3414 const ObjCContainerDecl *CD,
3415 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003416 NameOut = '\01';
3417 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003418 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003419 assert (CD && "Missing container decl in GetNameForMethod");
3420 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003421 if (const ObjCCategoryImplDecl *CID =
3422 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3423 NameOut += '(';
3424 NameOut += CID->getNameAsString();
3425 NameOut+= ')';
3426 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003427 NameOut += ' ';
3428 NameOut += D->getSelector().getAsString();
3429 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003430}
3431
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003432void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003433 EmitModuleInfo();
3434
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003435 // Emit the dummy bodies for any protocols which were referenced but
3436 // never defined.
3437 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3438 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3439 if (i->second->hasInitializer())
3440 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003441
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003442 std::vector<llvm::Constant*> Values(5);
3443 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3444 Values[1] = GetClassName(i->first);
3445 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3446 Values[3] = Values[4] =
3447 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3448 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3449 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3450 Values));
3451 }
3452
3453 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003454 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003455 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003456 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003457 }
3458
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003459 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003460 llvm::GlobalValue *GV =
3461 new llvm::GlobalVariable(AT, false,
3462 llvm::GlobalValue::AppendingLinkage,
3463 llvm::ConstantArray::get(AT, Used),
3464 "llvm.used",
3465 &CGM.getModule());
3466
3467 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003468
3469 // Add assembler directives to add lazy undefined symbol references
3470 // for classes which are referenced but not defined. This is
3471 // important for correct linker interaction.
3472
3473 // FIXME: Uh, this isn't particularly portable.
3474 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003475
3476 if (!CGM.getModule().getModuleInlineAsm().empty())
3477 s << "\n";
3478
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003479 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3480 e = LazySymbols.end(); i != e; ++i) {
3481 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3482 }
3483 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3484 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003485 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003486 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3487 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003488
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003489 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003490}
3491
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003492CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003493 : CGObjCCommonMac(cgm),
3494 ObjCTypes(cgm)
3495{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003496 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003497 ObjCABI = 2;
3498}
3499
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003500/* *** */
3501
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003502ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3503: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003504{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003505 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3506 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003507
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003508 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003509 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003510 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003511 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003512 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3513
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003514 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003515 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003516 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003517
3518 // FIXME: It would be nice to unify this with the opaque type, so
3519 // that the IR comes out a bit cleaner.
3520 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3521 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003522
3523 // I'm not sure I like this. The implicit coordination is a bit
3524 // gross. We should solve this in a reasonable fashion because this
3525 // is a pretty common task (match some runtime data structure with
3526 // an LLVM data structure).
3527
3528 // FIXME: This is leaked.
3529 // FIXME: Merge with rewriter code?
3530
3531 // struct _objc_super {
3532 // id self;
3533 // Class cls;
3534 // }
3535 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3536 SourceLocation(),
3537 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003538 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3539 Ctx.getObjCIdType(), 0, false));
3540 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3541 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003542 RD->completeDefinition(Ctx);
3543
3544 SuperCTy = Ctx.getTagDeclType(RD);
3545 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3546
3547 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003548 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3549
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003550 // struct _prop_t {
3551 // char *name;
3552 // char *attributes;
3553 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003554 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003555 CGM.getModule().addTypeName("struct._prop_t",
3556 PropertyTy);
3557
3558 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003559 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003560 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003561 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003562 // }
3563 PropertyListTy = llvm::StructType::get(IntTy,
3564 IntTy,
3565 llvm::ArrayType::get(PropertyTy, 0),
3566 NULL);
3567 CGM.getModule().addTypeName("struct._prop_list_t",
3568 PropertyListTy);
3569 // struct _prop_list_t *
3570 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3571
3572 // struct _objc_method {
3573 // SEL _cmd;
3574 // char *method_type;
3575 // char *_imp;
3576 // }
3577 MethodTy = llvm::StructType::get(SelectorPtrTy,
3578 Int8PtrTy,
3579 Int8PtrTy,
3580 NULL);
3581 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003582
3583 // struct _objc_cache *
3584 CacheTy = llvm::OpaqueType::get();
3585 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3586 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003587}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003588
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003589ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3590 : ObjCCommonTypesHelper(cgm)
3591{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003592 // struct _objc_method_description {
3593 // SEL name;
3594 // char *types;
3595 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003596 MethodDescriptionTy =
3597 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003598 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003599 NULL);
3600 CGM.getModule().addTypeName("struct._objc_method_description",
3601 MethodDescriptionTy);
3602
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003603 // struct _objc_method_description_list {
3604 // int count;
3605 // struct _objc_method_description[1];
3606 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003607 MethodDescriptionListTy =
3608 llvm::StructType::get(IntTy,
3609 llvm::ArrayType::get(MethodDescriptionTy, 0),
3610 NULL);
3611 CGM.getModule().addTypeName("struct._objc_method_description_list",
3612 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003613
3614 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003615 MethodDescriptionListPtrTy =
3616 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3617
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003618 // Protocol description structures
3619
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003620 // struct _objc_protocol_extension {
3621 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3622 // struct _objc_method_description_list *optional_instance_methods;
3623 // struct _objc_method_description_list *optional_class_methods;
3624 // struct _objc_property_list *instance_properties;
3625 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003626 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003627 llvm::StructType::get(IntTy,
3628 MethodDescriptionListPtrTy,
3629 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003630 PropertyListPtrTy,
3631 NULL);
3632 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3633 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003634
3635 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003636 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3637
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003638 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003639
3640 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3641 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3642
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003643 const llvm::Type *T =
3644 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3645 LongTy,
3646 llvm::ArrayType::get(ProtocolTyHolder, 0),
3647 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003648 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3649
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003650 // struct _objc_protocol {
3651 // struct _objc_protocol_extension *isa;
3652 // char *protocol_name;
3653 // struct _objc_protocol **_objc_protocol_list;
3654 // struct _objc_method_description_list *instance_methods;
3655 // struct _objc_method_description_list *class_methods;
3656 // }
3657 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003658 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003659 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3660 MethodDescriptionListPtrTy,
3661 MethodDescriptionListPtrTy,
3662 NULL);
3663 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3664
3665 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3666 CGM.getModule().addTypeName("struct._objc_protocol_list",
3667 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003668 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003669 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3670
3671 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003672 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003673 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003674
3675 // Class description structures
3676
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003677 // struct _objc_ivar {
3678 // char *ivar_name;
3679 // char *ivar_type;
3680 // int ivar_offset;
3681 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003682 IvarTy = llvm::StructType::get(Int8PtrTy,
3683 Int8PtrTy,
3684 IntTy,
3685 NULL);
3686 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3687
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003688 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003689 IvarListTy = llvm::OpaqueType::get();
3690 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3691 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3692
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003693 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003694 MethodListTy = llvm::OpaqueType::get();
3695 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3696 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3697
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003698 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003699 ClassExtensionTy =
3700 llvm::StructType::get(IntTy,
3701 Int8PtrTy,
3702 PropertyListPtrTy,
3703 NULL);
3704 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3705 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3706
3707 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3708
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003709 // struct _objc_class {
3710 // Class isa;
3711 // Class super_class;
3712 // char *name;
3713 // long version;
3714 // long info;
3715 // long instance_size;
3716 // struct _objc_ivar_list *ivars;
3717 // struct _objc_method_list *methods;
3718 // struct _objc_cache *cache;
3719 // struct _objc_protocol_list *protocols;
3720 // char *ivar_layout;
3721 // struct _objc_class_ext *ext;
3722 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003723 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3724 llvm::PointerType::getUnqual(ClassTyHolder),
3725 Int8PtrTy,
3726 LongTy,
3727 LongTy,
3728 LongTy,
3729 IvarListPtrTy,
3730 MethodListPtrTy,
3731 CachePtrTy,
3732 ProtocolListPtrTy,
3733 Int8PtrTy,
3734 ClassExtensionPtrTy,
3735 NULL);
3736 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3737
3738 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3739 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3740 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3741
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003742 // struct _objc_category {
3743 // char *category_name;
3744 // char *class_name;
3745 // struct _objc_method_list *instance_method;
3746 // struct _objc_method_list *class_method;
3747 // uint32_t size; // sizeof(struct _objc_category)
3748 // struct _objc_property_list *instance_properties;// category's @property
3749 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003750 CategoryTy = llvm::StructType::get(Int8PtrTy,
3751 Int8PtrTy,
3752 MethodListPtrTy,
3753 MethodListPtrTy,
3754 ProtocolListPtrTy,
3755 IntTy,
3756 PropertyListPtrTy,
3757 NULL);
3758 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3759
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003760 // Global metadata structures
3761
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003762 // struct _objc_symtab {
3763 // long sel_ref_cnt;
3764 // SEL *refs;
3765 // short cls_def_cnt;
3766 // short cat_def_cnt;
3767 // char *defs[cls_def_cnt + cat_def_cnt];
3768 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003769 SymtabTy = llvm::StructType::get(LongTy,
3770 SelectorPtrTy,
3771 ShortTy,
3772 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003773 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003774 NULL);
3775 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3776 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3777
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003778 // struct _objc_module {
3779 // long version;
3780 // long size; // sizeof(struct _objc_module)
3781 // char *name;
3782 // struct _objc_symtab* symtab;
3783 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003784 ModuleTy =
3785 llvm::StructType::get(LongTy,
3786 LongTy,
3787 Int8PtrTy,
3788 SymtabPtrTy,
3789 NULL);
3790 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003791
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003792
Anders Carlsson124526b2008-09-09 10:10:21 +00003793 // FIXME: This is the size of the setjmp buffer and should be
3794 // target specific. 18 is what's used on 32-bit X86.
3795 uint64_t SetJmpBufferSize = 18;
3796
3797 // Exceptions
3798 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003799 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003800
3801 ExceptionDataTy =
3802 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3803 SetJmpBufferSize),
3804 StackPtrTy, NULL);
3805 CGM.getModule().addTypeName("struct._objc_exception_data",
3806 ExceptionDataTy);
3807
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003808}
3809
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003810ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003811: ObjCCommonTypesHelper(cgm)
3812{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003813 // struct _method_list_t {
3814 // uint32_t entsize; // sizeof(struct _objc_method)
3815 // uint32_t method_count;
3816 // struct _objc_method method_list[method_count];
3817 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003818 MethodListnfABITy = llvm::StructType::get(IntTy,
3819 IntTy,
3820 llvm::ArrayType::get(MethodTy, 0),
3821 NULL);
3822 CGM.getModule().addTypeName("struct.__method_list_t",
3823 MethodListnfABITy);
3824 // struct method_list_t *
3825 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003826
3827 // struct _protocol_t {
3828 // id isa; // NULL
3829 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003830 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003831 // const struct method_list_t * const instance_methods;
3832 // const struct method_list_t * const class_methods;
3833 // const struct method_list_t *optionalInstanceMethods;
3834 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003835 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003836 // const uint32_t size; // sizeof(struct _protocol_t)
3837 // const uint32_t flags; // = 0
3838 // }
3839
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003840 // Holder for struct _protocol_list_t *
3841 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3842
3843 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3844 Int8PtrTy,
3845 llvm::PointerType::getUnqual(
3846 ProtocolListTyHolder),
3847 MethodListnfABIPtrTy,
3848 MethodListnfABIPtrTy,
3849 MethodListnfABIPtrTy,
3850 MethodListnfABIPtrTy,
3851 PropertyListPtrTy,
3852 IntTy,
3853 IntTy,
3854 NULL);
3855 CGM.getModule().addTypeName("struct._protocol_t",
3856 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003857
3858 // struct _protocol_t*
3859 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003860
Fariborz Jahanianda320092009-01-29 19:24:30 +00003861 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003862 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003863 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003864 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003865 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3866 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003867 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003868 NULL);
3869 CGM.getModule().addTypeName("struct._objc_protocol_list",
3870 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003871 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3872 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003873
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003874 // struct _objc_protocol_list*
3875 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003876
3877 // struct _ivar_t {
3878 // unsigned long int *offset; // pointer to ivar offset location
3879 // char *name;
3880 // char *type;
3881 // uint32_t alignment;
3882 // uint32_t size;
3883 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003884 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3885 Int8PtrTy,
3886 Int8PtrTy,
3887 IntTy,
3888 IntTy,
3889 NULL);
3890 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3891
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003892 // struct _ivar_list_t {
3893 // uint32 entsize; // sizeof(struct _ivar_t)
3894 // uint32 count;
3895 // struct _iver_t list[count];
3896 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003897 IvarListnfABITy = llvm::StructType::get(IntTy,
3898 IntTy,
3899 llvm::ArrayType::get(
3900 IvarnfABITy, 0),
3901 NULL);
3902 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3903
3904 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003905
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003906 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003907 // uint32_t const flags;
3908 // uint32_t const instanceStart;
3909 // uint32_t const instanceSize;
3910 // uint32_t const reserved; // only when building for 64bit targets
3911 // const uint8_t * const ivarLayout;
3912 // const char *const name;
3913 // const struct _method_list_t * const baseMethods;
3914 // const struct _objc_protocol_list *const baseProtocols;
3915 // const struct _ivar_list_t *const ivars;
3916 // const uint8_t * const weakIvarLayout;
3917 // const struct _prop_list_t * const properties;
3918 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003919
3920 // FIXME. Add 'reserved' field in 64bit abi mode!
3921 ClassRonfABITy = llvm::StructType::get(IntTy,
3922 IntTy,
3923 IntTy,
3924 Int8PtrTy,
3925 Int8PtrTy,
3926 MethodListnfABIPtrTy,
3927 ProtocolListnfABIPtrTy,
3928 IvarListnfABIPtrTy,
3929 Int8PtrTy,
3930 PropertyListPtrTy,
3931 NULL);
3932 CGM.getModule().addTypeName("struct._class_ro_t",
3933 ClassRonfABITy);
3934
3935 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3936 std::vector<const llvm::Type*> Params;
3937 Params.push_back(ObjectPtrTy);
3938 Params.push_back(SelectorPtrTy);
3939 ImpnfABITy = llvm::PointerType::getUnqual(
3940 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3941
3942 // struct _class_t {
3943 // struct _class_t *isa;
3944 // struct _class_t * const superclass;
3945 // void *cache;
3946 // IMP *vtable;
3947 // struct class_ro_t *ro;
3948 // }
3949
3950 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3951 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3952 llvm::PointerType::getUnqual(ClassTyHolder),
3953 CachePtrTy,
3954 llvm::PointerType::getUnqual(ImpnfABITy),
3955 llvm::PointerType::getUnqual(
3956 ClassRonfABITy),
3957 NULL);
3958 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3959
3960 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3961 ClassnfABITy);
3962
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003963 // LLVM for struct _class_t *
3964 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3965
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003966 // struct _category_t {
3967 // const char * const name;
3968 // struct _class_t *const cls;
3969 // const struct _method_list_t * const instance_methods;
3970 // const struct _method_list_t * const class_methods;
3971 // const struct _protocol_list_t * const protocols;
3972 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003973 // }
3974 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003975 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003976 MethodListnfABIPtrTy,
3977 MethodListnfABIPtrTy,
3978 ProtocolListnfABIPtrTy,
3979 PropertyListPtrTy,
3980 NULL);
3981 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003982
3983 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003984 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3985 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003986
3987 // MessageRefTy - LLVM for:
3988 // struct _message_ref_t {
3989 // IMP messenger;
3990 // SEL name;
3991 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003992
3993 // First the clang type for struct _message_ref_t
3994 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3995 SourceLocation(),
3996 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003997 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3998 Ctx.VoidPtrTy, 0, false));
3999 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
4000 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004001 RD->completeDefinition(Ctx);
4002
4003 MessageRefCTy = Ctx.getTagDeclType(RD);
4004 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4005 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004006
4007 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4008 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4009
4010 // SuperMessageRefTy - LLVM for:
4011 // struct _super_message_ref_t {
4012 // SUPER_IMP messenger;
4013 // SEL name;
4014 // };
4015 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4016 SelectorPtrTy,
4017 NULL);
4018 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4019
4020 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4021 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4022
Daniel Dunbare588b992009-03-01 04:46:24 +00004023
4024 // struct objc_typeinfo {
4025 // const void** vtable; // objc_ehtype_vtable + 2
4026 // const char* name; // c++ typeinfo string
4027 // Class cls;
4028 // };
4029 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4030 Int8PtrTy,
4031 ClassnfABIPtrTy,
4032 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004033 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004034 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004035}
4036
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004037llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4038 FinishNonFragileABIModule();
4039
4040 return NULL;
4041}
4042
Daniel Dunbar463b8762009-05-15 21:48:48 +00004043void CGObjCNonFragileABIMac::AddModuleClassList(const
4044 std::vector<llvm::GlobalValue*>
4045 &Container,
4046 const char *SymbolName,
4047 const char *SectionName) {
4048 unsigned NumClasses = Container.size();
4049
4050 if (!NumClasses)
4051 return;
4052
4053 std::vector<llvm::Constant*> Symbols(NumClasses);
4054 for (unsigned i=0; i<NumClasses; i++)
4055 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4056 ObjCTypes.Int8PtrTy);
4057 llvm::Constant* Init =
4058 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4059 NumClasses),
4060 Symbols);
4061
4062 llvm::GlobalVariable *GV =
4063 new llvm::GlobalVariable(Init->getType(), false,
4064 llvm::GlobalValue::InternalLinkage,
4065 Init,
4066 SymbolName,
4067 &CGM.getModule());
4068 GV->setAlignment(8);
4069 GV->setSection(SectionName);
4070 UsedGlobals.push_back(GV);
4071}
4072
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004073void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4074 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004075
Daniel Dunbar463b8762009-05-15 21:48:48 +00004076 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004077 // L_OBJC_LABEL_CLASS_$.
4078 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4079 // list of 'nonlazy' implementations (defined as those with a +load{}
4080 // method!!).
Daniel Dunbar463b8762009-05-15 21:48:48 +00004081 AddModuleClassList(DefinedClasses,
4082 "\01L_OBJC_LABEL_CLASS_$",
4083 "__DATA, __objc_classlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004084
4085 // Build list of all implemented category addresses in array
4086 // L_OBJC_LABEL_CATEGORY_$.
4087 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4088 // list of 'nonlazy' category implementations (defined as those with a +load{}
4089 // method!!).
Daniel Dunbar463b8762009-05-15 21:48:48 +00004090 AddModuleClassList(DefinedCategories,
4091 "\01L_OBJC_LABEL_CATEGORY_$",
4092 "__DATA, __objc_catlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004093
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004094 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4095 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4096 std::vector<llvm::Constant*> Values(2);
4097 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004098 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004099 // FIXME: Fix and continue?
4100 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4101 flags |= eImageInfo_GarbageCollected;
4102 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4103 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004104 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004105 llvm::Constant* Init = llvm::ConstantArray::get(
4106 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4107 Values);
4108 llvm::GlobalVariable *IMGV =
4109 new llvm::GlobalVariable(Init->getType(), false,
4110 llvm::GlobalValue::InternalLinkage,
4111 Init,
4112 "\01L_OBJC_IMAGE_INFO",
4113 &CGM.getModule());
4114 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004115 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004116 UsedGlobals.push_back(IMGV);
4117
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004118 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004119
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004120 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4121 e = UsedGlobals.end(); i != e; ++i) {
4122 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4123 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004124
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004125 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4126 llvm::GlobalValue *GV =
4127 new llvm::GlobalVariable(AT, false,
4128 llvm::GlobalValue::AppendingLinkage,
4129 llvm::ConstantArray::get(AT, Used),
4130 "llvm.used",
4131 &CGM.getModule());
4132
4133 GV->setSection("llvm.metadata");
4134
4135}
4136
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004137/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004138/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004139/// except for the 19 selectors in the list, we generate 32bit-style
4140/// message dispatch call for all the rest.
4141///
4142bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004143 if (NonLegacyDispatchMethods.empty()) {
4144 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4145 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4146 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4147 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4148 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4149 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4150 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4151 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4152 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4153 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4154
4155 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4156 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4157 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4158 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4159 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4160 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4161 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4162 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004163 // "countByEnumeratingWithState:objects:count"
4164 IdentifierInfo *KeyIdents[] = {
4165 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4166 &CGM.getContext().Idents.get("objects"),
4167 &CGM.getContext().Idents.get("count")
4168 };
4169 NonLegacyDispatchMethods.insert(
4170 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004171 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004172 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004173}
4174
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004175// Metadata flags
4176enum MetaDataDlags {
4177 CLS = 0x0,
4178 CLS_META = 0x1,
4179 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004180 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004181 CLS_EXCEPTION = 0x20
4182};
4183/// BuildClassRoTInitializer - generate meta-data for:
4184/// struct _class_ro_t {
4185/// uint32_t const flags;
4186/// uint32_t const instanceStart;
4187/// uint32_t const instanceSize;
4188/// uint32_t const reserved; // only when building for 64bit targets
4189/// const uint8_t * const ivarLayout;
4190/// const char *const name;
4191/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004192/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004193/// const struct _ivar_list_t *const ivars;
4194/// const uint8_t * const weakIvarLayout;
4195/// const struct _prop_list_t * const properties;
4196/// }
4197///
4198llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4199 unsigned flags,
4200 unsigned InstanceStart,
4201 unsigned InstanceSize,
4202 const ObjCImplementationDecl *ID) {
4203 std::string ClassName = ID->getNameAsString();
4204 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4205 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4206 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4207 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4208 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004209 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4210 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004211 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004212 // const struct _method_list_t * const baseMethods;
4213 std::vector<llvm::Constant*> Methods;
4214 std::string MethodListName("\01l_OBJC_$_");
4215 if (flags & CLS_META) {
4216 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004217 for (ObjCImplementationDecl::classmeth_iterator
4218 i = ID->classmeth_begin(CGM.getContext()),
4219 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004220 // Class methods should always be defined.
4221 Methods.push_back(GetMethodConstant(*i));
4222 }
4223 } else {
4224 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004225 for (ObjCImplementationDecl::instmeth_iterator
4226 i = ID->instmeth_begin(CGM.getContext()),
4227 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004228 // Instance methods should always be defined.
4229 Methods.push_back(GetMethodConstant(*i));
4230 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004231 for (ObjCImplementationDecl::propimpl_iterator
4232 i = ID->propimpl_begin(CGM.getContext()),
4233 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004234 ObjCPropertyImplDecl *PID = *i;
4235
4236 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4237 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4238
4239 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4240 if (llvm::Constant *C = GetMethodConstant(MD))
4241 Methods.push_back(C);
4242 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4243 if (llvm::Constant *C = GetMethodConstant(MD))
4244 Methods.push_back(C);
4245 }
4246 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004247 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004248 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004249 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004250
4251 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4252 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4253 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4254 + OID->getNameAsString(),
4255 OID->protocol_begin(),
4256 OID->protocol_end());
4257
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004258 if (flags & CLS_META)
4259 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4260 else
4261 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004262 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4263 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004264 if (flags & CLS_META)
4265 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4266 else
4267 Values[ 9] =
4268 EmitPropertyList(
4269 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4270 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004271 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4272 Values);
4273 llvm::GlobalVariable *CLASS_RO_GV =
4274 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4275 llvm::GlobalValue::InternalLinkage,
4276 Init,
4277 (flags & CLS_META) ?
4278 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4279 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4280 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004281 CLASS_RO_GV->setAlignment(
4282 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004283 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004284 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004285
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004286}
4287
4288/// BuildClassMetaData - This routine defines that to-level meta-data
4289/// for the given ClassName for:
4290/// struct _class_t {
4291/// struct _class_t *isa;
4292/// struct _class_t * const superclass;
4293/// void *cache;
4294/// IMP *vtable;
4295/// struct class_ro_t *ro;
4296/// }
4297///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004298llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4299 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004300 llvm::Constant *IsAGV,
4301 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004302 llvm::Constant *ClassRoGV,
4303 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004304 std::vector<llvm::Constant*> Values(5);
4305 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004306 Values[1] = SuperClassGV
4307 ? SuperClassGV
4308 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004309 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4310 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4311 Values[4] = ClassRoGV; // &CLASS_RO_GV
4312 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4313 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004314 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4315 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004316 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004317 GV->setAlignment(
4318 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004319 if (HiddenVisibility)
4320 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004321 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004322}
4323
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004324void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004325 uint32_t &InstanceStart,
4326 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004327 const ASTRecordLayout &RL =
4328 CGM.getContext().getASTObjCImplementationLayout(OID);
4329
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004330 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004331 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004332
4333 // If there are no fields, the start is the same as the end.
4334 if (!RL.getFieldCount())
4335 InstanceStart = InstanceSize;
4336 else
4337 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004338}
4339
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004340void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4341 std::string ClassName = ID->getNameAsString();
4342 if (!ObjCEmptyCacheVar) {
4343 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004344 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004345 false,
4346 llvm::GlobalValue::ExternalLinkage,
4347 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004348 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004349 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004350
4351 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004352 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004353 false,
4354 llvm::GlobalValue::ExternalLinkage,
4355 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004356 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004357 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004358 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004359 assert(ID->getClassInterface() &&
4360 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004361 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004362 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004363 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004364 uint32_t InstanceSize = InstanceStart;
4365 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004366 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4367 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004368
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004369 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004370
Daniel Dunbar04d40782009-04-14 06:00:08 +00004371 bool classIsHidden =
4372 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004373 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004374 flags |= OBJC2_CLS_HIDDEN;
4375 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004376 // class is root
4377 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004378 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004379 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004380 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004381 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004382 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4383 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4384 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004385 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004386 // work on super class metadata symbol.
4387 std::string SuperClassName =
4388 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004389 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004390 }
4391 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4392 InstanceStart,
4393 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004394 std::string TClassName = ObjCMetaClassName + ClassName;
4395 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004396 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4397 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004398
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004399 // Metadata for the class
4400 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004401 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004402 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004403
4404 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4405 flags |= CLS_EXCEPTION;
4406
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004407 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004408 flags |= CLS_ROOT;
4409 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004410 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004411 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004412 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004413 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004414 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004415 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004416 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004417 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004418 InstanceStart,
4419 InstanceSize,
4420 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004421
4422 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004423 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004424 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4425 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004426 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004427
4428 // Force the definition of the EHType if necessary.
4429 if (flags & CLS_EXCEPTION)
4430 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004431}
4432
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004433/// GenerateProtocolRef - This routine is called to generate code for
4434/// a protocol reference expression; as in:
4435/// @code
4436/// @protocol(Proto1);
4437/// @endcode
4438/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4439/// which will hold address of the protocol meta-data.
4440///
4441llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4442 const ObjCProtocolDecl *PD) {
4443
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004444 // This routine is called for @protocol only. So, we must build definition
4445 // of protocol's meta-data (not a reference to it!)
4446 //
4447 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004448 ObjCTypes.ExternalProtocolPtrTy);
4449
4450 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4451 ProtocolName += PD->getNameAsCString();
4452
4453 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4454 if (PTGV)
4455 return Builder.CreateLoad(PTGV, false, "tmp");
4456 PTGV = new llvm::GlobalVariable(
4457 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004458 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004459 Init,
4460 ProtocolName,
4461 &CGM.getModule());
4462 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4463 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4464 UsedGlobals.push_back(PTGV);
4465 return Builder.CreateLoad(PTGV, false, "tmp");
4466}
4467
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004468/// GenerateCategory - Build metadata for a category implementation.
4469/// struct _category_t {
4470/// const char * const name;
4471/// struct _class_t *const cls;
4472/// const struct _method_list_t * const instance_methods;
4473/// const struct _method_list_t * const class_methods;
4474/// const struct _protocol_list_t * const protocols;
4475/// const struct _prop_list_t * const properties;
4476/// }
4477///
4478void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4479{
4480 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004481 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4482 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004483 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004484 std::string ExtClassName(getClassSymbolPrefix() +
4485 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004486
4487 std::vector<llvm::Constant*> Values(6);
4488 Values[0] = GetClassName(OCD->getIdentifier());
4489 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004490 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004491 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004492 std::vector<llvm::Constant*> Methods;
4493 std::string MethodListName(Prefix);
4494 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4495 "_$_" + OCD->getNameAsString();
4496
Douglas Gregor653f1b12009-04-23 01:02:12 +00004497 for (ObjCCategoryImplDecl::instmeth_iterator
4498 i = OCD->instmeth_begin(CGM.getContext()),
4499 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004500 // Instance methods should always be defined.
4501 Methods.push_back(GetMethodConstant(*i));
4502 }
4503
4504 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004505 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004506 Methods);
4507
4508 MethodListName = Prefix;
4509 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4510 OCD->getNameAsString();
4511 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004512 for (ObjCCategoryImplDecl::classmeth_iterator
4513 i = OCD->classmeth_begin(CGM.getContext()),
4514 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004515 // Class methods should always be defined.
4516 Methods.push_back(GetMethodConstant(*i));
4517 }
4518
4519 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004520 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004521 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004522 const ObjCCategoryDecl *Category =
4523 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004524 if (Category) {
4525 std::string ExtName(Interface->getNameAsString() + "_$_" +
4526 OCD->getNameAsString());
4527 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4528 + Interface->getNameAsString() + "_$_"
4529 + Category->getNameAsString(),
4530 Category->protocol_begin(),
4531 Category->protocol_end());
4532 Values[5] =
4533 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4534 OCD, Category, ObjCTypes);
4535 }
4536 else {
4537 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4538 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4539 }
4540
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004541 llvm::Constant *Init =
4542 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4543 Values);
4544 llvm::GlobalVariable *GCATV
4545 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4546 false,
4547 llvm::GlobalValue::InternalLinkage,
4548 Init,
4549 ExtCatName,
4550 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004551 GCATV->setAlignment(
4552 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004553 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004554 UsedGlobals.push_back(GCATV);
4555 DefinedCategories.push_back(GCATV);
4556}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004557
4558/// GetMethodConstant - Return a struct objc_method constant for the
4559/// given method if it has been defined. The result is null if the
4560/// method has not been defined. The return value has type MethodPtrTy.
4561llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4562 const ObjCMethodDecl *MD) {
4563 // FIXME: Use DenseMap::lookup
4564 llvm::Function *Fn = MethodDefinitions[MD];
4565 if (!Fn)
4566 return 0;
4567
4568 std::vector<llvm::Constant*> Method(3);
4569 Method[0] =
4570 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4571 ObjCTypes.SelectorPtrTy);
4572 Method[1] = GetMethodVarType(MD);
4573 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4574 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4575}
4576
4577/// EmitMethodList - Build meta-data for method declarations
4578/// struct _method_list_t {
4579/// uint32_t entsize; // sizeof(struct _objc_method)
4580/// uint32_t method_count;
4581/// struct _objc_method method_list[method_count];
4582/// }
4583///
4584llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4585 const std::string &Name,
4586 const char *Section,
4587 const ConstantVector &Methods) {
4588 // Return null for empty list.
4589 if (Methods.empty())
4590 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4591
4592 std::vector<llvm::Constant*> Values(3);
4593 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004594 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004595 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4596 // method_count
4597 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4598 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4599 Methods.size());
4600 Values[2] = llvm::ConstantArray::get(AT, Methods);
4601 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4602
4603 llvm::GlobalVariable *GV =
4604 new llvm::GlobalVariable(Init->getType(), false,
4605 llvm::GlobalValue::InternalLinkage,
4606 Init,
4607 Name,
4608 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004609 GV->setAlignment(
4610 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004611 GV->setSection(Section);
4612 UsedGlobals.push_back(GV);
4613 return llvm::ConstantExpr::getBitCast(GV,
4614 ObjCTypes.MethodListnfABIPtrTy);
4615}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004616
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004617/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4618/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004619llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004620 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004621 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004622 // FIXME: We shouldn't need to do this lookup.
4623 unsigned Index;
4624 const ObjCInterfaceDecl *Container =
4625 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4626 assert(Container && "Unable to find ivar container!");
4627 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004628 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004629 llvm::GlobalVariable *IvarOffsetGV =
4630 CGM.getModule().getGlobalVariable(Name);
4631 if (!IvarOffsetGV)
4632 IvarOffsetGV =
4633 new llvm::GlobalVariable(ObjCTypes.LongTy,
4634 false,
4635 llvm::GlobalValue::ExternalLinkage,
4636 0,
4637 Name,
4638 &CGM.getModule());
4639 return IvarOffsetGV;
4640}
4641
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004642llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004643 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004644 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004645 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004646 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4647 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4648 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004649 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004650 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004651
4652 // FIXME: This matches gcc, but shouldn't the visibility be set on
4653 // the use as well (i.e., in ObjCIvarOffsetVariable).
4654 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4655 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4656 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004657 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004658 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004659 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004660 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004661 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004662}
4663
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004664/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004665/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004666/// IvarListnfABIPtrTy.
4667/// struct _ivar_t {
4668/// unsigned long int *offset; // pointer to ivar offset location
4669/// char *name;
4670/// char *type;
4671/// uint32_t alignment;
4672/// uint32_t size;
4673/// }
4674/// struct _ivar_list_t {
4675/// uint32 entsize; // sizeof(struct _ivar_t)
4676/// uint32 count;
4677/// struct _iver_t list[count];
4678/// }
4679///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004680
4681void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4682 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4683 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4684 E = OID->ivar_end(); I != E; ++I) {
4685 // Ignore unnamed bit-fields.
4686 if (!(*I)->getDeclName())
4687 continue;
4688
4689 Res.push_back(*I);
4690 }
4691
Fariborz Jahanian98200742009-05-12 18:14:29 +00004692 // Also save synthesize ivars.
4693 // FIXME. Why can't we just use passed in Res small vector?
4694 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
4695 CGM.getContext().CollectSynthesizedIvars(OID, Ivars);
4696 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
4697 Res.push_back(Ivars[k]);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004698}
4699
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004700llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4701 const ObjCImplementationDecl *ID) {
4702
4703 std::vector<llvm::Constant*> Ivars, Ivar(5);
4704
4705 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4706 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4707
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004708 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004709
Daniel Dunbar91636d62009-04-20 00:33:43 +00004710 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004711 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004712 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004713
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004714 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4715 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004716 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004717 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004718 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4719 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004720 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004721 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004722 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004723 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004724 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004725 Align = llvm::Log2_32(Align);
4726 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004727 // NOTE. Size of a bitfield does not match gcc's, because of the
4728 // way bitfields are treated special in each. But I am told that
4729 // 'size' for bitfield ivars is ignored by the runtime so it does
4730 // not matter. If it matters, there is enough info to get the
4731 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004732 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4733 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4734 }
4735 // Return null for empty list.
4736 if (Ivars.empty())
4737 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4738 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004739 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004740 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4741 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4742 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4743 Ivars.size());
4744 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4745 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4746 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4747 llvm::GlobalVariable *GV =
4748 new llvm::GlobalVariable(Init->getType(), false,
4749 llvm::GlobalValue::InternalLinkage,
4750 Init,
4751 Prefix + OID->getNameAsString(),
4752 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004753 GV->setAlignment(
4754 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004755 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004756
4757 UsedGlobals.push_back(GV);
4758 return llvm::ConstantExpr::getBitCast(GV,
4759 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760}
4761
4762llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4763 const ObjCProtocolDecl *PD) {
4764 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4765
4766 if (!Entry) {
4767 // We use the initializer as a marker of whether this is a forward
4768 // reference or not. At module finalization we add the empty
4769 // contents for protocols which were referenced but never defined.
4770 Entry =
4771 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4772 llvm::GlobalValue::ExternalLinkage,
4773 0,
4774 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4775 &CGM.getModule());
4776 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4777 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004778 }
4779
4780 return Entry;
4781}
4782
4783/// GetOrEmitProtocol - Generate the protocol meta-data:
4784/// @code
4785/// struct _protocol_t {
4786/// id isa; // NULL
4787/// const char * const protocol_name;
4788/// const struct _protocol_list_t * protocol_list; // super protocols
4789/// const struct method_list_t * const instance_methods;
4790/// const struct method_list_t * const class_methods;
4791/// const struct method_list_t *optionalInstanceMethods;
4792/// const struct method_list_t *optionalClassMethods;
4793/// const struct _prop_list_t * properties;
4794/// const uint32_t size; // sizeof(struct _protocol_t)
4795/// const uint32_t flags; // = 0
4796/// }
4797/// @endcode
4798///
4799
4800llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4801 const ObjCProtocolDecl *PD) {
4802 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4803
4804 // Early exit if a defining object has already been generated.
4805 if (Entry && Entry->hasInitializer())
4806 return Entry;
4807
4808 const char *ProtocolName = PD->getNameAsCString();
4809
4810 // Construct method lists.
4811 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4812 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004813 for (ObjCProtocolDecl::instmeth_iterator
4814 i = PD->instmeth_begin(CGM.getContext()),
4815 e = PD->instmeth_end(CGM.getContext());
4816 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004818 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004819 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4820 OptInstanceMethods.push_back(C);
4821 } else {
4822 InstanceMethods.push_back(C);
4823 }
4824 }
4825
Douglas Gregor6ab35242009-04-09 21:40:53 +00004826 for (ObjCProtocolDecl::classmeth_iterator
4827 i = PD->classmeth_begin(CGM.getContext()),
4828 e = PD->classmeth_end(CGM.getContext());
4829 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004830 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004831 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004832 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4833 OptClassMethods.push_back(C);
4834 } else {
4835 ClassMethods.push_back(C);
4836 }
4837 }
4838
4839 std::vector<llvm::Constant*> Values(10);
4840 // isa is NULL
4841 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4842 Values[1] = GetClassName(PD->getIdentifier());
4843 Values[2] = EmitProtocolList(
4844 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4845 PD->protocol_begin(),
4846 PD->protocol_end());
4847
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004848 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004849 + PD->getNameAsString(),
4850 "__DATA, __objc_const",
4851 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004852 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004853 + PD->getNameAsString(),
4854 "__DATA, __objc_const",
4855 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004856 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004857 + PD->getNameAsString(),
4858 "__DATA, __objc_const",
4859 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004860 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861 + PD->getNameAsString(),
4862 "__DATA, __objc_const",
4863 OptClassMethods);
4864 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4865 0, PD, ObjCTypes);
4866 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004867 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004868 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4869 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4870 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4871 Values);
4872
4873 if (Entry) {
4874 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004875 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004876 Entry->setInitializer(Init);
4877 } else {
4878 Entry =
4879 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004880 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004881 Init,
4882 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4883 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004884 Entry->setAlignment(
4885 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004886 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004887 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004888 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4889
4890 // Use this protocol meta-data to build protocol list table in section
4891 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004892 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004893 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004894 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004895 Entry,
4896 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4897 +ProtocolName,
4898 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004899 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004900 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004901 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004902 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4903 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004904 return Entry;
4905}
4906
4907/// EmitProtocolList - Generate protocol list meta-data:
4908/// @code
4909/// struct _protocol_list_t {
4910/// long protocol_count; // Note, this is 32/64 bit
4911/// struct _protocol_t[protocol_count];
4912/// }
4913/// @endcode
4914///
4915llvm::Constant *
4916CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4917 ObjCProtocolDecl::protocol_iterator begin,
4918 ObjCProtocolDecl::protocol_iterator end) {
4919 std::vector<llvm::Constant*> ProtocolRefs;
4920
Fariborz Jahanianda320092009-01-29 19:24:30 +00004921 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004922 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004923 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4924
Daniel Dunbar948e2582009-02-15 07:36:20 +00004925 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004926 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4927 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004928 return llvm::ConstantExpr::getBitCast(GV,
4929 ObjCTypes.ProtocolListnfABIPtrTy);
4930
4931 for (; begin != end; ++begin)
4932 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4933
Fariborz Jahanianda320092009-01-29 19:24:30 +00004934 // This list is null terminated.
4935 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004936 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004937
4938 std::vector<llvm::Constant*> Values(2);
4939 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4940 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004941 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004942 ProtocolRefs.size()),
4943 ProtocolRefs);
4944
4945 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4946 GV = new llvm::GlobalVariable(Init->getType(), false,
4947 llvm::GlobalValue::InternalLinkage,
4948 Init,
4949 Name,
4950 &CGM.getModule());
4951 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004952 GV->setAlignment(
4953 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004954 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004955 return llvm::ConstantExpr::getBitCast(GV,
4956 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004957}
4958
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004959/// GetMethodDescriptionConstant - This routine build following meta-data:
4960/// struct _objc_method {
4961/// SEL _cmd;
4962/// char *method_type;
4963/// char *_imp;
4964/// }
4965
4966llvm::Constant *
4967CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4968 std::vector<llvm::Constant*> Desc(3);
4969 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4970 ObjCTypes.SelectorPtrTy);
4971 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004972 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004973 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4974 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4975}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004976
4977/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4978/// This code gen. amounts to generating code for:
4979/// @code
4980/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4981/// @encode
4982///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004983LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004984 CodeGen::CodeGenFunction &CGF,
4985 QualType ObjectTy,
4986 llvm::Value *BaseValue,
4987 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004988 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004989 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004990 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4991 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004992}
4993
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004994llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4995 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004996 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004997 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004998 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4999 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005000}
5001
Fariborz Jahanian46551122009-02-04 00:22:57 +00005002CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
5003 CodeGen::CodeGenFunction &CGF,
5004 QualType ResultType,
5005 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005006 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00005007 QualType Arg0Ty,
5008 bool IsSuper,
5009 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 // FIXME. Even though IsSuper is passes. This function doese not
5011 // handle calls to 'super' receivers.
5012 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005013 llvm::Value *Arg0 = Receiver;
5014 if (!IsSuper)
5015 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016
5017 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00005018 // FIXME. This is too much work to get the ABI-specific result type
5019 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005020 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5021 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005022 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005023 std::string Name("\01l_");
5024 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005025#if 0
5026 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005027 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005028 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005029 // FIXME. Is there a better way of getting these names.
5030 // They are available in RuntimeFunctions vector pair.
5031 Name += "objc_msgSendId_stret_fixup";
5032 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005033 else
5034#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005035 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005036 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005037 Name += "objc_msgSendSuper2_stret_fixup";
5038 }
5039 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005040 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005041 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005042 Name += "objc_msgSend_stret_fixup";
5043 }
5044 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005045 else if (!IsSuper && ResultType->isFloatingType()) {
5046 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5047 BuiltinType::Kind k = BT->getKind();
5048 if (k == BuiltinType::LongDouble) {
5049 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5050 Name += "objc_msgSend_fpret_fixup";
5051 }
5052 else {
5053 Fn = ObjCTypes.getMessageSendFixupFn();
5054 Name += "objc_msgSend_fixup";
5055 }
5056 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005057 }
5058 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005059#if 0
5060// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005061 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005062 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005063 Name += "objc_msgSendId_fixup";
5064 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005065 else
5066#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005067 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005068 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005069 Name += "objc_msgSendSuper2_fixup";
5070 }
5071 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005072 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005073 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005074 Name += "objc_msgSend_fixup";
5075 }
5076 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005077 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005078 Name += '_';
5079 std::string SelName(Sel.getAsString());
5080 // Replace all ':' in selector name with '_' ouch!
5081 for(unsigned i = 0; i < SelName.size(); i++)
5082 if (SelName[i] == ':')
5083 SelName[i] = '_';
5084 Name += SelName;
5085 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5086 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005087 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005088 std::vector<llvm::Constant*> Values(2);
5089 Values[0] = Fn;
5090 Values[1] = GetMethodVarName(Sel);
5091 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5092 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005093 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005094 Init,
5095 Name,
5096 &CGM.getModule());
5097 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005098 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005099 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005100 }
5101 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005102
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005103 CallArgList ActualArgs;
5104 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5105 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5106 ObjCTypes.MessageRefCPtrTy));
5107 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005108 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5109 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5110 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005111 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005112 Callee = CGF.Builder.CreateBitCast(Callee,
5113 llvm::PointerType::getUnqual(FTy));
5114 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005115}
5116
5117/// Generate code for a message send expression in the nonfragile abi.
5118CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5119 CodeGen::CodeGenFunction &CGF,
5120 QualType ResultType,
5121 Selector Sel,
5122 llvm::Value *Receiver,
5123 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005124 const CallArgList &CallArgs,
5125 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005126 return LegacyDispatchedSelector(Sel)
5127 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5128 Receiver, CGF.getContext().getObjCIdType(),
5129 false, CallArgs, ObjCTypes)
5130 : EmitMessageSend(CGF, ResultType, Sel,
5131 Receiver, CGF.getContext().getObjCIdType(),
5132 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005133}
5134
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005135llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005136CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005137 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5138
Daniel Dunbardfff2302009-03-02 05:18:14 +00005139 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005140 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5141 llvm::GlobalValue::ExternalLinkage,
5142 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005143 }
5144
5145 return GV;
5146}
5147
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005148llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005149 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005150 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5151
5152 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005153 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005154 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005155 Entry =
5156 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5157 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005158 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005159 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005160 &CGM.getModule());
5161 Entry->setAlignment(
5162 CGM.getTargetData().getPrefTypeAlignment(
5163 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005164 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5165 UsedGlobals.push_back(Entry);
5166 }
5167
5168 return Builder.CreateLoad(Entry, false, "tmp");
5169}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005170
Daniel Dunbar11394522009-04-18 08:51:00 +00005171llvm::Value *
5172CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5173 const ObjCInterfaceDecl *ID) {
5174 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5175
5176 if (!Entry) {
5177 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5178 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5179 Entry =
5180 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5181 llvm::GlobalValue::InternalLinkage,
5182 ClassGV,
5183 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5184 &CGM.getModule());
5185 Entry->setAlignment(
5186 CGM.getTargetData().getPrefTypeAlignment(
5187 ObjCTypes.ClassnfABIPtrTy));
5188 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005189 UsedGlobals.push_back(Entry);
5190 }
5191
5192 return Builder.CreateLoad(Entry, false, "tmp");
5193}
5194
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005195/// EmitMetaClassRef - Return a Value * of the address of _class_t
5196/// meta-data
5197///
5198llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5199 const ObjCInterfaceDecl *ID) {
5200 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5201 if (Entry)
5202 return Builder.CreateLoad(Entry, false, "tmp");
5203
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005204 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005205 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005206 Entry =
5207 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5208 llvm::GlobalValue::InternalLinkage,
5209 MetaClassGV,
5210 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5211 &CGM.getModule());
5212 Entry->setAlignment(
5213 CGM.getTargetData().getPrefTypeAlignment(
5214 ObjCTypes.ClassnfABIPtrTy));
5215
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005216 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005217 UsedGlobals.push_back(Entry);
5218
5219 return Builder.CreateLoad(Entry, false, "tmp");
5220}
5221
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005222/// GetClass - Return a reference to the class for the given interface
5223/// decl.
5224llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5225 const ObjCInterfaceDecl *ID) {
5226 return EmitClassRef(Builder, ID);
5227}
5228
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005229/// Generates a message send where the super is the receiver. This is
5230/// a message send to self with special delivery semantics indicating
5231/// which class's method should be called.
5232CodeGen::RValue
5233CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5234 QualType ResultType,
5235 Selector Sel,
5236 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005237 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005238 llvm::Value *Receiver,
5239 bool IsClassMessage,
5240 const CodeGen::CallArgList &CallArgs) {
5241 // ...
5242 // Create and init a super structure; this is a (receiver, class)
5243 // pair we will pass to objc_msgSendSuper.
5244 llvm::Value *ObjCSuper =
5245 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5246
5247 llvm::Value *ReceiverAsObject =
5248 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5249 CGF.Builder.CreateStore(ReceiverAsObject,
5250 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5251
5252 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005253 llvm::Value *Target;
5254 if (IsClassMessage) {
5255 if (isCategoryImpl) {
5256 // Message sent to "super' in a class method defined in
5257 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005258 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005259 Target = CGF.Builder.CreateStructGEP(Target, 0);
5260 Target = CGF.Builder.CreateLoad(Target);
5261 }
5262 else
5263 Target = EmitMetaClassRef(CGF.Builder, Class);
5264 }
5265 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005266 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005267
5268 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5269 // and ObjCTypes types.
5270 const llvm::Type *ClassTy =
5271 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5272 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5273 CGF.Builder.CreateStore(Target,
5274 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5275
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005276 return (LegacyDispatchedSelector(Sel))
5277 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5278 ObjCSuper, ObjCTypes.SuperPtrCTy,
5279 true, CallArgs,
5280 ObjCTypes)
5281 : EmitMessageSend(CGF, ResultType, Sel,
5282 ObjCSuper, ObjCTypes.SuperPtrCTy,
5283 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005284}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005285
5286llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5287 Selector Sel) {
5288 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5289
5290 if (!Entry) {
5291 llvm::Constant *Casted =
5292 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5293 ObjCTypes.SelectorPtrTy);
5294 Entry =
5295 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5296 llvm::GlobalValue::InternalLinkage,
5297 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5298 &CGM.getModule());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005299 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005300 UsedGlobals.push_back(Entry);
5301 }
5302
5303 return Builder.CreateLoad(Entry, false, "tmp");
5304}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005305/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5306/// objc_assign_ivar (id src, id *dst)
5307///
5308void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5309 llvm::Value *src, llvm::Value *dst)
5310{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005311 const llvm::Type * SrcTy = src->getType();
5312 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005313 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005314 assert(Size <= 8 && "does not support size > 8");
5315 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5316 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005317 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5318 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005319 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5320 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005321 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005322 src, dst, "assignivar");
5323 return;
5324}
5325
5326/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5327/// objc_assign_strongCast (id src, id *dst)
5328///
5329void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5330 CodeGen::CodeGenFunction &CGF,
5331 llvm::Value *src, llvm::Value *dst)
5332{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005333 const llvm::Type * SrcTy = src->getType();
5334 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005335 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005336 assert(Size <= 8 && "does not support size > 8");
5337 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5338 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005339 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5340 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005341 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5342 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005343 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005344 src, dst, "weakassign");
5345 return;
5346}
5347
5348/// EmitObjCWeakRead - Code gen for loading value of a __weak
5349/// object: objc_read_weak (id *src)
5350///
5351llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5352 CodeGen::CodeGenFunction &CGF,
5353 llvm::Value *AddrWeakObj)
5354{
Eli Friedman8339b352009-03-07 03:57:15 +00005355 const llvm::Type* DestTy =
5356 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005357 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005358 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005359 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005360 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005361 return read_weak;
5362}
5363
5364/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5365/// objc_assign_weak (id src, id *dst)
5366///
5367void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5368 llvm::Value *src, llvm::Value *dst)
5369{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005370 const llvm::Type * SrcTy = src->getType();
5371 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005372 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005373 assert(Size <= 8 && "does not support size > 8");
5374 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5375 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005376 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5377 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005378 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5379 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005380 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005381 src, dst, "weakassign");
5382 return;
5383}
5384
5385/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5386/// objc_assign_global (id src, id *dst)
5387///
5388void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5389 llvm::Value *src, llvm::Value *dst)
5390{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005391 const llvm::Type * SrcTy = src->getType();
5392 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005393 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005394 assert(Size <= 8 && "does not support size > 8");
5395 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5396 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005397 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5398 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005399 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5400 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005401 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005402 src, dst, "globalassign");
5403 return;
5404}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005405
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005406void
5407CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5408 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005409 bool isTry = isa<ObjCAtTryStmt>(S);
5410 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5411 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005412 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005413 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005414 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005415 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5416
5417 // For @synchronized, call objc_sync_enter(sync.expr). The
5418 // evaluation of the expression must occur before we enter the
5419 // @synchronized. We can safely avoid a temp here because jumps into
5420 // @synchronized are illegal & this will dominate uses.
5421 llvm::Value *SyncArg = 0;
5422 if (!isTry) {
5423 SyncArg =
5424 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5425 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005426 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005427 }
5428
5429 // Push an EH context entry, used for handling rethrows and jumps
5430 // through finally.
5431 CGF.PushCleanupBlock(FinallyBlock);
5432
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005433 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005434
5435 CGF.EmitBlock(TryBlock);
5436 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5437 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5438 CGF.EmitBranchThroughCleanup(FinallyEnd);
5439
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005440 // Emit the exception handler.
5441
5442 CGF.EmitBlock(TryHandler);
5443
5444 llvm::Value *llvm_eh_exception =
5445 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5446 llvm::Value *llvm_eh_selector_i64 =
5447 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5448 llvm::Value *llvm_eh_typeid_for_i64 =
5449 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5450 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5451 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5452
5453 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5454 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005455 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005456
5457 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005458 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005459 bool HasCatchAll = false;
5460 if (isTry) {
5461 if (const ObjCAtCatchStmt* CatchStmt =
5462 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5463 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005464 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005465 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005466
5467 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005468 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005469 // Use i8* null here to signal this is a catch all, not a cleanup.
5470 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5471 SelectorArgs.push_back(Null);
5472 HasCatchAll = true;
5473 break;
5474 }
5475
Daniel Dunbarede8de92009-03-06 00:01:21 +00005476 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5477 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005478 llvm::Value *IDEHType =
5479 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5480 if (!IDEHType)
5481 IDEHType =
5482 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5483 llvm::GlobalValue::ExternalLinkage,
5484 0, "OBJC_EHTYPE_id", &CGM.getModule());
5485 SelectorArgs.push_back(IDEHType);
5486 HasCatchAll = true;
5487 break;
5488 }
5489
5490 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005491 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005492 assert(PT && "Invalid @catch type.");
5493 const ObjCInterfaceType *IT =
5494 PT->getPointeeType()->getAsObjCInterfaceType();
5495 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005496 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005497 SelectorArgs.push_back(EHType);
5498 }
5499 }
5500 }
5501
5502 // We use a cleanup unless there was already a catch all.
5503 if (!HasCatchAll) {
5504 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005505 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005506 }
5507
5508 llvm::Value *Selector =
5509 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5510 SelectorArgs.begin(), SelectorArgs.end(),
5511 "selector");
5512 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005513 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005514 const Stmt *CatchBody = Handlers[i].second;
5515
5516 llvm::BasicBlock *Next = 0;
5517
5518 // The last handler always matches.
5519 if (i + 1 != e) {
5520 assert(CatchParam && "Only last handler can be a catch all.");
5521
5522 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5523 Next = CGF.createBasicBlock("catch.next");
5524 llvm::Value *Id =
5525 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5526 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5527 ObjCTypes.Int8PtrTy));
5528 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5529 Match, Next);
5530
5531 CGF.EmitBlock(Match);
5532 }
5533
5534 if (CatchBody) {
5535 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5536 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5537
5538 // Cleanups must call objc_end_catch.
5539 //
5540 // FIXME: It seems incorrect for objc_begin_catch to be inside
5541 // this context, but this matches gcc.
5542 CGF.PushCleanupBlock(MatchEnd);
5543 CGF.setInvokeDest(MatchHandler);
5544
5545 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005546 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005547
5548 // Bind the catch parameter if it exists.
5549 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005550 ExcObject =
5551 CGF.Builder.CreateBitCast(ExcObject,
5552 CGF.ConvertType(CatchParam->getType()));
5553 // CatchParam is a ParmVarDecl because of the grammar
5554 // construction used to handle this, but for codegen purposes
5555 // we treat this as a local decl.
5556 CGF.EmitLocalBlockVarDecl(*CatchParam);
5557 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005558 }
5559
5560 CGF.ObjCEHValueStack.push_back(ExcObject);
5561 CGF.EmitStmt(CatchBody);
5562 CGF.ObjCEHValueStack.pop_back();
5563
5564 CGF.EmitBranchThroughCleanup(FinallyEnd);
5565
5566 CGF.EmitBlock(MatchHandler);
5567
5568 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5569 // We are required to emit this call to satisfy LLVM, even
5570 // though we don't use the result.
5571 llvm::SmallVector<llvm::Value*, 8> Args;
5572 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005573 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005574 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5575 0));
5576 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5577 CGF.Builder.CreateStore(Exc, RethrowPtr);
5578 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5579
5580 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5581
5582 CGF.EmitBlock(MatchEnd);
5583
5584 // Unfortunately, we also have to generate another EH frame here
5585 // in case this throws.
5586 llvm::BasicBlock *MatchEndHandler =
5587 CGF.createBasicBlock("match.end.handler");
5588 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005589 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005590 Cont, MatchEndHandler,
5591 Args.begin(), Args.begin());
5592
5593 CGF.EmitBlock(Cont);
5594 if (Info.SwitchBlock)
5595 CGF.EmitBlock(Info.SwitchBlock);
5596 if (Info.EndBlock)
5597 CGF.EmitBlock(Info.EndBlock);
5598
5599 CGF.EmitBlock(MatchEndHandler);
5600 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5601 // We are required to emit this call to satisfy LLVM, even
5602 // though we don't use the result.
5603 Args.clear();
5604 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005605 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005606 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5607 0));
5608 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5609 CGF.Builder.CreateStore(Exc, RethrowPtr);
5610 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5611
5612 if (Next)
5613 CGF.EmitBlock(Next);
5614 } else {
5615 assert(!Next && "catchup should be last handler.");
5616
5617 CGF.Builder.CreateStore(Exc, RethrowPtr);
5618 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5619 }
5620 }
5621
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005622 // Pop the cleanup entry, the @finally is outside this cleanup
5623 // scope.
5624 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5625 CGF.setInvokeDest(PrevLandingPad);
5626
5627 CGF.EmitBlock(FinallyBlock);
5628
5629 if (isTry) {
5630 if (const ObjCAtFinallyStmt* FinallyStmt =
5631 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5632 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5633 } else {
5634 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5635 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005636 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005637 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005638
5639 if (Info.SwitchBlock)
5640 CGF.EmitBlock(Info.SwitchBlock);
5641 if (Info.EndBlock)
5642 CGF.EmitBlock(Info.EndBlock);
5643
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005644 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005645 CGF.EmitBranch(FinallyEnd);
5646
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005647 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005648 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005649 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005650 CGF.Builder.CreateUnreachable();
5651
5652 CGF.EmitBlock(FinallyEnd);
5653}
5654
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005655/// EmitThrowStmt - Generate code for a throw statement.
5656void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5657 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005658 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005659 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005660 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005661 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005662 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5663 "Unexpected rethrow outside @catch block.");
5664 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005665 }
5666
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005667 llvm::Value *ExceptionAsObject =
5668 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5669 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5670 if (InvokeDest) {
5671 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005672 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005673 Cont, InvokeDest,
5674 &ExceptionAsObject, &ExceptionAsObject + 1);
5675 CGF.EmitBlock(Cont);
5676 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005677 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005678 CGF.Builder.CreateUnreachable();
5679
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005680 // Clear the insertion point to indicate we are in unreachable code.
5681 CGF.Builder.ClearInsertionPoint();
5682}
Daniel Dunbare588b992009-03-01 04:46:24 +00005683
5684llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005685CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5686 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005687 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005688
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005689 // If we don't need a definition, return the entry if found or check
5690 // if we use an external reference.
5691 if (!ForDefinition) {
5692 if (Entry)
5693 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005694
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005695 // If this type (or a super class) has the __objc_exception__
5696 // attribute, emit an external reference.
5697 if (hasObjCExceptionAttribute(ID))
5698 return Entry =
5699 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5700 llvm::GlobalValue::ExternalLinkage,
5701 0,
5702 (std::string("OBJC_EHTYPE_$_") +
5703 ID->getIdentifier()->getName()),
5704 &CGM.getModule());
5705 }
5706
5707 // Otherwise we need to either make a new entry or fill in the
5708 // initializer.
5709 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005710 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005711 std::string VTableName = "objc_ehtype_vtable";
5712 llvm::GlobalVariable *VTableGV =
5713 CGM.getModule().getGlobalVariable(VTableName);
5714 if (!VTableGV)
5715 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5716 llvm::GlobalValue::ExternalLinkage,
5717 0, VTableName, &CGM.getModule());
5718
5719 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5720
5721 std::vector<llvm::Constant*> Values(3);
5722 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5723 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005724 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005725 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5726
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005727 if (Entry) {
5728 Entry->setInitializer(Init);
5729 } else {
5730 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5731 llvm::GlobalValue::WeakAnyLinkage,
5732 Init,
5733 (std::string("OBJC_EHTYPE_$_") +
5734 ID->getIdentifier()->getName()),
5735 &CGM.getModule());
5736 }
5737
Daniel Dunbar04d40782009-04-14 06:00:08 +00005738 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005739 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005740 Entry->setAlignment(8);
5741
5742 if (ForDefinition) {
5743 Entry->setSection("__DATA,__objc_const");
5744 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5745 } else {
5746 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5747 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005748
5749 return Entry;
5750}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005751
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005752/* *** */
5753
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005754CodeGen::CGObjCRuntime *
5755CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005756 return new CGObjCMac(CGM);
5757}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005758
5759CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005760CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005761 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005762}