blob: 8f1404da65dd229577a90094598bff8a89408d67 [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
Mike Stumpf5408fe2009-05-16 07:57:57 +0000143 // FIXME: We should find a nicer way to make the labels for metadata, string
144 // concatenation is lame.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000145
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;
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000813
814 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
815 std::vector<llvm::GlobalValue*> DefinedNonLazyClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000816
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000817 /// DefinedCategories - List of defined categories.
818 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000819
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000820 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
821 std::vector<llvm::GlobalValue*> DefinedNonLazyCategories;
822
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000823 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000824 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000825 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000826
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000827 /// GetNameForMethod - Return a name for the given method.
828 /// \param[out] NameOut - The return value.
829 void GetNameForMethod(const ObjCMethodDecl *OMD,
830 const ObjCContainerDecl *CD,
831 std::string &NameOut);
832
833 /// GetMethodVarName - Return a unique constant for the given
834 /// selector's name. The return value has type char *.
835 llvm::Constant *GetMethodVarName(Selector Sel);
836 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
837 llvm::Constant *GetMethodVarName(const std::string &Name);
838
839 /// GetMethodVarType - Return a unique constant for the given
840 /// selector's name. The return value has type char *.
841
842 // FIXME: This is a horrible name.
843 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000844 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000845
846 /// GetPropertyName - Return a unique constant for the given
847 /// name. The return value has type char *.
848 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
849
850 // FIXME: This can be dropped once string functions are unified.
851 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
852 const Decl *Container);
853
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000854 /// GetClassName - Return a unique constant for the given selector's
855 /// name. The return value has type char *.
856 llvm::Constant *GetClassName(IdentifierInfo *Ident);
857
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000858 /// BuildIvarLayout - Builds ivar layout bitmap for the class
859 /// implementation for the __strong or __weak case.
860 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000861 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
862 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000863
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000864 void BuildAggrIvarRecordLayout(const RecordType *RT,
865 unsigned int BytePos, bool ForStrongLayout,
866 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000867 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000868 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000869 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000870 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000871 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000872 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000873
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000874 /// GetIvarLayoutName - Returns a unique constant for the given
875 /// ivar layout bitmap.
876 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
877 const ObjCCommonTypesHelper &ObjCTypes);
878
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000879 /// EmitPropertyList - Emit the given property list. The return
880 /// value has type PropertyListPtrTy.
881 llvm::Constant *EmitPropertyList(const std::string &Name,
882 const Decl *Container,
883 const ObjCContainerDecl *OCD,
884 const ObjCCommonTypesHelper &ObjCTypes);
885
Fariborz Jahanianda320092009-01-29 19:24:30 +0000886 /// GetProtocolRef - Return a reference to the internal protocol
887 /// description, creating an empty one if it has not been
888 /// defined. The return value has type ProtocolPtrTy.
889 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000890
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000891 /// CreateMetadataVar - Create a global variable with internal
892 /// linkage for use by the Objective-C runtime.
893 ///
894 /// This is a convenience wrapper which not only creates the
895 /// variable, but also sets the section and alignment and adds the
896 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000897 ///
898 /// \param Name - The variable name.
899 /// \param Init - The variable initializer; this is also used to
900 /// define the type of the variable.
901 /// \param Section - The section the variable should go into, or 0.
902 /// \param Align - The alignment for the variable, or 0.
903 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000904 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000905 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
906 llvm::Constant *Init,
907 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000908 unsigned Align,
909 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000910
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000911 /// GetNamedIvarList - Return the list of ivars in the interface
912 /// itself (not including super classes and not including unnamed
913 /// bitfields).
914 ///
915 /// For the non-fragile ABI, this also includes synthesized property
916 /// ivars.
917 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
918 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000919
920 CodeGen::RValue EmitLegacyMessageSend(CodeGen::CodeGenFunction &CGF,
921 QualType ResultType,
922 llvm::Value *Sel,
923 llvm::Value *Arg0,
924 QualType Arg0Ty,
925 bool IsSuper,
926 const CallArgList &CallArgs,
927 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000928
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000929public:
930 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
931 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000932
Steve Naroff33fdb732009-03-31 16:53:37 +0000933 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000934
935 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
936 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000937
938 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
939
940 /// GetOrEmitProtocol - Get the protocol object for the given
941 /// declaration, emitting it if necessary. The return value has type
942 /// ProtocolPtrTy.
943 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
944
945 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
946 /// object for the given declaration, emitting it if needed. These
947 /// forward references will be filled in with empty bodies if no
948 /// definition is seen. The return value has type ProtocolPtrTy.
949 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000950};
951
952class CGObjCMac : public CGObjCCommonMac {
953private:
954 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000955 /// EmitImageInfo - Emit the image info marker used to encode some module
956 /// level information.
957 void EmitImageInfo();
958
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000959 /// EmitModuleInfo - Another marker encoding module level
960 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000961 void EmitModuleInfo();
962
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000963 /// EmitModuleSymols - Emit module symbols, the list of defined
964 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000965 llvm::Constant *EmitModuleSymbols();
966
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000967 /// FinishModule - Write out global data structures at the end of
968 /// processing a translation unit.
969 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000970
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000971 /// EmitClassExtension - Generate the class extension structure used
972 /// to store the weak ivar layout and properties. The return value
973 /// has type ClassExtensionPtrTy.
974 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
975
976 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
977 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000978 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000979 const ObjCInterfaceDecl *ID);
980
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000981 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000982 QualType ResultType,
983 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000984 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000985 QualType Arg0Ty,
986 bool IsSuper,
987 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000988
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000989 /// EmitIvarList - Emit the ivar list for the given
990 /// implementation. If ForClass is true the list of class ivars
991 /// (i.e. metaclass ivars) is emitted, otherwise the list of
992 /// interface ivars will be emitted. The return value has type
993 /// IvarListPtrTy.
994 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000995 bool ForClass);
996
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000997 /// EmitMetaClass - Emit a forward reference to the class structure
998 /// for the metaclass of the given interface. The return value has
999 /// type ClassPtrTy.
1000 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1001
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001002 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001003 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001004 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1005 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001006 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001007
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001008 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001009
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001010 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001011
1012 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001013 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001014 llvm::Constant *EmitMethodList(const std::string &Name,
1015 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001016 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001017
1018 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001019 /// method declarations.
1020 /// - TypeName: The name for the type containing the methods.
1021 /// - IsProtocol: True iff these methods are for a protocol.
1022 /// - ClassMethds: True iff these are class methods.
1023 /// - Required: When true, only "required" methods are
1024 /// listed. Similarly, when false only "optional" methods are
1025 /// listed. For classes this should always be true.
1026 /// - begin, end: The method list to output.
1027 ///
1028 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001029 llvm::Constant *EmitMethodDescList(const std::string &Name,
1030 const char *Section,
1031 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001032
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001033 /// GetOrEmitProtocol - Get the protocol object for the given
1034 /// declaration, emitting it if necessary. The return value has type
1035 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001036 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001037
1038 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1039 /// object for the given declaration, emitting it if needed. These
1040 /// forward references will be filled in with empty bodies if no
1041 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001042 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001043
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001044 /// EmitProtocolExtension - Generate the protocol extension
1045 /// structure used to store optional instance and class methods, and
1046 /// protocol properties. The return value has type
1047 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001048 llvm::Constant *
1049 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1050 const ConstantVector &OptInstanceMethods,
1051 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001052
1053 /// EmitProtocolList - Generate the list of referenced
1054 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001055 llvm::Constant *EmitProtocolList(const std::string &Name,
1056 ObjCProtocolDecl::protocol_iterator begin,
1057 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001058
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001059 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1060 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001061 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001062
Fariborz Jahanianda320092009-01-29 19:24:30 +00001063 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001064 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001065
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001066 virtual llvm::Function *ModuleInitFunction();
1067
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001068 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001069 QualType ResultType,
1070 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001071 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001072 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001073 const CallArgList &CallArgs,
1074 const ObjCMethodDecl *Method);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001075
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001076 virtual CodeGen::RValue
1077 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001078 QualType ResultType,
1079 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001080 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001081 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001082 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001083 bool IsClassMessage,
1084 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001085
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001086 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001087 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001088
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001089 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001090
1091 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1092 /// untyped one.
1093 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1094 const ObjCMethodDecl *Method);
1095
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001096 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001097
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001098 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001099
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001100 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001101 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001102
Chris Lattner74391b42009-03-22 21:03:39 +00001103 virtual llvm::Constant *GetPropertyGetFunction();
1104 virtual llvm::Constant *GetPropertySetFunction();
1105 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001106
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001107 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1108 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001109 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1110 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001111 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001112 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001113 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1114 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001115 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1116 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001117 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1118 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001119 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1120 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001121
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001122 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1123 QualType ObjectTy,
1124 llvm::Value *BaseValue,
1125 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001126 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001127 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001128 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001129 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001130};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001131
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001132class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001133private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001134 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001135 llvm::GlobalVariable* ObjCEmptyCacheVar;
1136 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001137
Daniel Dunbar11394522009-04-18 08:51:00 +00001138 /// SuperClassReferences - uniqued super class references.
1139 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1140
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001141 /// MetaClassReferences - uniqued meta class references.
1142 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001143
1144 /// EHTypeReferences - uniqued class ehtype references.
1145 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001146
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001147 /// NonLegacyDispatchMethods - List of methods for which we do *not* generate
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001148 /// legacy messaging dispatch.
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001149 llvm::DenseSet<Selector> NonLegacyDispatchMethods;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001150
1151 /// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001152 /// NonLegacyDispatchMethods; false otherwise.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001153 bool LegacyDispatchedSelector(Selector Sel);
1154
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001155 /// FinishNonFragileABIModule - Write out global data structures at the end of
1156 /// processing a translation unit.
1157 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001158
Daniel Dunbar463b8762009-05-15 21:48:48 +00001159 /// AddModuleClassList - Add the given list of class pointers to the
1160 /// module with the provided symbol and section names.
1161 void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
1162 const char *SymbolName,
1163 const char *SectionName);
1164
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001165 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1166 unsigned InstanceStart,
1167 unsigned InstanceSize,
1168 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001169 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1170 llvm::Constant *IsAGV,
1171 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001172 llvm::Constant *ClassRoGV,
1173 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001174
1175 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1176
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001177 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1178
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001179 /// EmitMethodList - Emit the method list for the given
1180 /// implementation. The return value has type MethodListnfABITy.
1181 llvm::Constant *EmitMethodList(const std::string &Name,
1182 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001183 const ConstantVector &Methods);
1184 /// EmitIvarList - Emit the ivar list for the given
1185 /// implementation. If ForClass is true the list of class ivars
1186 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1187 /// interface ivars will be emitted. The return value has type
1188 /// IvarListnfABIPtrTy.
1189 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001190
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001191 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001192 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001193 unsigned long int offset);
1194
Fariborz Jahanianda320092009-01-29 19:24:30 +00001195 /// GetOrEmitProtocol - Get the protocol object for the given
1196 /// declaration, emitting it if necessary. The return value has type
1197 /// ProtocolPtrTy.
1198 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1199
1200 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1201 /// object for the given declaration, emitting it if needed. These
1202 /// forward references will be filled in with empty bodies if no
1203 /// definition is seen. The return value has type ProtocolPtrTy.
1204 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1205
1206 /// EmitProtocolList - Generate the list of referenced
1207 /// protocols. The return value has type ProtocolListPtrTy.
1208 llvm::Constant *EmitProtocolList(const std::string &Name,
1209 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001210 ObjCProtocolDecl::protocol_iterator end);
1211
1212 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1213 QualType ResultType,
1214 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001215 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001216 QualType Arg0Ty,
1217 bool IsSuper,
1218 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001219
1220 /// GetClassGlobal - Return the global variable for the Objective-C
1221 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001222 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1223
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001224 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001225 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001226 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001227 const ObjCInterfaceDecl *ID);
1228
1229 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1230 /// for the given super class reference.
1231 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1232 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001233
1234 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1235 /// meta-data
1236 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1237 const ObjCInterfaceDecl *ID);
1238
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001239 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1240 /// the given ivar.
1241 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001242 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001243 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001244 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001245
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001246 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1247 /// for the given selector.
1248 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001249
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001250 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001251 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001252 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1253 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001254
1255 const char *getMetaclassSymbolPrefix() const {
1256 return "OBJC_METACLASS_$_";
1257 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001258
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001259 const char *getClassSymbolPrefix() const {
1260 return "OBJC_CLASS_$_";
1261 }
1262
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001263 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001264 uint32_t &InstanceStart,
1265 uint32_t &InstanceSize);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001266
1267 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001268 Selector GetNullarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001269 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1270 return CGM.getContext().Selectors.getSelector(0, &II);
1271 }
1272
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001273 Selector GetUnarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001274 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1275 return CGM.getContext().Selectors.getSelector(1, &II);
1276 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001277
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001278 /// ImplementationIsNonLazy - Check whether the given category or
1279 /// class implementation is "non-lazy".
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00001280 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001281
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001282public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001283 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001284 // FIXME. All stubs for now!
1285 virtual llvm::Function *ModuleInitFunction();
1286
1287 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1288 QualType ResultType,
1289 Selector Sel,
1290 llvm::Value *Receiver,
1291 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001292 const CallArgList &CallArgs,
1293 const ObjCMethodDecl *Method);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001294
1295 virtual CodeGen::RValue
1296 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1297 QualType ResultType,
1298 Selector Sel,
1299 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001300 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001301 llvm::Value *Receiver,
1302 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001303 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001304
1305 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001306 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001307
1308 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001309 { return EmitSelector(Builder, Sel); }
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001310
1311 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1312 /// untyped one.
1313 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1314 const ObjCMethodDecl *Method)
1315 { return EmitSelector(Builder, Method->getSelector()); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001316
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001317 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001318
1319 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001320 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001321 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001322
Chris Lattner74391b42009-03-22 21:03:39 +00001323 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001324 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001325 }
Chris Lattner74391b42009-03-22 21:03:39 +00001326 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001327 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001328 }
Chris Lattner74391b42009-03-22 21:03:39 +00001329 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001330 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001331 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001332
1333 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001334 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001335 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001336 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001337 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001338 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001339 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001340 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001341 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001342 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001343 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001344 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001345 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001346 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001347 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1348 QualType ObjectTy,
1349 llvm::Value *BaseValue,
1350 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001351 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001352 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001353 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001354 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001355};
1356
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001357} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001358
1359/* *** Helper Functions *** */
1360
1361/// getConstantGEP() - Help routine to construct simple GEPs.
1362static llvm::Constant *getConstantGEP(llvm::Constant *C,
1363 unsigned idx0,
1364 unsigned idx1) {
1365 llvm::Value *Idxs[] = {
1366 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1367 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1368 };
1369 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1370}
1371
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001372/// hasObjCExceptionAttribute - Return true if this class or any super
1373/// class has the __objc_exception__ attribute.
1374static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001375 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001376 return true;
1377 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1378 return hasObjCExceptionAttribute(Super);
1379 return false;
1380}
1381
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001382/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001383
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001384CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1385 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001386{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001387 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001388 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001389}
1390
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001391/// GetClass - Return a reference to the class for the given interface
1392/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001393llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001394 const ObjCInterfaceDecl *ID) {
1395 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001396}
1397
1398/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001399llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001400 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001401}
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001402llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1403 *Method) {
1404 return EmitSelector(Builder, Method->getSelector());
1405}
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001406
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001407/// Generate a constant CFString object.
1408/*
1409 struct __builtin_CFString {
1410 const int *isa; // point to __CFConstantStringClassReference
1411 int flags;
1412 const char *str;
1413 long length;
1414 };
1415*/
1416
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001417llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001418 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001419 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001420}
1421
1422/// Generates a message send where the super is the receiver. This is
1423/// a message send to self with special delivery semantics indicating
1424/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001425CodeGen::RValue
1426CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001427 QualType ResultType,
1428 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001429 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001430 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001431 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001432 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001433 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001434 // Create and init a super structure; this is a (receiver, class)
1435 // pair we will pass to objc_msgSendSuper.
1436 llvm::Value *ObjCSuper =
1437 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1438 llvm::Value *ReceiverAsObject =
1439 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1440 CGF.Builder.CreateStore(ReceiverAsObject,
1441 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001442
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001443 // If this is a class message the metaclass is passed as the target.
1444 llvm::Value *Target;
1445 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001446 if (isCategoryImpl) {
1447 // Message sent to 'super' in a class method defined in a category
1448 // implementation requires an odd treatment.
1449 // If we are in a class method, we must retrieve the
1450 // _metaclass_ for the current class, pointed at by
1451 // the class's "isa" pointer. The following assumes that
1452 // isa" is the first ivar in a class (which it must be).
1453 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1454 Target = CGF.Builder.CreateStructGEP(Target, 0);
1455 Target = CGF.Builder.CreateLoad(Target);
1456 }
1457 else {
1458 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1459 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1460 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1461 Target = Super;
1462 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001463 } else {
1464 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1465 }
Mike Stumpf5408fe2009-05-16 07:57:57 +00001466 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1467 // ObjCTypes types.
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001468 const llvm::Type *ClassTy =
1469 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001470 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001471 CGF.Builder.CreateStore(Target,
1472 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001473 return EmitLegacyMessageSend(CGF, ResultType,
1474 EmitSelector(CGF.Builder, Sel),
1475 ObjCSuper, ObjCTypes.SuperPtrCTy,
1476 true, CallArgs, ObjCTypes);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001477}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001478
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001479/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001480CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001481 QualType ResultType,
1482 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001483 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001484 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001485 const CallArgList &CallArgs,
1486 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001487 return EmitLegacyMessageSend(CGF, ResultType,
1488 EmitSelector(CGF.Builder, Sel),
1489 Receiver, CGF.getContext().getObjCIdType(),
1490 false, CallArgs, ObjCTypes);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001491}
1492
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001493CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1494 CodeGen::CodeGenFunction &CGF,
1495 QualType ResultType,
1496 llvm::Value *Sel,
1497 llvm::Value *Arg0,
1498 QualType Arg0Ty,
1499 bool IsSuper,
1500 const CallArgList &CallArgs,
1501 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001502 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001503 if (!IsSuper)
1504 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001505 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001506 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001507 CGF.getContext().getObjCSelType()));
1508 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001509
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001510 CodeGenTypes &Types = CGM.getTypes();
1511 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001512 // In 64bit ABI, type must be assumed VARARG. In 32bit abi,
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001513 // it seems not to matter.
1514 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1515
1516 llvm::Constant *Fn = NULL;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001517 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001518 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1519 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001520 } else if (ResultType->isFloatingType()) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001521 if (ObjCABI == 2) {
1522 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1523 BuiltinType::Kind k = BT->getKind();
1524 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1525 : ObjCTypes.getSendFn2(IsSuper);
1526 }
1527 }
1528 else
Mike Stumpf5408fe2009-05-16 07:57:57 +00001529 // FIXME. This currently matches gcc's API for x86-32. May need to change
1530 // for others if we have their API.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001531 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001532 } else {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001533 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1534 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001535 }
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001536 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001537 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001538 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001539}
1540
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001541llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001542 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001543 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001544 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001545 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1546
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001547 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1548 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001549}
1550
Fariborz Jahanianda320092009-01-29 19:24:30 +00001551void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001552 // FIXME: We shouldn't need this, the protocol decl should contain enough
1553 // information to tell us whether this was a declaration or a definition.
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001554 DefinedProtocols.insert(PD->getIdentifier());
1555
1556 // If we have generated a forward reference to this protocol, emit
1557 // it now. Otherwise do nothing, the protocol objects are lazily
1558 // emitted.
1559 if (Protocols.count(PD->getIdentifier()))
1560 GetOrEmitProtocol(PD);
1561}
1562
Fariborz Jahanianda320092009-01-29 19:24:30 +00001563llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001564 if (DefinedProtocols.count(PD->getIdentifier()))
1565 return GetOrEmitProtocol(PD);
1566 return GetOrEmitProtocolRef(PD);
1567}
1568
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001569/*
1570 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1571 struct _objc_protocol {
1572 struct _objc_protocol_extension *isa;
1573 char *protocol_name;
1574 struct _objc_protocol_list *protocol_list;
1575 struct _objc__method_prototype_list *instance_methods;
1576 struct _objc__method_prototype_list *class_methods
1577 };
1578
1579 See EmitProtocolExtension().
1580*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001581llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1582 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1583
1584 // Early exit if a defining object has already been generated.
1585 if (Entry && Entry->hasInitializer())
1586 return Entry;
1587
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001588 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001589 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001590 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1591
Chris Lattner8ec03f52008-11-24 03:54:41 +00001592 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001593
1594 // Construct method lists.
1595 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1596 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001597 for (ObjCProtocolDecl::instmeth_iterator
1598 i = PD->instmeth_begin(CGM.getContext()),
1599 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001600 ObjCMethodDecl *MD = *i;
1601 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1602 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1603 OptInstanceMethods.push_back(C);
1604 } else {
1605 InstanceMethods.push_back(C);
1606 }
1607 }
1608
Douglas Gregor6ab35242009-04-09 21:40:53 +00001609 for (ObjCProtocolDecl::classmeth_iterator
1610 i = PD->classmeth_begin(CGM.getContext()),
1611 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001612 ObjCMethodDecl *MD = *i;
1613 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1614 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1615 OptClassMethods.push_back(C);
1616 } else {
1617 ClassMethods.push_back(C);
1618 }
1619 }
1620
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001621 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001622 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001623 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001624 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001625 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001626 PD->protocol_begin(),
1627 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001628 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001629 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1630 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001631 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1632 InstanceMethods);
1633 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001634 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1635 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001636 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1637 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001638 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1639 Values);
1640
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001641 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001642 // Already created, fix the linkage and update the initializer.
1643 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001644 Entry->setInitializer(Init);
1645 } else {
1646 Entry =
1647 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1648 llvm::GlobalValue::InternalLinkage,
1649 Init,
1650 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1651 &CGM.getModule());
1652 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001653 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001654 UsedGlobals.push_back(Entry);
1655 // FIXME: Is this necessary? Why only for protocol?
1656 Entry->setAlignment(4);
1657 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001658
1659 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001660}
1661
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001662llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001663 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1664
1665 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001666 // We use the initializer as a marker of whether this is a forward
1667 // reference or not. At module finalization we add the empty
1668 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001669 Entry =
1670 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001671 llvm::GlobalValue::ExternalLinkage,
1672 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001673 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001674 &CGM.getModule());
1675 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001676 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001677 UsedGlobals.push_back(Entry);
1678 // FIXME: Is this necessary? Why only for protocol?
1679 Entry->setAlignment(4);
1680 }
1681
1682 return Entry;
1683}
1684
1685/*
1686 struct _objc_protocol_extension {
1687 uint32_t size;
1688 struct objc_method_description_list *optional_instance_methods;
1689 struct objc_method_description_list *optional_class_methods;
1690 struct objc_property_list *instance_properties;
1691 };
1692*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001693llvm::Constant *
1694CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1695 const ConstantVector &OptInstanceMethods,
1696 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001697 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001698 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001699 std::vector<llvm::Constant*> Values(4);
1700 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001701 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001702 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1703 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001704 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1705 OptInstanceMethods);
1706 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001707 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1708 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001709 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1710 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001711 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1712 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001713 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001714
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001715 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001716 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1717 Values[3]->isNullValue())
1718 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1719
1720 llvm::Constant *Init =
1721 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001722
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001723 // No special section, but goes in llvm.used
1724 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1725 Init,
1726 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001727}
1728
1729/*
1730 struct objc_protocol_list {
1731 struct objc_protocol_list *next;
1732 long count;
1733 Protocol *list[];
1734 };
1735*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001736llvm::Constant *
1737CGObjCMac::EmitProtocolList(const std::string &Name,
1738 ObjCProtocolDecl::protocol_iterator begin,
1739 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001740 std::vector<llvm::Constant*> ProtocolRefs;
1741
Daniel Dunbardbc933702008-08-21 21:57:41 +00001742 for (; begin != end; ++begin)
1743 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001744
1745 // Just return null for empty protocol lists
1746 if (ProtocolRefs.empty())
1747 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1748
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001749 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001750 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1751
1752 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001753 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001754 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1755 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1756 Values[2] =
1757 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1758 ProtocolRefs.size()),
1759 ProtocolRefs);
1760
1761 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1762 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001763 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001764 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001765 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1766}
1767
1768/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001769 struct _objc_property {
1770 const char * const name;
1771 const char * const attributes;
1772 };
1773
1774 struct _objc_property_list {
1775 uint32_t entsize; // sizeof (struct _objc_property)
1776 uint32_t prop_count;
1777 struct _objc_property[prop_count];
1778 };
1779*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001780llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1781 const Decl *Container,
1782 const ObjCContainerDecl *OCD,
1783 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001784 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001785 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1786 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001787 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001788 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001789 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001790 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1791 Prop));
1792 }
1793
1794 // Return null for empty list.
1795 if (Properties.empty())
1796 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1797
1798 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001799 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001800 std::vector<llvm::Constant*> Values(3);
1801 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1802 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1803 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1804 Properties.size());
1805 Values[2] = llvm::ConstantArray::get(AT, Properties);
1806 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1807
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001808 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001809 CreateMetadataVar(Name, Init,
1810 (ObjCABI == 2) ? "__DATA, __objc_const" :
1811 "__OBJC,__property,regular,no_dead_strip",
1812 (ObjCABI == 2) ? 8 : 4,
1813 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001814 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001815}
1816
1817/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001818 struct objc_method_description_list {
1819 int count;
1820 struct objc_method_description list[];
1821 };
1822*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001823llvm::Constant *
1824CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1825 std::vector<llvm::Constant*> Desc(2);
1826 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1827 ObjCTypes.SelectorPtrTy);
1828 Desc[1] = GetMethodVarType(MD);
1829 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1830 Desc);
1831}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001832
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001833llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1834 const char *Section,
1835 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001836 // Return null for empty list.
1837 if (Methods.empty())
1838 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1839
1840 std::vector<llvm::Constant*> Values(2);
1841 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1842 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1843 Methods.size());
1844 Values[1] = llvm::ConstantArray::get(AT, Methods);
1845 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1846
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001847 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001848 return llvm::ConstantExpr::getBitCast(GV,
1849 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001850}
1851
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001852/*
1853 struct _objc_category {
1854 char *category_name;
1855 char *class_name;
1856 struct _objc_method_list *instance_methods;
1857 struct _objc_method_list *class_methods;
1858 struct _objc_protocol_list *protocols;
1859 uint32_t size; // <rdar://4585769>
1860 struct _objc_property_list *instance_properties;
1861 };
1862 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001863void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001864 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001865
Mike Stumpf5408fe2009-05-16 07:57:57 +00001866 // FIXME: This is poor design, the OCD should have a pointer to the category
1867 // decl. Additionally, note that Category can be null for the @implementation
1868 // w/o an @interface case. Sema should just create one for us as it does for
1869 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001870 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001871 const ObjCCategoryDecl *Category =
1872 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001873 std::string ExtName(Interface->getNameAsString() + "_" +
1874 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001875
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001876 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001877 for (ObjCCategoryImplDecl::instmeth_iterator
1878 i = OCD->instmeth_begin(CGM.getContext()),
1879 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001880 // Instance methods should always be defined.
1881 InstanceMethods.push_back(GetMethodConstant(*i));
1882 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001883 for (ObjCCategoryImplDecl::classmeth_iterator
1884 i = OCD->classmeth_begin(CGM.getContext()),
1885 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001886 // Class methods should always be defined.
1887 ClassMethods.push_back(GetMethodConstant(*i));
1888 }
1889
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001890 std::vector<llvm::Constant*> Values(7);
1891 Values[0] = GetClassName(OCD->getIdentifier());
1892 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001893 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001894 Values[2] =
1895 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1896 ExtName,
1897 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001898 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001899 Values[3] =
1900 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001901 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001902 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001903 if (Category) {
1904 Values[4] =
1905 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1906 Category->protocol_begin(),
1907 Category->protocol_end());
1908 } else {
1909 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1910 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001911 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001912
1913 // If there is no category @interface then there can be no properties.
1914 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001915 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001916 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001917 } else {
1918 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1919 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001920
1921 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1922 Values);
1923
1924 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001925 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1926 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001927 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001928 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001929}
1930
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001931// FIXME: Get from somewhere?
1932enum ClassFlags {
1933 eClassFlags_Factory = 0x00001,
1934 eClassFlags_Meta = 0x00002,
1935 // <rdr://5142207>
1936 eClassFlags_HasCXXStructors = 0x02000,
1937 eClassFlags_Hidden = 0x20000,
1938 eClassFlags_ABI2_Hidden = 0x00010,
1939 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1940};
1941
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001942/*
1943 struct _objc_class {
1944 Class isa;
1945 Class super_class;
1946 const char *name;
1947 long version;
1948 long info;
1949 long instance_size;
1950 struct _objc_ivar_list *ivars;
1951 struct _objc_method_list *methods;
1952 struct _objc_cache *cache;
1953 struct _objc_protocol_list *protocols;
1954 // Objective-C 1.0 extensions (<rdr://4585769>)
1955 const char *ivar_layout;
1956 struct _objc_class_ext *ext;
1957 };
1958
1959 See EmitClassExtension();
1960 */
1961void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001962 DefinedSymbols.insert(ID->getIdentifier());
1963
Chris Lattner8ec03f52008-11-24 03:54:41 +00001964 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001965 // FIXME: Gross
1966 ObjCInterfaceDecl *Interface =
1967 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001968 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001969 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001970 Interface->protocol_begin(),
1971 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001972 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001973 unsigned Size =
1974 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001975
1976 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001977 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001978 Flags |= eClassFlags_Hidden;
1979
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001980 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001981 for (ObjCImplementationDecl::instmeth_iterator
1982 i = ID->instmeth_begin(CGM.getContext()),
1983 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001984 // Instance methods should always be defined.
1985 InstanceMethods.push_back(GetMethodConstant(*i));
1986 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001987 for (ObjCImplementationDecl::classmeth_iterator
1988 i = ID->classmeth_begin(CGM.getContext()),
1989 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001990 // Class methods should always be defined.
1991 ClassMethods.push_back(GetMethodConstant(*i));
1992 }
1993
Douglas Gregor653f1b12009-04-23 01:02:12 +00001994 for (ObjCImplementationDecl::propimpl_iterator
1995 i = ID->propimpl_begin(CGM.getContext()),
1996 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001997 ObjCPropertyImplDecl *PID = *i;
1998
1999 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2000 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2001
2002 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
2003 if (llvm::Constant *C = GetMethodConstant(MD))
2004 InstanceMethods.push_back(C);
2005 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
2006 if (llvm::Constant *C = GetMethodConstant(MD))
2007 InstanceMethods.push_back(C);
2008 }
2009 }
2010
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002011 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00002012 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002013 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002014 // Record a reference to the super class.
2015 LazySymbols.insert(Super->getIdentifier());
2016
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002017 Values[ 1] =
2018 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2019 ObjCTypes.ClassPtrTy);
2020 } else {
2021 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2022 }
2023 Values[ 2] = GetClassName(ID->getIdentifier());
2024 // Version is always 0.
2025 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2026 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2027 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002028 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002029 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002030 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002031 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002032 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002033 // cache is always NULL.
2034 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2035 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002036 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002037 Values[11] = EmitClassExtension(ID);
2038 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2039 Values);
2040
2041 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002042 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2043 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002044 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002045 DefinedClasses.push_back(GV);
2046}
2047
2048llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2049 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002050 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002051 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002052 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002053
Daniel Dunbar04d40782009-04-14 06:00:08 +00002054 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002055 Flags |= eClassFlags_Hidden;
2056
2057 std::vector<llvm::Constant*> Values(12);
2058 // The isa for the metaclass is the root of the hierarchy.
2059 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2060 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2061 Root = Super;
2062 Values[ 0] =
2063 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2064 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002065 // The super class for the metaclass is emitted as the name of the
2066 // super class. The runtime fixes this up to point to the
2067 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002068 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2069 Values[ 1] =
2070 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2071 ObjCTypes.ClassPtrTy);
2072 } else {
2073 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2074 }
2075 Values[ 2] = GetClassName(ID->getIdentifier());
2076 // Version is always 0.
2077 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2078 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2079 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002080 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002081 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002082 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002083 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002084 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002085 // cache is always NULL.
2086 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2087 Values[ 9] = Protocols;
2088 // ivar_layout for metaclass is always NULL.
2089 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2090 // The class extension is always unused for metaclasses.
2091 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2092 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2093 Values);
2094
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002095 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002096 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002097
2098 // Check for a forward reference.
2099 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2100 if (GV) {
2101 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2102 "Forward metaclass reference has incorrect type.");
2103 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2104 GV->setInitializer(Init);
2105 } else {
2106 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2107 llvm::GlobalValue::InternalLinkage,
2108 Init, Name,
2109 &CGM.getModule());
2110 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002111 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002112 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002113 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002114
2115 return GV;
2116}
2117
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002118llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002119 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002120
Mike Stumpf5408fe2009-05-16 07:57:57 +00002121 // FIXME: Should we look these up somewhere other than the module. Its a bit
2122 // silly since we only generate these while processing an implementation, so
2123 // exactly one pointer would work if know when we entered/exitted an
2124 // implementation block.
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002125
2126 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002127 // Previously, metaclass with internal linkage may have been defined.
2128 // pass 'true' as 2nd argument so it is returned.
2129 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002130 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2131 "Forward metaclass reference has incorrect type.");
2132 return GV;
2133 } else {
2134 // Generate as an external reference to keep a consistent
2135 // module. This will be patched up when we emit the metaclass.
2136 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2137 llvm::GlobalValue::ExternalLinkage,
2138 0,
2139 Name,
2140 &CGM.getModule());
2141 }
2142}
2143
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002144/*
2145 struct objc_class_ext {
2146 uint32_t size;
2147 const char *weak_ivar_layout;
2148 struct _objc_property_list *properties;
2149 };
2150*/
2151llvm::Constant *
2152CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2153 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002154 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002155
2156 std::vector<llvm::Constant*> Values(3);
2157 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002158 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002159 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002160 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002161
2162 // Return null if no extension bits are used.
2163 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2164 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2165
2166 llvm::Constant *Init =
2167 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002168 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002169 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2170 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002171}
2172
2173/*
2174 struct objc_ivar {
2175 char *ivar_name;
2176 char *ivar_type;
2177 int ivar_offset;
2178 };
2179
2180 struct objc_ivar_list {
2181 int ivar_count;
2182 struct objc_ivar list[count];
2183 };
2184 */
2185llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002186 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002187 std::vector<llvm::Constant*> Ivars, Ivar(3);
2188
2189 // When emitting the root class GCC emits ivar entries for the
2190 // actual class structure. It is not clear if we need to follow this
2191 // behavior; for now lets try and get away with not doing it. If so,
2192 // the cleanest solution would be to make up an ObjCInterfaceDecl
2193 // for the class.
2194 if (ForClass)
2195 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002196
2197 ObjCInterfaceDecl *OID =
2198 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002199
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002200 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2201 GetNamedIvarList(OID, OIvars);
2202
2203 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2204 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002205 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2206 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002207 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002208 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002209 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002210 }
2211
2212 // Return null for empty list.
2213 if (Ivars.empty())
2214 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2215
2216 std::vector<llvm::Constant*> Values(2);
2217 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2218 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2219 Ivars.size());
2220 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2221 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2222
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002223 llvm::GlobalVariable *GV;
2224 if (ForClass)
2225 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002226 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2227 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002228 else
2229 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2230 + ID->getNameAsString(),
2231 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002232 4, true);
2233 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002234}
2235
2236/*
2237 struct objc_method {
2238 SEL method_name;
2239 char *method_types;
2240 void *method;
2241 };
2242
2243 struct objc_method_list {
2244 struct objc_method_list *obsolete;
2245 int count;
2246 struct objc_method methods_list[count];
2247 };
2248*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002249
2250/// GetMethodConstant - Return a struct objc_method constant for the
2251/// given method if it has been defined. The result is null if the
2252/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002253llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002254 // FIXME: Use DenseMap::lookup
2255 llvm::Function *Fn = MethodDefinitions[MD];
2256 if (!Fn)
2257 return 0;
2258
2259 std::vector<llvm::Constant*> Method(3);
2260 Method[0] =
2261 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2262 ObjCTypes.SelectorPtrTy);
2263 Method[1] = GetMethodVarType(MD);
2264 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2265 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2266}
2267
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002268llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2269 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002270 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002271 // Return null for empty list.
2272 if (Methods.empty())
2273 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2274
2275 std::vector<llvm::Constant*> Values(3);
2276 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2277 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2278 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2279 Methods.size());
2280 Values[2] = llvm::ConstantArray::get(AT, Methods);
2281 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2282
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002283 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002284 return llvm::ConstantExpr::getBitCast(GV,
2285 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002286}
2287
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002288llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002289 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002290 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002291 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002292
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002293 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002294 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002295 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002296 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002297 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002298 llvm::GlobalValue::InternalLinkage,
2299 Name,
2300 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002301 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002302
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002303 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002304}
2305
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002306llvm::GlobalVariable *
2307CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2308 llvm::Constant *Init,
2309 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002310 unsigned Align,
2311 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002312 const llvm::Type *Ty = Init->getType();
2313 llvm::GlobalVariable *GV =
2314 new llvm::GlobalVariable(Ty, false,
2315 llvm::GlobalValue::InternalLinkage,
2316 Init,
2317 Name,
2318 &CGM.getModule());
2319 if (Section)
2320 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002321 if (Align)
2322 GV->setAlignment(Align);
2323 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002324 UsedGlobals.push_back(GV);
2325 return GV;
2326}
2327
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002328llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002329 // Abuse this interface function as a place to finalize.
2330 FinishModule();
2331
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002332 return NULL;
2333}
2334
Chris Lattner74391b42009-03-22 21:03:39 +00002335llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002336 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002337}
2338
Chris Lattner74391b42009-03-22 21:03:39 +00002339llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002340 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002341}
2342
Chris Lattner74391b42009-03-22 21:03:39 +00002343llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002344 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002345}
2346
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002347/*
2348
2349Objective-C setjmp-longjmp (sjlj) Exception Handling
2350--
2351
2352The basic framework for a @try-catch-finally is as follows:
2353{
2354 objc_exception_data d;
2355 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002356 bool _call_try_exit = true;
2357
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002358 objc_exception_try_enter(&d);
2359 if (!setjmp(d.jmp_buf)) {
2360 ... try body ...
2361 } else {
2362 // exception path
2363 id _caught = objc_exception_extract(&d);
2364
2365 // enter new try scope for handlers
2366 if (!setjmp(d.jmp_buf)) {
2367 ... match exception and execute catch blocks ...
2368
2369 // fell off end, rethrow.
2370 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002371 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002372 } else {
2373 // exception in catch block
2374 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002375 _call_try_exit = false;
2376 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002377 }
2378 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002379 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002380
2381finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002382 if (_call_try_exit)
2383 objc_exception_try_exit(&d);
2384
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002385 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002386 ... dispatch to finally destination ...
2387
2388finally_rethrow:
2389 objc_exception_throw(_rethrow);
2390
2391finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002392}
2393
2394This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002395uses _rethrow to determine if objc_exception_try_exit should be called
2396and if the object should be rethrown. This breaks in the face of
2397throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002398
2399We specialize this framework for a few particular circumstances:
2400
2401 - If there are no catch blocks, then we avoid emitting the second
2402 exception handling context.
2403
2404 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2405 e)) we avoid emitting the code to rethrow an uncaught exception.
2406
2407 - FIXME: If there is no @finally block we can do a few more
2408 simplifications.
2409
2410Rethrows and Jumps-Through-Finally
2411--
2412
2413Support for implicit rethrows and jumping through the finally block is
2414handled by storing the current exception-handling context in
2415ObjCEHStack.
2416
Daniel Dunbar898d5082008-09-30 01:06:03 +00002417In order to implement proper @finally semantics, we support one basic
2418mechanism for jumping through the finally block to an arbitrary
2419destination. Constructs which generate exits from a @try or @catch
2420block use this mechanism to implement the proper semantics by chaining
2421jumps, as necessary.
2422
2423This mechanism works like the one used for indirect goto: we
2424arbitrarily assign an ID to each destination and store the ID for the
2425destination in a variable prior to entering the finally block. At the
2426end of the finally block we simply create a switch to the proper
2427destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002428
2429Code gen for @synchronized(expr) stmt;
2430Effectively generating code for:
2431objc_sync_enter(expr);
2432@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002433*/
2434
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002435void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2436 const Stmt &S) {
2437 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002438 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002439 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002440 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002441 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2442 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2443 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002444
2445 // For @synchronized, call objc_sync_enter(sync.expr). The
2446 // evaluation of the expression must occur before we enter the
2447 // @synchronized. We can safely avoid a temp here because jumps into
2448 // @synchronized are illegal & this will dominate uses.
2449 llvm::Value *SyncArg = 0;
2450 if (!isTry) {
2451 SyncArg =
2452 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2453 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002454 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002455 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002456
2457 // Push an EH context entry, used for handling rethrows and jumps
2458 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002459 CGF.PushCleanupBlock(FinallyBlock);
2460
Anders Carlsson273558f2009-02-07 21:37:21 +00002461 CGF.ObjCEHValueStack.push_back(0);
2462
Daniel Dunbar898d5082008-09-30 01:06:03 +00002463 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002464 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2465 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002466 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2467 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002468 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2469 "_call_try_exit");
2470 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2471
Anders Carlsson80f25672008-09-09 17:59:25 +00002472 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002473 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002474 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2475 "jmpbufarray");
2476 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002477 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002478 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002479
Daniel Dunbar55e87422008-11-11 02:29:29 +00002480 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2481 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002482 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002483 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002484
2485 // Emit the @try block.
2486 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002487 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2488 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002489 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002490
2491 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002492 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002493
2494 // Retrieve the exception object. We may emit multiple blocks but
2495 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002496 llvm::Value *Caught =
2497 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2498 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002499 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002500 if (!isTry)
2501 {
2502 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002503 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002504 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002505 }
2506 else if (const ObjCAtCatchStmt* CatchStmt =
2507 cast<ObjCAtTryStmt>(S).getCatchStmts())
2508 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002509 // Enter a new exception try block (in case a @catch block throws
2510 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002511 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002512
Chris Lattner34b02a12009-04-22 02:26:14 +00002513 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002514 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002515 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002516
Daniel Dunbar55e87422008-11-11 02:29:29 +00002517 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2518 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002519 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002520
2521 CGF.EmitBlock(CatchBlock);
2522
Daniel Dunbar55e40722008-09-27 07:03:52 +00002523 // Handle catch list. As a special case we check if everything is
2524 // matched and avoid generating code for falling off the end if
2525 // so.
2526 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002527 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002528 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002529
Steve Naroff7ba138a2009-03-03 19:52:17 +00002530 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002531 const PointerType *PT = 0;
2532
Anders Carlsson80f25672008-09-09 17:59:25 +00002533 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002534 if (!CatchParam) {
2535 AllMatched = true;
2536 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002537 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002538
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002539 // catch(id e) always matches.
2540 // FIXME: For the time being we also match id<X>; this should
2541 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002542 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002543 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002544 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002545 }
2546
Daniel Dunbar55e40722008-09-27 07:03:52 +00002547 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002548 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002549 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002550 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002551 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002552 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002553
Anders Carlssondde0a942008-09-11 09:15:33 +00002554 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002555 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002556 break;
2557 }
2558
Daniel Dunbar129271a2008-09-27 07:36:24 +00002559 assert(PT && "Unexpected non-pointer type in @catch");
2560 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002561 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002562 assert(ObjCType && "Catch parameter must have Objective-C type!");
2563
2564 // Check if the @catch block matches the exception object.
2565 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2566
Chris Lattner34b02a12009-04-22 02:26:14 +00002567 llvm::Value *Match =
2568 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2569 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002570
Daniel Dunbar55e87422008-11-11 02:29:29 +00002571 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002572
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002573 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002574 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002575
2576 // Emit the @catch block.
2577 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002578 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002579 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002580
2581 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002582 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002583 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002584 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002585
2586 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002587 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002588
2589 CGF.EmitBlock(NextCatchBlock);
2590 }
2591
Daniel Dunbar55e40722008-09-27 07:03:52 +00002592 if (!AllMatched) {
2593 // None of the handlers caught the exception, so store it to be
2594 // rethrown at the end of the @finally block.
2595 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002596 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002597 }
2598
2599 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002600 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002601 CGF.Builder.CreateStore(
2602 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2603 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002604 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002605 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002606 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002607 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002608 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002609 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002610 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002611 }
2612
Daniel Dunbar898d5082008-09-30 01:06:03 +00002613 // Pop the exception-handling stack entry. It is important to do
2614 // this now, because the code in the @finally block is not in this
2615 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002616 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2617
Anders Carlsson273558f2009-02-07 21:37:21 +00002618 CGF.ObjCEHValueStack.pop_back();
2619
Anders Carlsson80f25672008-09-09 17:59:25 +00002620 // Emit the @finally block.
2621 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002622 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2623
2624 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2625
2626 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002627 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002628
2629 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002630 if (isTry) {
2631 if (const ObjCAtFinallyStmt* FinallyStmt =
2632 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2633 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002634 } else {
2635 // Emit objc_sync_exit(expr); as finally's sole statement for
2636 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002637 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002638 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002639
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002640 // Emit the switch block
2641 if (Info.SwitchBlock)
2642 CGF.EmitBlock(Info.SwitchBlock);
2643 if (Info.EndBlock)
2644 CGF.EmitBlock(Info.EndBlock);
2645
Daniel Dunbar898d5082008-09-30 01:06:03 +00002646 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002647 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002648 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002649 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002650
2651 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002652}
2653
2654void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002655 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002656 llvm::Value *ExceptionAsObject;
2657
2658 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2659 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2660 ExceptionAsObject =
2661 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2662 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002663 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002664 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002665 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002666 }
2667
Chris Lattnerbbccd612009-04-22 02:38:11 +00002668 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002669 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002670
2671 // Clear the insertion point to indicate we are in unreachable code.
2672 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002673}
2674
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002675/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002676/// object: objc_read_weak (id *src)
2677///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002678llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002679 llvm::Value *AddrWeakObj)
2680{
Eli Friedman8339b352009-03-07 03:57:15 +00002681 const llvm::Type* DestTy =
2682 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002683 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002684 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002685 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002686 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002687 return read_weak;
2688}
2689
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002690/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2691/// objc_assign_weak (id src, id *dst)
2692///
2693void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2694 llvm::Value *src, llvm::Value *dst)
2695{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002696 const llvm::Type * SrcTy = src->getType();
2697 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002698 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002699 assert(Size <= 8 && "does not support size > 8");
2700 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2701 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002702 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2703 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002704 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2705 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002706 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002707 src, dst, "weakassign");
2708 return;
2709}
2710
Fariborz Jahanian58626502008-11-19 00:59:10 +00002711/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2712/// objc_assign_global (id src, id *dst)
2713///
2714void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2715 llvm::Value *src, llvm::Value *dst)
2716{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002717 const llvm::Type * SrcTy = src->getType();
2718 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002719 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002720 assert(Size <= 8 && "does not support size > 8");
2721 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2722 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002723 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2724 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002725 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2726 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002727 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002728 src, dst, "globalassign");
2729 return;
2730}
2731
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002732/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2733/// objc_assign_ivar (id src, id *dst)
2734///
2735void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2736 llvm::Value *src, llvm::Value *dst)
2737{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002738 const llvm::Type * SrcTy = src->getType();
2739 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002740 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002741 assert(Size <= 8 && "does not support size > 8");
2742 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2743 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002744 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2745 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002746 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2747 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002748 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002749 src, dst, "assignivar");
2750 return;
2751}
2752
Fariborz Jahanian58626502008-11-19 00:59:10 +00002753/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2754/// objc_assign_strongCast (id src, id *dst)
2755///
2756void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2757 llvm::Value *src, llvm::Value *dst)
2758{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002759 const llvm::Type * SrcTy = src->getType();
2760 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002761 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002762 assert(Size <= 8 && "does not support size > 8");
2763 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2764 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002765 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2766 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002767 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2768 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002769 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002770 src, dst, "weakassign");
2771 return;
2772}
2773
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002774/// EmitObjCValueForIvar - Code Gen for ivar reference.
2775///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002776LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2777 QualType ObjectTy,
2778 llvm::Value *BaseValue,
2779 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002780 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002781 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002782 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2783 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002784}
2785
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002786llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002787 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002788 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002789 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002790 return llvm::ConstantInt::get(
2791 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2792 Offset);
2793}
2794
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002795/* *** Private Interface *** */
2796
2797/// EmitImageInfo - Emit the image info marker used to encode some module
2798/// level information.
2799///
2800/// See: <rdr://4810609&4810587&4810587>
2801/// struct IMAGE_INFO {
2802/// unsigned version;
2803/// unsigned flags;
2804/// };
2805enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002806 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2807 // this implies.
2808 eImageInfo_GarbageCollected = (1 << 1),
2809 eImageInfo_GCOnly = (1 << 2),
2810 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2811
2812 // A flag indicating that the module has no instances of an
2813 // @synthesize of a superclass variable. <rdar://problem/6803242>
2814 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002815};
2816
2817void CGObjCMac::EmitImageInfo() {
2818 unsigned version = 0; // Version is unused?
2819 unsigned flags = 0;
2820
2821 // FIXME: Fix and continue?
2822 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2823 flags |= eImageInfo_GarbageCollected;
2824 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2825 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002826
2827 // We never allow @synthesize of a superclass property.
2828 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002829
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002830 // Emitted as int[2];
2831 llvm::Constant *values[2] = {
2832 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2833 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2834 };
2835 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002836
2837 const char *Section;
2838 if (ObjCABI == 1)
2839 Section = "__OBJC, __image_info,regular";
2840 else
2841 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002842 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002843 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2844 llvm::ConstantArray::get(AT, values, 2),
2845 Section,
2846 0,
2847 true);
2848 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002849}
2850
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002851
2852// struct objc_module {
2853// unsigned long version;
2854// unsigned long size;
2855// const char *name;
2856// Symtab symtab;
2857// };
2858
2859// FIXME: Get from somewhere
2860static const int ModuleVersion = 7;
2861
2862void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002863 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002864
2865 std::vector<llvm::Constant*> Values(4);
2866 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2867 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002868 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002869 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002870 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002871 CreateMetadataVar("\01L_OBJC_MODULES",
2872 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2873 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002874 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002875}
2876
2877llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002878 unsigned NumClasses = DefinedClasses.size();
2879 unsigned NumCategories = DefinedCategories.size();
2880
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002881 // Return null if no symbols were defined.
2882 if (!NumClasses && !NumCategories)
2883 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2884
2885 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002886 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2887 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2888 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2889 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2890
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002891 // The runtime expects exactly the list of defined classes followed
2892 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002893 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002894 for (unsigned i=0; i<NumClasses; i++)
2895 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2896 ObjCTypes.Int8PtrTy);
2897 for (unsigned i=0; i<NumCategories; i++)
2898 Symbols[NumClasses + i] =
2899 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2900 ObjCTypes.Int8PtrTy);
2901
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002902 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002903 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002904 NumClasses + NumCategories),
2905 Symbols);
2906
2907 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2908
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002909 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002910 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2911 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002912 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002913 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2914}
2915
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002916llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002917 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002918 LazySymbols.insert(ID->getIdentifier());
2919
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002920 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2921
2922 if (!Entry) {
2923 llvm::Constant *Casted =
2924 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2925 ObjCTypes.ClassPtrTy);
2926 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002927 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2928 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002929 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002930 }
2931
2932 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002933}
2934
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002935llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002936 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2937
2938 if (!Entry) {
2939 llvm::Constant *Casted =
2940 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2941 ObjCTypes.SelectorPtrTy);
2942 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002943 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2944 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002945 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002946 }
2947
2948 return Builder.CreateLoad(Entry, false, "tmp");
2949}
2950
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002951llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002952 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002953
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002954 if (!Entry)
2955 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2956 llvm::ConstantArray::get(Ident->getName()),
2957 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002958 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002959
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002960 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002961}
2962
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002963/// GetIvarLayoutName - Returns a unique constant for the given
2964/// ivar layout bitmap.
2965llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2966 const ObjCCommonTypesHelper &ObjCTypes) {
2967 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2968}
2969
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002970static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2971 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002972 if (FQT.isObjCGCStrong())
2973 return QualType::Strong;
2974
2975 if (FQT.isObjCGCWeak())
2976 return QualType::Weak;
2977
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002978 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002979 return QualType::Strong;
2980
2981 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002982 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002983
2984 return QualType::GCNone;
2985}
2986
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002987void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2988 unsigned int BytePos,
2989 bool ForStrongLayout,
2990 bool &HasUnion) {
2991 const RecordDecl *RD = RT->getDecl();
2992 // FIXME - Use iterator.
2993 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2994 RD->field_end(CGM.getContext()));
2995 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2996 const llvm::StructLayout *RecLayout =
2997 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2998
2999 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
3000 ForStrongLayout, HasUnion);
3001}
3002
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003003void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003004 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003005 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00003006 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003007 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003008 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003009 bool IsUnion = (RD && RD->isUnion());
3010 uint64_t MaxUnionIvarSize = 0;
3011 uint64_t MaxSkippedUnionIvarSize = 0;
3012 FieldDecl *MaxField = 0;
3013 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003014 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003015 uint64_t MaxFieldOffset = 0;
3016 uint64_t MaxSkippedFieldOffset = 0;
3017 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003018
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003019 if (RecFields.empty())
3020 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003021 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3022 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3023
Chris Lattnerf1690852009-03-31 08:48:01 +00003024 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003025 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003026 uint64_t FieldOffset;
3027 if (RD)
3028 FieldOffset =
3029 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3030 else
3031 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003032
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003033 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003034 if (!Field->getIdentifier() || Field->isBitField()) {
3035 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003036 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003037 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003038 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003039
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003040 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003041 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003042 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003043 if (FQT->isUnionType())
3044 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003045
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003046 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003047 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003048 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003049 continue;
3050 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003051
3052 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003053 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 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003056 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003057 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003058 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3059 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003060 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003061 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003062 FQT = CArray->getElementType();
3063 }
3064
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003065 assert(!FQT->isUnionType() &&
3066 "layout for array of unions not supported");
3067 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003068 int OldIndex = IvarsInfo.size() - 1;
3069 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003070
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003071 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003072 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003073 ForStrongLayout, HasUnion);
3074
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003075 // Replicate layout information for each array element. Note that
3076 // one element is already done.
3077 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003078 for (int FirstIndex = IvarsInfo.size() - 1,
3079 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003080 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003081 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3082 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3083 IvarsInfo[i].ivar_size));
3084 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3085 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3086 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003087 }
3088 continue;
3089 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003090 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003091 // At this point, we are done with Record/Union and array there of.
3092 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003093 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003094
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003095 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003096 if ((ForStrongLayout && GCAttr == QualType::Strong)
3097 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003098 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003099 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003100 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003101 MaxUnionIvarSize = UnionIvarSize;
3102 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003103 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003104 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003105 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003106 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003107 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003108 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003109 } else if ((ForStrongLayout &&
3110 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3111 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3112 if (IsUnion) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00003113 // FIXME: Why the asymmetry? We divide by word size in bits on other
3114 // side.
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003115 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003116 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003117 MaxSkippedUnionIvarSize = UnionIvarSize;
3118 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003119 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003120 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003121 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003122 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003123 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003124 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003125 }
3126 }
3127 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003128
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003129 if (LastFieldBitfield) {
3130 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003131 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3132 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003133 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003134 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003135 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003136 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3137 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003138 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003139 }
3140
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003141 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003142 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003143 MaxUnionIvarSize));
3144 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003145 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003146 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003147}
3148
3149/// BuildIvarLayout - Builds ivar layout bitmap for the class
3150/// implementation for the __strong or __weak case.
3151/// The layout map displays which words in ivar list must be skipped
3152/// and which must be scanned by GC (see below). String is built of bytes.
3153/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3154/// of words to skip and right nibble is count of words to scan. So, each
3155/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3156/// represented by a 0x00 byte which also ends the string.
3157/// 1. when ForStrongLayout is true, following ivars are scanned:
3158/// - id, Class
3159/// - object *
3160/// - __strong anything
3161///
3162/// 2. When ForStrongLayout is false, following ivars are scanned:
3163/// - __weak anything
3164///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003165llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003166 const ObjCImplementationDecl *OMD,
3167 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003168 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003169
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003170 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003171 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3172 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3173 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003174
Chris Lattnerf1690852009-03-31 08:48:01 +00003175 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003176 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003177 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003178
Daniel Dunbar37153282009-05-04 04:10:48 +00003179 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003180 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3181 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3182 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3183 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3184
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003185 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003186 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003187
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003188 SkipIvars.clear();
3189 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003190
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003191 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003192 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003193 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003194
3195 // Sort on byte position in case we encounterred a union nested in
3196 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003197 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003198 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003199 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003200 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003201
3202 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003203 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003204 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003205 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003206 if (IvarsInfo[0].ivar_bytepos == 0) {
3207 WordsToSkip = 0;
3208 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003209 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003210 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3211 WordsToScan = IvarsInfo[0].ivar_size;
3212 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003213 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003214 unsigned int TailPrevGCObjC =
3215 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003216 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003217 // consecutive 'scanned' object pointers.
3218 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003219 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003220 // Skip over 'gc'able object pointer which lay over each other.
3221 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3222 continue;
3223 // Must skip over 1 or more words. We save current skip/scan values
3224 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003225 SKIP_SCAN SkScan;
3226 SkScan.skip = WordsToSkip;
3227 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003228 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003229
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003230 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003231 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3232 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003233 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003234 WordsToSkip = 0;
3235 WordsToScan = IvarsInfo[i].ivar_size;
3236 }
3237 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003238 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003239 SKIP_SCAN SkScan;
3240 SkScan.skip = WordsToSkip;
3241 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003242 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003243 }
3244
3245 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003246 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003247 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003248 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003249 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3250 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003251 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003252 IvarsInfo[LastIndex].ivar_bytepos +
3253 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003254 BytesSkipped = (LastByteSkipped > LastByteScanned);
3255 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003256 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003257 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003258 SKIP_SCAN SkScan;
3259 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3260 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003261 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003262 }
3263 }
3264 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3265 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003266 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003267 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003268 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3269 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3270 // 0xM0 followed by 0x0N detected.
3271 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3272 for (int j = i+1; j < SkipScan; j++)
3273 SkipScanIvars[j] = SkipScanIvars[j+1];
3274 --SkipScan;
3275 }
3276 }
3277
3278 // Generate the string.
3279 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003280 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003281 unsigned char byte;
3282 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3283 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3284 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3285 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3286
3287 if (skip_small > 0 || skip_big > 0)
3288 BytesSkipped = true;
3289 // first skip big.
3290 for (unsigned int ix = 0; ix < skip_big; ix++)
3291 BitMap += (unsigned char)(0xf0);
3292
3293 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003294 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003295 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003296 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003297 byte |= 0xf;
3298 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003299 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003300 byte |= scan_small;
3301 scan_small = 0;
3302 }
3303 BitMap += byte;
3304 }
3305 // next scan big
3306 for (unsigned int ix = 0; ix < scan_big; ix++)
3307 BitMap += (unsigned char)(0x0f);
3308 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003309 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003310 byte = scan_small;
3311 BitMap += byte;
3312 }
3313 }
3314 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003315 unsigned char zero = 0;
3316 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003317
3318 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3319 printf("\n%s ivar layout for class '%s': ",
3320 ForStrongLayout ? "strong" : "weak",
3321 OMD->getClassInterface()->getNameAsCString());
3322 const unsigned char *s = (unsigned char*)BitMap.c_str();
3323 for (unsigned i = 0; i < BitMap.size(); i++)
3324 if (!(s[i] & 0xf0))
3325 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3326 else
3327 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3328 printf("\n");
3329 }
3330
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003331 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3332 // final layout.
3333 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003334 return llvm::Constant::getNullValue(PtrTy);
3335 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3336 llvm::ConstantArray::get(BitMap.c_str()),
3337 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003338 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003339 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003340}
3341
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003342llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003343 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3344
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003345 // FIXME: Avoid std::string copying.
3346 if (!Entry)
3347 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3348 llvm::ConstantArray::get(Sel.getAsString()),
3349 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003350 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003351
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003352 return getConstantGEP(Entry, 0, 0);
3353}
3354
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003355// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003356llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003357 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3358}
3359
3360// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003361llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003362 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3363}
3364
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003365llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003366 std::string TypeStr;
3367 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3368
3369 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003370
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003371 if (!Entry)
3372 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3373 llvm::ConstantArray::get(TypeStr),
3374 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003375 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003376
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003377 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003378}
3379
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003380llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003381 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003382 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3383 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003384
3385 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3386
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003387 if (!Entry)
3388 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3389 llvm::ConstantArray::get(TypeStr),
3390 "__TEXT,__cstring,cstring_literals",
3391 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003392
3393 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003394}
3395
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003396// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003397llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003398 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3399
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003400 if (!Entry)
3401 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3402 llvm::ConstantArray::get(Ident->getName()),
3403 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003404 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003405
3406 return getConstantGEP(Entry, 0, 0);
3407}
3408
3409// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003410// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003411llvm::Constant *
3412 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3413 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003414 std::string TypeStr;
3415 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003416 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3417}
3418
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003419void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3420 const ObjCContainerDecl *CD,
3421 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003422 NameOut = '\01';
3423 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003424 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003425 assert (CD && "Missing container decl in GetNameForMethod");
3426 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003427 if (const ObjCCategoryImplDecl *CID =
3428 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3429 NameOut += '(';
3430 NameOut += CID->getNameAsString();
3431 NameOut+= ')';
3432 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003433 NameOut += ' ';
3434 NameOut += D->getSelector().getAsString();
3435 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003436}
3437
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003438void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003439 EmitModuleInfo();
3440
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003441 // Emit the dummy bodies for any protocols which were referenced but
3442 // never defined.
3443 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3444 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3445 if (i->second->hasInitializer())
3446 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003447
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003448 std::vector<llvm::Constant*> Values(5);
3449 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3450 Values[1] = GetClassName(i->first);
3451 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3452 Values[3] = Values[4] =
3453 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3454 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3455 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3456 Values));
3457 }
3458
3459 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003460 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003461 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003462 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003463 }
3464
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003465 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003466 llvm::GlobalValue *GV =
3467 new llvm::GlobalVariable(AT, false,
3468 llvm::GlobalValue::AppendingLinkage,
3469 llvm::ConstantArray::get(AT, Used),
3470 "llvm.used",
3471 &CGM.getModule());
3472
3473 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003474
3475 // Add assembler directives to add lazy undefined symbol references
3476 // for classes which are referenced but not defined. This is
3477 // important for correct linker interaction.
3478
3479 // FIXME: Uh, this isn't particularly portable.
3480 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003481
3482 if (!CGM.getModule().getModuleInlineAsm().empty())
3483 s << "\n";
3484
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003485 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3486 e = LazySymbols.end(); i != e; ++i) {
3487 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3488 }
3489 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3490 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003491 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003492 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3493 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003494
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003495 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003496}
3497
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003498CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003499 : CGObjCCommonMac(cgm),
3500 ObjCTypes(cgm)
3501{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003502 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003503 ObjCABI = 2;
3504}
3505
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003506/* *** */
3507
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003508ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3509: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003510{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003511 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3512 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003513
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003514 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003515 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003516 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003517 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003518 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3519
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003520 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003521 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003522 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003523
Mike Stumpf5408fe2009-05-16 07:57:57 +00003524 // FIXME: It would be nice to unify this with the opaque type, so that the IR
3525 // comes out a bit cleaner.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003526 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3527 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003528
3529 // I'm not sure I like this. The implicit coordination is a bit
3530 // gross. We should solve this in a reasonable fashion because this
3531 // is a pretty common task (match some runtime data structure with
3532 // an LLVM data structure).
3533
3534 // FIXME: This is leaked.
3535 // FIXME: Merge with rewriter code?
3536
3537 // struct _objc_super {
3538 // id self;
3539 // Class cls;
3540 // }
3541 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3542 SourceLocation(),
3543 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003544 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3545 Ctx.getObjCIdType(), 0, false));
3546 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3547 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003548 RD->completeDefinition(Ctx);
3549
3550 SuperCTy = Ctx.getTagDeclType(RD);
3551 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3552
3553 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003554 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3555
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003556 // struct _prop_t {
3557 // char *name;
3558 // char *attributes;
3559 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003560 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003561 CGM.getModule().addTypeName("struct._prop_t",
3562 PropertyTy);
3563
3564 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003565 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003566 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003567 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003568 // }
3569 PropertyListTy = llvm::StructType::get(IntTy,
3570 IntTy,
3571 llvm::ArrayType::get(PropertyTy, 0),
3572 NULL);
3573 CGM.getModule().addTypeName("struct._prop_list_t",
3574 PropertyListTy);
3575 // struct _prop_list_t *
3576 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3577
3578 // struct _objc_method {
3579 // SEL _cmd;
3580 // char *method_type;
3581 // char *_imp;
3582 // }
3583 MethodTy = llvm::StructType::get(SelectorPtrTy,
3584 Int8PtrTy,
3585 Int8PtrTy,
3586 NULL);
3587 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003588
3589 // struct _objc_cache *
3590 CacheTy = llvm::OpaqueType::get();
3591 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3592 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003593}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003594
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003595ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3596 : ObjCCommonTypesHelper(cgm)
3597{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003598 // struct _objc_method_description {
3599 // SEL name;
3600 // char *types;
3601 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003602 MethodDescriptionTy =
3603 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003604 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003605 NULL);
3606 CGM.getModule().addTypeName("struct._objc_method_description",
3607 MethodDescriptionTy);
3608
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003609 // struct _objc_method_description_list {
3610 // int count;
3611 // struct _objc_method_description[1];
3612 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003613 MethodDescriptionListTy =
3614 llvm::StructType::get(IntTy,
3615 llvm::ArrayType::get(MethodDescriptionTy, 0),
3616 NULL);
3617 CGM.getModule().addTypeName("struct._objc_method_description_list",
3618 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003619
3620 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003621 MethodDescriptionListPtrTy =
3622 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3623
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003624 // Protocol description structures
3625
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003626 // struct _objc_protocol_extension {
3627 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3628 // struct _objc_method_description_list *optional_instance_methods;
3629 // struct _objc_method_description_list *optional_class_methods;
3630 // struct _objc_property_list *instance_properties;
3631 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003632 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003633 llvm::StructType::get(IntTy,
3634 MethodDescriptionListPtrTy,
3635 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003636 PropertyListPtrTy,
3637 NULL);
3638 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3639 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003640
3641 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003642 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3643
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003644 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003645
3646 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3647 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3648
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003649 const llvm::Type *T =
3650 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3651 LongTy,
3652 llvm::ArrayType::get(ProtocolTyHolder, 0),
3653 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003654 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3655
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003656 // struct _objc_protocol {
3657 // struct _objc_protocol_extension *isa;
3658 // char *protocol_name;
3659 // struct _objc_protocol **_objc_protocol_list;
3660 // struct _objc_method_description_list *instance_methods;
3661 // struct _objc_method_description_list *class_methods;
3662 // }
3663 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003664 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003665 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3666 MethodDescriptionListPtrTy,
3667 MethodDescriptionListPtrTy,
3668 NULL);
3669 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3670
3671 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3672 CGM.getModule().addTypeName("struct._objc_protocol_list",
3673 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003674 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003675 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3676
3677 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003678 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003679 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003680
3681 // Class description structures
3682
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003683 // struct _objc_ivar {
3684 // char *ivar_name;
3685 // char *ivar_type;
3686 // int ivar_offset;
3687 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003688 IvarTy = llvm::StructType::get(Int8PtrTy,
3689 Int8PtrTy,
3690 IntTy,
3691 NULL);
3692 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3693
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003694 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003695 IvarListTy = llvm::OpaqueType::get();
3696 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3697 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3698
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003699 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003700 MethodListTy = llvm::OpaqueType::get();
3701 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3702 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3703
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003704 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003705 ClassExtensionTy =
3706 llvm::StructType::get(IntTy,
3707 Int8PtrTy,
3708 PropertyListPtrTy,
3709 NULL);
3710 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3711 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3712
3713 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3714
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003715 // struct _objc_class {
3716 // Class isa;
3717 // Class super_class;
3718 // char *name;
3719 // long version;
3720 // long info;
3721 // long instance_size;
3722 // struct _objc_ivar_list *ivars;
3723 // struct _objc_method_list *methods;
3724 // struct _objc_cache *cache;
3725 // struct _objc_protocol_list *protocols;
3726 // char *ivar_layout;
3727 // struct _objc_class_ext *ext;
3728 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003729 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3730 llvm::PointerType::getUnqual(ClassTyHolder),
3731 Int8PtrTy,
3732 LongTy,
3733 LongTy,
3734 LongTy,
3735 IvarListPtrTy,
3736 MethodListPtrTy,
3737 CachePtrTy,
3738 ProtocolListPtrTy,
3739 Int8PtrTy,
3740 ClassExtensionPtrTy,
3741 NULL);
3742 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3743
3744 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3745 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3746 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3747
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003748 // struct _objc_category {
3749 // char *category_name;
3750 // char *class_name;
3751 // struct _objc_method_list *instance_method;
3752 // struct _objc_method_list *class_method;
3753 // uint32_t size; // sizeof(struct _objc_category)
3754 // struct _objc_property_list *instance_properties;// category's @property
3755 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003756 CategoryTy = llvm::StructType::get(Int8PtrTy,
3757 Int8PtrTy,
3758 MethodListPtrTy,
3759 MethodListPtrTy,
3760 ProtocolListPtrTy,
3761 IntTy,
3762 PropertyListPtrTy,
3763 NULL);
3764 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3765
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003766 // Global metadata structures
3767
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003768 // struct _objc_symtab {
3769 // long sel_ref_cnt;
3770 // SEL *refs;
3771 // short cls_def_cnt;
3772 // short cat_def_cnt;
3773 // char *defs[cls_def_cnt + cat_def_cnt];
3774 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003775 SymtabTy = llvm::StructType::get(LongTy,
3776 SelectorPtrTy,
3777 ShortTy,
3778 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003779 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003780 NULL);
3781 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3782 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3783
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003784 // struct _objc_module {
3785 // long version;
3786 // long size; // sizeof(struct _objc_module)
3787 // char *name;
3788 // struct _objc_symtab* symtab;
3789 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003790 ModuleTy =
3791 llvm::StructType::get(LongTy,
3792 LongTy,
3793 Int8PtrTy,
3794 SymtabPtrTy,
3795 NULL);
3796 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003797
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003798
Mike Stumpf5408fe2009-05-16 07:57:57 +00003799 // FIXME: This is the size of the setjmp buffer and should be target
3800 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson124526b2008-09-09 10:10:21 +00003801 uint64_t SetJmpBufferSize = 18;
3802
3803 // Exceptions
3804 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003805 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003806
3807 ExceptionDataTy =
3808 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3809 SetJmpBufferSize),
3810 StackPtrTy, NULL);
3811 CGM.getModule().addTypeName("struct._objc_exception_data",
3812 ExceptionDataTy);
3813
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003814}
3815
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003816ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003817: ObjCCommonTypesHelper(cgm)
3818{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003819 // struct _method_list_t {
3820 // uint32_t entsize; // sizeof(struct _objc_method)
3821 // uint32_t method_count;
3822 // struct _objc_method method_list[method_count];
3823 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003824 MethodListnfABITy = llvm::StructType::get(IntTy,
3825 IntTy,
3826 llvm::ArrayType::get(MethodTy, 0),
3827 NULL);
3828 CGM.getModule().addTypeName("struct.__method_list_t",
3829 MethodListnfABITy);
3830 // struct method_list_t *
3831 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003832
3833 // struct _protocol_t {
3834 // id isa; // NULL
3835 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003836 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003837 // const struct method_list_t * const instance_methods;
3838 // const struct method_list_t * const class_methods;
3839 // const struct method_list_t *optionalInstanceMethods;
3840 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003841 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003842 // const uint32_t size; // sizeof(struct _protocol_t)
3843 // const uint32_t flags; // = 0
3844 // }
3845
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003846 // Holder for struct _protocol_list_t *
3847 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3848
3849 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3850 Int8PtrTy,
3851 llvm::PointerType::getUnqual(
3852 ProtocolListTyHolder),
3853 MethodListnfABIPtrTy,
3854 MethodListnfABIPtrTy,
3855 MethodListnfABIPtrTy,
3856 MethodListnfABIPtrTy,
3857 PropertyListPtrTy,
3858 IntTy,
3859 IntTy,
3860 NULL);
3861 CGM.getModule().addTypeName("struct._protocol_t",
3862 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003863
3864 // struct _protocol_t*
3865 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003866
Fariborz Jahanianda320092009-01-29 19:24:30 +00003867 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003868 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003869 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003870 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003871 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3872 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003873 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003874 NULL);
3875 CGM.getModule().addTypeName("struct._objc_protocol_list",
3876 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003877 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3878 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003879
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003880 // struct _objc_protocol_list*
3881 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003882
3883 // struct _ivar_t {
3884 // unsigned long int *offset; // pointer to ivar offset location
3885 // char *name;
3886 // char *type;
3887 // uint32_t alignment;
3888 // uint32_t size;
3889 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003890 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3891 Int8PtrTy,
3892 Int8PtrTy,
3893 IntTy,
3894 IntTy,
3895 NULL);
3896 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3897
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003898 // struct _ivar_list_t {
3899 // uint32 entsize; // sizeof(struct _ivar_t)
3900 // uint32 count;
3901 // struct _iver_t list[count];
3902 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003903 IvarListnfABITy = llvm::StructType::get(IntTy,
3904 IntTy,
3905 llvm::ArrayType::get(
3906 IvarnfABITy, 0),
3907 NULL);
3908 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3909
3910 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003911
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003912 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003913 // uint32_t const flags;
3914 // uint32_t const instanceStart;
3915 // uint32_t const instanceSize;
3916 // uint32_t const reserved; // only when building for 64bit targets
3917 // const uint8_t * const ivarLayout;
3918 // const char *const name;
3919 // const struct _method_list_t * const baseMethods;
3920 // const struct _objc_protocol_list *const baseProtocols;
3921 // const struct _ivar_list_t *const ivars;
3922 // const uint8_t * const weakIvarLayout;
3923 // const struct _prop_list_t * const properties;
3924 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003925
3926 // FIXME. Add 'reserved' field in 64bit abi mode!
3927 ClassRonfABITy = llvm::StructType::get(IntTy,
3928 IntTy,
3929 IntTy,
3930 Int8PtrTy,
3931 Int8PtrTy,
3932 MethodListnfABIPtrTy,
3933 ProtocolListnfABIPtrTy,
3934 IvarListnfABIPtrTy,
3935 Int8PtrTy,
3936 PropertyListPtrTy,
3937 NULL);
3938 CGM.getModule().addTypeName("struct._class_ro_t",
3939 ClassRonfABITy);
3940
3941 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3942 std::vector<const llvm::Type*> Params;
3943 Params.push_back(ObjectPtrTy);
3944 Params.push_back(SelectorPtrTy);
3945 ImpnfABITy = llvm::PointerType::getUnqual(
3946 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3947
3948 // struct _class_t {
3949 // struct _class_t *isa;
3950 // struct _class_t * const superclass;
3951 // void *cache;
3952 // IMP *vtable;
3953 // struct class_ro_t *ro;
3954 // }
3955
3956 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3957 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3958 llvm::PointerType::getUnqual(ClassTyHolder),
3959 CachePtrTy,
3960 llvm::PointerType::getUnqual(ImpnfABITy),
3961 llvm::PointerType::getUnqual(
3962 ClassRonfABITy),
3963 NULL);
3964 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3965
3966 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3967 ClassnfABITy);
3968
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003969 // LLVM for struct _class_t *
3970 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3971
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003972 // struct _category_t {
3973 // const char * const name;
3974 // struct _class_t *const cls;
3975 // const struct _method_list_t * const instance_methods;
3976 // const struct _method_list_t * const class_methods;
3977 // const struct _protocol_list_t * const protocols;
3978 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003979 // }
3980 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003981 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003982 MethodListnfABIPtrTy,
3983 MethodListnfABIPtrTy,
3984 ProtocolListnfABIPtrTy,
3985 PropertyListPtrTy,
3986 NULL);
3987 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003988
3989 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003990 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3991 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003992
3993 // MessageRefTy - LLVM for:
3994 // struct _message_ref_t {
3995 // IMP messenger;
3996 // SEL name;
3997 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003998
3999 // First the clang type for struct _message_ref_t
4000 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
4001 SourceLocation(),
4002 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00004003 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
4004 Ctx.VoidPtrTy, 0, false));
4005 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
4006 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004007 RD->completeDefinition(Ctx);
4008
4009 MessageRefCTy = Ctx.getTagDeclType(RD);
4010 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4011 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004012
4013 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4014 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4015
4016 // SuperMessageRefTy - LLVM for:
4017 // struct _super_message_ref_t {
4018 // SUPER_IMP messenger;
4019 // SEL name;
4020 // };
4021 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4022 SelectorPtrTy,
4023 NULL);
4024 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4025
4026 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4027 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4028
Daniel Dunbare588b992009-03-01 04:46:24 +00004029
4030 // struct objc_typeinfo {
4031 // const void** vtable; // objc_ehtype_vtable + 2
4032 // const char* name; // c++ typeinfo string
4033 // Class cls;
4034 // };
4035 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4036 Int8PtrTy,
4037 ClassnfABIPtrTy,
4038 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004039 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004040 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004041}
4042
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004043llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4044 FinishNonFragileABIModule();
4045
4046 return NULL;
4047}
4048
Daniel Dunbar463b8762009-05-15 21:48:48 +00004049void CGObjCNonFragileABIMac::AddModuleClassList(const
4050 std::vector<llvm::GlobalValue*>
4051 &Container,
4052 const char *SymbolName,
4053 const char *SectionName) {
4054 unsigned NumClasses = Container.size();
4055
4056 if (!NumClasses)
4057 return;
4058
4059 std::vector<llvm::Constant*> Symbols(NumClasses);
4060 for (unsigned i=0; i<NumClasses; i++)
4061 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4062 ObjCTypes.Int8PtrTy);
4063 llvm::Constant* Init =
4064 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4065 NumClasses),
4066 Symbols);
4067
4068 llvm::GlobalVariable *GV =
4069 new llvm::GlobalVariable(Init->getType(), false,
4070 llvm::GlobalValue::InternalLinkage,
4071 Init,
4072 SymbolName,
4073 &CGM.getModule());
4074 GV->setAlignment(8);
4075 GV->setSection(SectionName);
4076 UsedGlobals.push_back(GV);
4077}
4078
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004079void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4080 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004081
Daniel Dunbar463b8762009-05-15 21:48:48 +00004082 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004083 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004084 AddModuleClassList(DefinedClasses,
4085 "\01L_OBJC_LABEL_CLASS_$",
4086 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004087 AddModuleClassList(DefinedNonLazyClasses,
4088 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4089 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004090
4091 // Build list of all implemented category addresses in array
4092 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004093 AddModuleClassList(DefinedCategories,
4094 "\01L_OBJC_LABEL_CATEGORY_$",
4095 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004096 AddModuleClassList(DefinedNonLazyCategories,
4097 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4098 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004099
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004100 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4101 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4102 std::vector<llvm::Constant*> Values(2);
4103 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004104 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004105 // FIXME: Fix and continue?
4106 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4107 flags |= eImageInfo_GarbageCollected;
4108 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4109 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004110 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004111 llvm::Constant* Init = llvm::ConstantArray::get(
4112 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4113 Values);
4114 llvm::GlobalVariable *IMGV =
4115 new llvm::GlobalVariable(Init->getType(), false,
4116 llvm::GlobalValue::InternalLinkage,
4117 Init,
4118 "\01L_OBJC_IMAGE_INFO",
4119 &CGM.getModule());
4120 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004121 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004122 UsedGlobals.push_back(IMGV);
4123
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004124 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004125
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004126 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4127 e = UsedGlobals.end(); i != e; ++i) {
4128 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4129 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004130
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004131 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4132 llvm::GlobalValue *GV =
4133 new llvm::GlobalVariable(AT, false,
4134 llvm::GlobalValue::AppendingLinkage,
4135 llvm::ConstantArray::get(AT, Used),
4136 "llvm.used",
4137 &CGM.getModule());
4138
4139 GV->setSection("llvm.metadata");
4140
4141}
4142
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004143/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004144/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004145/// except for the 19 selectors in the list, we generate 32bit-style
4146/// message dispatch call for all the rest.
4147///
4148bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004149 if (NonLegacyDispatchMethods.empty()) {
4150 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4151 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4152 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4153 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4154 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4155 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4156 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4157 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4158 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4159 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4160
4161 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4162 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4163 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4164 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4165 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4166 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4167 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4168 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004169 // "countByEnumeratingWithState:objects:count"
4170 IdentifierInfo *KeyIdents[] = {
4171 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4172 &CGM.getContext().Idents.get("objects"),
4173 &CGM.getContext().Idents.get("count")
4174 };
4175 NonLegacyDispatchMethods.insert(
4176 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004177 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004178 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004179}
4180
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004181// Metadata flags
4182enum MetaDataDlags {
4183 CLS = 0x0,
4184 CLS_META = 0x1,
4185 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004186 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004187 CLS_EXCEPTION = 0x20
4188};
4189/// BuildClassRoTInitializer - generate meta-data for:
4190/// struct _class_ro_t {
4191/// uint32_t const flags;
4192/// uint32_t const instanceStart;
4193/// uint32_t const instanceSize;
4194/// uint32_t const reserved; // only when building for 64bit targets
4195/// const uint8_t * const ivarLayout;
4196/// const char *const name;
4197/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004198/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004199/// const struct _ivar_list_t *const ivars;
4200/// const uint8_t * const weakIvarLayout;
4201/// const struct _prop_list_t * const properties;
4202/// }
4203///
4204llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4205 unsigned flags,
4206 unsigned InstanceStart,
4207 unsigned InstanceSize,
4208 const ObjCImplementationDecl *ID) {
4209 std::string ClassName = ID->getNameAsString();
4210 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4211 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4212 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4213 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4214 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004215 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4216 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004217 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004218 // const struct _method_list_t * const baseMethods;
4219 std::vector<llvm::Constant*> Methods;
4220 std::string MethodListName("\01l_OBJC_$_");
4221 if (flags & CLS_META) {
4222 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004223 for (ObjCImplementationDecl::classmeth_iterator
4224 i = ID->classmeth_begin(CGM.getContext()),
4225 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004226 // Class methods should always be defined.
4227 Methods.push_back(GetMethodConstant(*i));
4228 }
4229 } else {
4230 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004231 for (ObjCImplementationDecl::instmeth_iterator
4232 i = ID->instmeth_begin(CGM.getContext()),
4233 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004234 // Instance methods should always be defined.
4235 Methods.push_back(GetMethodConstant(*i));
4236 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004237 for (ObjCImplementationDecl::propimpl_iterator
4238 i = ID->propimpl_begin(CGM.getContext()),
4239 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004240 ObjCPropertyImplDecl *PID = *i;
4241
4242 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4243 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4244
4245 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4246 if (llvm::Constant *C = GetMethodConstant(MD))
4247 Methods.push_back(C);
4248 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4249 if (llvm::Constant *C = GetMethodConstant(MD))
4250 Methods.push_back(C);
4251 }
4252 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004253 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004254 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004255 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004256
4257 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4258 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4259 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4260 + OID->getNameAsString(),
4261 OID->protocol_begin(),
4262 OID->protocol_end());
4263
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004264 if (flags & CLS_META)
4265 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4266 else
4267 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004268 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4269 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004270 if (flags & CLS_META)
4271 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4272 else
4273 Values[ 9] =
4274 EmitPropertyList(
4275 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4276 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004277 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4278 Values);
4279 llvm::GlobalVariable *CLASS_RO_GV =
4280 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4281 llvm::GlobalValue::InternalLinkage,
4282 Init,
4283 (flags & CLS_META) ?
4284 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4285 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4286 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004287 CLASS_RO_GV->setAlignment(
4288 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004289 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004290 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004291
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004292}
4293
4294/// BuildClassMetaData - This routine defines that to-level meta-data
4295/// for the given ClassName for:
4296/// struct _class_t {
4297/// struct _class_t *isa;
4298/// struct _class_t * const superclass;
4299/// void *cache;
4300/// IMP *vtable;
4301/// struct class_ro_t *ro;
4302/// }
4303///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004304llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4305 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004306 llvm::Constant *IsAGV,
4307 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004308 llvm::Constant *ClassRoGV,
4309 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004310 std::vector<llvm::Constant*> Values(5);
4311 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004312 Values[1] = SuperClassGV
4313 ? SuperClassGV
4314 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004315 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4316 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4317 Values[4] = ClassRoGV; // &CLASS_RO_GV
4318 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4319 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004320 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4321 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004322 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004323 GV->setAlignment(
4324 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004325 if (HiddenVisibility)
4326 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004327 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004328}
4329
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004330bool
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00004331CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
4332 return OD->getClassMethod(CGM.getContext(), GetNullarySelector("load")) != 0;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004333}
4334
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004335void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004336 uint32_t &InstanceStart,
4337 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004338 const ASTRecordLayout &RL =
4339 CGM.getContext().getASTObjCImplementationLayout(OID);
4340
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004341 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004342 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004343
4344 // If there are no fields, the start is the same as the end.
4345 if (!RL.getFieldCount())
4346 InstanceStart = InstanceSize;
4347 else
4348 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004349}
4350
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004351void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4352 std::string ClassName = ID->getNameAsString();
4353 if (!ObjCEmptyCacheVar) {
4354 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004355 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004356 false,
4357 llvm::GlobalValue::ExternalLinkage,
4358 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004359 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004360 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004361
4362 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004363 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004364 false,
4365 llvm::GlobalValue::ExternalLinkage,
4366 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004367 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004368 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004369 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004370 assert(ID->getClassInterface() &&
4371 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004372 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004373 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004374 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004375 uint32_t InstanceSize = InstanceStart;
4376 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004377 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4378 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004379
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004380 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004381
Daniel Dunbar04d40782009-04-14 06:00:08 +00004382 bool classIsHidden =
4383 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004384 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004385 flags |= OBJC2_CLS_HIDDEN;
4386 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004387 // class is root
4388 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004389 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004390 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004391 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004392 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004393 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4394 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4395 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004396 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004397 // work on super class metadata symbol.
4398 std::string SuperClassName =
4399 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004400 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004401 }
4402 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4403 InstanceStart,
4404 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004405 std::string TClassName = ObjCMetaClassName + ClassName;
4406 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004407 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4408 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004409
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004410 // Metadata for the class
4411 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004412 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004413 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004414
4415 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4416 flags |= CLS_EXCEPTION;
4417
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004418 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004419 flags |= CLS_ROOT;
4420 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004421 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004422 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004423 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004424 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004425 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004426 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004427 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004428 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004429 InstanceStart,
4430 InstanceSize,
4431 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004432
4433 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004434 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004435 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4436 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004437 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004438
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004439 // Determine if this class is also "non-lazy".
4440 if (ImplementationIsNonLazy(ID))
4441 DefinedNonLazyClasses.push_back(ClassMD);
4442
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004443 // Force the definition of the EHType if necessary.
4444 if (flags & CLS_EXCEPTION)
4445 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004446}
4447
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004448/// GenerateProtocolRef - This routine is called to generate code for
4449/// a protocol reference expression; as in:
4450/// @code
4451/// @protocol(Proto1);
4452/// @endcode
4453/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4454/// which will hold address of the protocol meta-data.
4455///
4456llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4457 const ObjCProtocolDecl *PD) {
4458
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004459 // This routine is called for @protocol only. So, we must build definition
4460 // of protocol's meta-data (not a reference to it!)
4461 //
4462 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004463 ObjCTypes.ExternalProtocolPtrTy);
4464
4465 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4466 ProtocolName += PD->getNameAsCString();
4467
4468 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4469 if (PTGV)
4470 return Builder.CreateLoad(PTGV, false, "tmp");
4471 PTGV = new llvm::GlobalVariable(
4472 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004473 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004474 Init,
4475 ProtocolName,
4476 &CGM.getModule());
4477 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4478 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4479 UsedGlobals.push_back(PTGV);
4480 return Builder.CreateLoad(PTGV, false, "tmp");
4481}
4482
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004483/// GenerateCategory - Build metadata for a category implementation.
4484/// struct _category_t {
4485/// const char * const name;
4486/// struct _class_t *const cls;
4487/// const struct _method_list_t * const instance_methods;
4488/// const struct _method_list_t * const class_methods;
4489/// const struct _protocol_list_t * const protocols;
4490/// const struct _prop_list_t * const properties;
4491/// }
4492///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004493void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004494 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004495 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4496 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004497 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004498 std::string ExtClassName(getClassSymbolPrefix() +
4499 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004500
4501 std::vector<llvm::Constant*> Values(6);
4502 Values[0] = GetClassName(OCD->getIdentifier());
4503 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004504 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004505 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004506 std::vector<llvm::Constant*> Methods;
4507 std::string MethodListName(Prefix);
4508 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4509 "_$_" + OCD->getNameAsString();
4510
Douglas Gregor653f1b12009-04-23 01:02:12 +00004511 for (ObjCCategoryImplDecl::instmeth_iterator
4512 i = OCD->instmeth_begin(CGM.getContext()),
4513 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004514 // Instance methods should always be defined.
4515 Methods.push_back(GetMethodConstant(*i));
4516 }
4517
4518 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004519 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004520 Methods);
4521
4522 MethodListName = Prefix;
4523 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4524 OCD->getNameAsString();
4525 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004526 for (ObjCCategoryImplDecl::classmeth_iterator
4527 i = OCD->classmeth_begin(CGM.getContext()),
4528 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004529 // Class methods should always be defined.
4530 Methods.push_back(GetMethodConstant(*i));
4531 }
4532
4533 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004534 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004535 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004536 const ObjCCategoryDecl *Category =
4537 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004538 if (Category) {
4539 std::string ExtName(Interface->getNameAsString() + "_$_" +
4540 OCD->getNameAsString());
4541 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4542 + Interface->getNameAsString() + "_$_"
4543 + Category->getNameAsString(),
4544 Category->protocol_begin(),
4545 Category->protocol_end());
4546 Values[5] =
4547 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4548 OCD, Category, ObjCTypes);
4549 }
4550 else {
4551 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4552 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4553 }
4554
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004555 llvm::Constant *Init =
4556 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4557 Values);
4558 llvm::GlobalVariable *GCATV
4559 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4560 false,
4561 llvm::GlobalValue::InternalLinkage,
4562 Init,
4563 ExtCatName,
4564 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004565 GCATV->setAlignment(
4566 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004567 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004568 UsedGlobals.push_back(GCATV);
4569 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004570
4571 // Determine if this category is also "non-lazy".
4572 if (ImplementationIsNonLazy(OCD))
4573 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004574}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004575
4576/// GetMethodConstant - Return a struct objc_method constant for the
4577/// given method if it has been defined. The result is null if the
4578/// method has not been defined. The return value has type MethodPtrTy.
4579llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4580 const ObjCMethodDecl *MD) {
4581 // FIXME: Use DenseMap::lookup
4582 llvm::Function *Fn = MethodDefinitions[MD];
4583 if (!Fn)
4584 return 0;
4585
4586 std::vector<llvm::Constant*> Method(3);
4587 Method[0] =
4588 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4589 ObjCTypes.SelectorPtrTy);
4590 Method[1] = GetMethodVarType(MD);
4591 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4592 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4593}
4594
4595/// EmitMethodList - Build meta-data for method declarations
4596/// struct _method_list_t {
4597/// uint32_t entsize; // sizeof(struct _objc_method)
4598/// uint32_t method_count;
4599/// struct _objc_method method_list[method_count];
4600/// }
4601///
4602llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4603 const std::string &Name,
4604 const char *Section,
4605 const ConstantVector &Methods) {
4606 // Return null for empty list.
4607 if (Methods.empty())
4608 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4609
4610 std::vector<llvm::Constant*> Values(3);
4611 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004612 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004613 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4614 // method_count
4615 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4616 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4617 Methods.size());
4618 Values[2] = llvm::ConstantArray::get(AT, Methods);
4619 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4620
4621 llvm::GlobalVariable *GV =
4622 new llvm::GlobalVariable(Init->getType(), false,
4623 llvm::GlobalValue::InternalLinkage,
4624 Init,
4625 Name,
4626 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004627 GV->setAlignment(
4628 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004629 GV->setSection(Section);
4630 UsedGlobals.push_back(GV);
4631 return llvm::ConstantExpr::getBitCast(GV,
4632 ObjCTypes.MethodListnfABIPtrTy);
4633}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004634
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004635/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4636/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004637llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004638 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004639 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004640 // FIXME: We shouldn't need to do this lookup.
4641 unsigned Index;
4642 const ObjCInterfaceDecl *Container =
4643 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4644 assert(Container && "Unable to find ivar container!");
4645 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004646 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004647 llvm::GlobalVariable *IvarOffsetGV =
4648 CGM.getModule().getGlobalVariable(Name);
4649 if (!IvarOffsetGV)
4650 IvarOffsetGV =
4651 new llvm::GlobalVariable(ObjCTypes.LongTy,
4652 false,
4653 llvm::GlobalValue::ExternalLinkage,
4654 0,
4655 Name,
4656 &CGM.getModule());
4657 return IvarOffsetGV;
4658}
4659
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004660llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004661 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004662 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004663 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004664 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4665 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4666 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004667 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004668 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004669
Mike Stumpf5408fe2009-05-16 07:57:57 +00004670 // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
4671 // well (i.e., in ObjCIvarOffsetVariable).
Daniel Dunbar737c5022009-04-19 00:44:02 +00004672 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4673 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4674 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004675 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004676 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004677 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004678 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004679 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004680}
4681
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004682/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004683/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004684/// IvarListnfABIPtrTy.
4685/// struct _ivar_t {
4686/// unsigned long int *offset; // pointer to ivar offset location
4687/// char *name;
4688/// char *type;
4689/// uint32_t alignment;
4690/// uint32_t size;
4691/// }
4692/// struct _ivar_list_t {
4693/// uint32 entsize; // sizeof(struct _ivar_t)
4694/// uint32 count;
4695/// struct _iver_t list[count];
4696/// }
4697///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004698
4699void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4700 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4701 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4702 E = OID->ivar_end(); I != E; ++I) {
4703 // Ignore unnamed bit-fields.
4704 if (!(*I)->getDeclName())
4705 continue;
4706
4707 Res.push_back(*I);
4708 }
4709
Fariborz Jahanian98200742009-05-12 18:14:29 +00004710 // Also save synthesize ivars.
4711 // FIXME. Why can't we just use passed in Res small vector?
4712 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
4713 CGM.getContext().CollectSynthesizedIvars(OID, Ivars);
4714 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
4715 Res.push_back(Ivars[k]);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004716}
4717
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004718llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4719 const ObjCImplementationDecl *ID) {
4720
4721 std::vector<llvm::Constant*> Ivars, Ivar(5);
4722
4723 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4724 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4725
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004726 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004727
Daniel Dunbar91636d62009-04-20 00:33:43 +00004728 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004729 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004730 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004731
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004732 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4733 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004734 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004735 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004736 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4737 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004738 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004739 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004740 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004741 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004742 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004743 Align = llvm::Log2_32(Align);
4744 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004745 // NOTE. Size of a bitfield does not match gcc's, because of the
4746 // way bitfields are treated special in each. But I am told that
4747 // 'size' for bitfield ivars is ignored by the runtime so it does
4748 // not matter. If it matters, there is enough info to get the
4749 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004750 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4751 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4752 }
4753 // Return null for empty list.
4754 if (Ivars.empty())
4755 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4756 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004757 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004758 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4759 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4760 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4761 Ivars.size());
4762 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4763 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4764 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4765 llvm::GlobalVariable *GV =
4766 new llvm::GlobalVariable(Init->getType(), false,
4767 llvm::GlobalValue::InternalLinkage,
4768 Init,
4769 Prefix + OID->getNameAsString(),
4770 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004771 GV->setAlignment(
4772 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004773 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004774
4775 UsedGlobals.push_back(GV);
4776 return llvm::ConstantExpr::getBitCast(GV,
4777 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004778}
4779
4780llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4781 const ObjCProtocolDecl *PD) {
4782 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4783
4784 if (!Entry) {
4785 // We use the initializer as a marker of whether this is a forward
4786 // reference or not. At module finalization we add the empty
4787 // contents for protocols which were referenced but never defined.
4788 Entry =
4789 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4790 llvm::GlobalValue::ExternalLinkage,
4791 0,
4792 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4793 &CGM.getModule());
4794 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4795 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 }
4797
4798 return Entry;
4799}
4800
4801/// GetOrEmitProtocol - Generate the protocol meta-data:
4802/// @code
4803/// struct _protocol_t {
4804/// id isa; // NULL
4805/// const char * const protocol_name;
4806/// const struct _protocol_list_t * protocol_list; // super protocols
4807/// const struct method_list_t * const instance_methods;
4808/// const struct method_list_t * const class_methods;
4809/// const struct method_list_t *optionalInstanceMethods;
4810/// const struct method_list_t *optionalClassMethods;
4811/// const struct _prop_list_t * properties;
4812/// const uint32_t size; // sizeof(struct _protocol_t)
4813/// const uint32_t flags; // = 0
4814/// }
4815/// @endcode
4816///
4817
4818llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4819 const ObjCProtocolDecl *PD) {
4820 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4821
4822 // Early exit if a defining object has already been generated.
4823 if (Entry && Entry->hasInitializer())
4824 return Entry;
4825
4826 const char *ProtocolName = PD->getNameAsCString();
4827
4828 // Construct method lists.
4829 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4830 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004831 for (ObjCProtocolDecl::instmeth_iterator
4832 i = PD->instmeth_begin(CGM.getContext()),
4833 e = PD->instmeth_end(CGM.getContext());
4834 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004835 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004836 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004837 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4838 OptInstanceMethods.push_back(C);
4839 } else {
4840 InstanceMethods.push_back(C);
4841 }
4842 }
4843
Douglas Gregor6ab35242009-04-09 21:40:53 +00004844 for (ObjCProtocolDecl::classmeth_iterator
4845 i = PD->classmeth_begin(CGM.getContext()),
4846 e = PD->classmeth_end(CGM.getContext());
4847 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004848 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004849 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004850 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4851 OptClassMethods.push_back(C);
4852 } else {
4853 ClassMethods.push_back(C);
4854 }
4855 }
4856
4857 std::vector<llvm::Constant*> Values(10);
4858 // isa is NULL
4859 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4860 Values[1] = GetClassName(PD->getIdentifier());
4861 Values[2] = EmitProtocolList(
4862 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4863 PD->protocol_begin(),
4864 PD->protocol_end());
4865
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004866 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004867 + PD->getNameAsString(),
4868 "__DATA, __objc_const",
4869 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004870 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004871 + PD->getNameAsString(),
4872 "__DATA, __objc_const",
4873 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004874 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004875 + PD->getNameAsString(),
4876 "__DATA, __objc_const",
4877 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004878 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004879 + PD->getNameAsString(),
4880 "__DATA, __objc_const",
4881 OptClassMethods);
4882 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4883 0, PD, ObjCTypes);
4884 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004885 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004886 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4887 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4888 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4889 Values);
4890
4891 if (Entry) {
4892 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004893 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004894 Entry->setInitializer(Init);
4895 } else {
4896 Entry =
4897 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004898 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004899 Init,
4900 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4901 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004902 Entry->setAlignment(
4903 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004904 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004905 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004906 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4907
4908 // Use this protocol meta-data to build protocol list table in section
4909 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004910 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004911 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004912 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004913 Entry,
4914 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4915 +ProtocolName,
4916 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004917 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004918 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004919 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004920 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4921 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004922 return Entry;
4923}
4924
4925/// EmitProtocolList - Generate protocol list meta-data:
4926/// @code
4927/// struct _protocol_list_t {
4928/// long protocol_count; // Note, this is 32/64 bit
4929/// struct _protocol_t[protocol_count];
4930/// }
4931/// @endcode
4932///
4933llvm::Constant *
4934CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4935 ObjCProtocolDecl::protocol_iterator begin,
4936 ObjCProtocolDecl::protocol_iterator end) {
4937 std::vector<llvm::Constant*> ProtocolRefs;
4938
Fariborz Jahanianda320092009-01-29 19:24:30 +00004939 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004940 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004941 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4942
Daniel Dunbar948e2582009-02-15 07:36:20 +00004943 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004944 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4945 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004946 return llvm::ConstantExpr::getBitCast(GV,
4947 ObjCTypes.ProtocolListnfABIPtrTy);
4948
4949 for (; begin != end; ++begin)
4950 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4951
Fariborz Jahanianda320092009-01-29 19:24:30 +00004952 // This list is null terminated.
4953 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004954 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004955
4956 std::vector<llvm::Constant*> Values(2);
4957 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4958 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004959 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004960 ProtocolRefs.size()),
4961 ProtocolRefs);
4962
4963 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4964 GV = new llvm::GlobalVariable(Init->getType(), false,
4965 llvm::GlobalValue::InternalLinkage,
4966 Init,
4967 Name,
4968 &CGM.getModule());
4969 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004970 GV->setAlignment(
4971 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004972 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004973 return llvm::ConstantExpr::getBitCast(GV,
4974 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004975}
4976
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004977/// GetMethodDescriptionConstant - This routine build following meta-data:
4978/// struct _objc_method {
4979/// SEL _cmd;
4980/// char *method_type;
4981/// char *_imp;
4982/// }
4983
4984llvm::Constant *
4985CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4986 std::vector<llvm::Constant*> Desc(3);
4987 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4988 ObjCTypes.SelectorPtrTy);
4989 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004990 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004991 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4992 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4993}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004994
4995/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4996/// This code gen. amounts to generating code for:
4997/// @code
4998/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4999/// @encode
5000///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00005001LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005002 CodeGen::CodeGenFunction &CGF,
5003 QualType ObjectTy,
5004 llvm::Value *BaseValue,
5005 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005006 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00005007 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00005008 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
5009 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005010}
5011
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005012llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
5013 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00005014 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005015 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00005016 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
5017 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005018}
5019
Fariborz Jahanian46551122009-02-04 00:22:57 +00005020CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
5021 CodeGen::CodeGenFunction &CGF,
5022 QualType ResultType,
5023 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005024 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00005025 QualType Arg0Ty,
5026 bool IsSuper,
5027 const CallArgList &CallArgs) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00005028 // FIXME. Even though IsSuper is passes. This function doese not handle calls
5029 // to 'super' receivers.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005030 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005031 llvm::Value *Arg0 = Receiver;
5032 if (!IsSuper)
5033 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005034
5035 // Find the message function name.
Mike Stumpf5408fe2009-05-16 07:57:57 +00005036 // FIXME. This is too much work to get the ABI-specific result type needed to
5037 // find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005038 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5039 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005040 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005041 std::string Name("\01l_");
5042 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005043#if 0
5044 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005045 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005046 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 // FIXME. Is there a better way of getting these names.
5048 // They are available in RuntimeFunctions vector pair.
5049 Name += "objc_msgSendId_stret_fixup";
5050 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005051 else
5052#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005053 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005054 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005055 Name += "objc_msgSendSuper2_stret_fixup";
5056 }
5057 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005058 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005059 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005060 Name += "objc_msgSend_stret_fixup";
5061 }
5062 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005063 else if (!IsSuper && ResultType->isFloatingType()) {
5064 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5065 BuiltinType::Kind k = BT->getKind();
5066 if (k == BuiltinType::LongDouble) {
5067 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5068 Name += "objc_msgSend_fpret_fixup";
5069 }
5070 else {
5071 Fn = ObjCTypes.getMessageSendFixupFn();
5072 Name += "objc_msgSend_fixup";
5073 }
5074 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005075 }
5076 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005077#if 0
5078// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005079 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005080 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005081 Name += "objc_msgSendId_fixup";
5082 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005083 else
5084#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005085 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005086 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005087 Name += "objc_msgSendSuper2_fixup";
5088 }
5089 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005090 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005091 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005092 Name += "objc_msgSend_fixup";
5093 }
5094 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005095 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005096 Name += '_';
5097 std::string SelName(Sel.getAsString());
5098 // Replace all ':' in selector name with '_' ouch!
5099 for(unsigned i = 0; i < SelName.size(); i++)
5100 if (SelName[i] == ':')
5101 SelName[i] = '_';
5102 Name += SelName;
5103 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5104 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005105 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005106 std::vector<llvm::Constant*> Values(2);
5107 Values[0] = Fn;
5108 Values[1] = GetMethodVarName(Sel);
5109 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5110 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005111 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005112 Init,
5113 Name,
5114 &CGM.getModule());
5115 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005116 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005117 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005118 }
5119 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005120
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005121 CallArgList ActualArgs;
5122 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5123 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5124 ObjCTypes.MessageRefCPtrTy));
5125 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005126 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5127 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5128 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005129 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005130 Callee = CGF.Builder.CreateBitCast(Callee,
5131 llvm::PointerType::getUnqual(FTy));
5132 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005133}
5134
5135/// Generate code for a message send expression in the nonfragile abi.
5136CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5137 CodeGen::CodeGenFunction &CGF,
5138 QualType ResultType,
5139 Selector Sel,
5140 llvm::Value *Receiver,
5141 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005142 const CallArgList &CallArgs,
5143 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005144 return LegacyDispatchedSelector(Sel)
5145 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5146 Receiver, CGF.getContext().getObjCIdType(),
5147 false, CallArgs, ObjCTypes)
5148 : EmitMessageSend(CGF, ResultType, Sel,
5149 Receiver, CGF.getContext().getObjCIdType(),
5150 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005151}
5152
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005153llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005154CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005155 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5156
Daniel Dunbardfff2302009-03-02 05:18:14 +00005157 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005158 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5159 llvm::GlobalValue::ExternalLinkage,
5160 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005161 }
5162
5163 return GV;
5164}
5165
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005166llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005167 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005168 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5169
5170 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005171 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005172 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005173 Entry =
5174 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5175 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005176 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005177 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005178 &CGM.getModule());
5179 Entry->setAlignment(
5180 CGM.getTargetData().getPrefTypeAlignment(
5181 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005182 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5183 UsedGlobals.push_back(Entry);
5184 }
5185
5186 return Builder.CreateLoad(Entry, false, "tmp");
5187}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005188
Daniel Dunbar11394522009-04-18 08:51:00 +00005189llvm::Value *
5190CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5191 const ObjCInterfaceDecl *ID) {
5192 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5193
5194 if (!Entry) {
5195 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5196 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5197 Entry =
5198 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5199 llvm::GlobalValue::InternalLinkage,
5200 ClassGV,
5201 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5202 &CGM.getModule());
5203 Entry->setAlignment(
5204 CGM.getTargetData().getPrefTypeAlignment(
5205 ObjCTypes.ClassnfABIPtrTy));
5206 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005207 UsedGlobals.push_back(Entry);
5208 }
5209
5210 return Builder.CreateLoad(Entry, false, "tmp");
5211}
5212
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005213/// EmitMetaClassRef - Return a Value * of the address of _class_t
5214/// meta-data
5215///
5216llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5217 const ObjCInterfaceDecl *ID) {
5218 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5219 if (Entry)
5220 return Builder.CreateLoad(Entry, false, "tmp");
5221
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005222 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005223 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005224 Entry =
5225 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5226 llvm::GlobalValue::InternalLinkage,
5227 MetaClassGV,
5228 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5229 &CGM.getModule());
5230 Entry->setAlignment(
5231 CGM.getTargetData().getPrefTypeAlignment(
5232 ObjCTypes.ClassnfABIPtrTy));
5233
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005234 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005235 UsedGlobals.push_back(Entry);
5236
5237 return Builder.CreateLoad(Entry, false, "tmp");
5238}
5239
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005240/// GetClass - Return a reference to the class for the given interface
5241/// decl.
5242llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5243 const ObjCInterfaceDecl *ID) {
5244 return EmitClassRef(Builder, ID);
5245}
5246
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005247/// Generates a message send where the super is the receiver. This is
5248/// a message send to self with special delivery semantics indicating
5249/// which class's method should be called.
5250CodeGen::RValue
5251CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5252 QualType ResultType,
5253 Selector Sel,
5254 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005255 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005256 llvm::Value *Receiver,
5257 bool IsClassMessage,
5258 const CodeGen::CallArgList &CallArgs) {
5259 // ...
5260 // Create and init a super structure; this is a (receiver, class)
5261 // pair we will pass to objc_msgSendSuper.
5262 llvm::Value *ObjCSuper =
5263 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5264
5265 llvm::Value *ReceiverAsObject =
5266 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5267 CGF.Builder.CreateStore(ReceiverAsObject,
5268 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5269
5270 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005271 llvm::Value *Target;
5272 if (IsClassMessage) {
5273 if (isCategoryImpl) {
5274 // Message sent to "super' in a class method defined in
5275 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005276 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005277 Target = CGF.Builder.CreateStructGEP(Target, 0);
5278 Target = CGF.Builder.CreateLoad(Target);
5279 }
5280 else
5281 Target = EmitMetaClassRef(CGF.Builder, Class);
5282 }
5283 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005284 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005285
Mike Stumpf5408fe2009-05-16 07:57:57 +00005286 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5287 // ObjCTypes types.
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005288 const llvm::Type *ClassTy =
5289 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5290 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5291 CGF.Builder.CreateStore(Target,
5292 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5293
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005294 return (LegacyDispatchedSelector(Sel))
5295 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5296 ObjCSuper, ObjCTypes.SuperPtrCTy,
5297 true, CallArgs,
5298 ObjCTypes)
5299 : EmitMessageSend(CGF, ResultType, Sel,
5300 ObjCSuper, ObjCTypes.SuperPtrCTy,
5301 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005302}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005303
5304llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5305 Selector Sel) {
5306 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5307
5308 if (!Entry) {
5309 llvm::Constant *Casted =
5310 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5311 ObjCTypes.SelectorPtrTy);
5312 Entry =
5313 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5314 llvm::GlobalValue::InternalLinkage,
5315 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5316 &CGM.getModule());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005317 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005318 UsedGlobals.push_back(Entry);
5319 }
5320
5321 return Builder.CreateLoad(Entry, false, "tmp");
5322}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005323/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5324/// objc_assign_ivar (id src, id *dst)
5325///
5326void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5327 llvm::Value *src, llvm::Value *dst)
5328{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005329 const llvm::Type * SrcTy = src->getType();
5330 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005331 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005332 assert(Size <= 8 && "does not support size > 8");
5333 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5334 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005335 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5336 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005337 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5338 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005339 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005340 src, dst, "assignivar");
5341 return;
5342}
5343
5344/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5345/// objc_assign_strongCast (id src, id *dst)
5346///
5347void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5348 CodeGen::CodeGenFunction &CGF,
5349 llvm::Value *src, llvm::Value *dst)
5350{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005351 const llvm::Type * SrcTy = src->getType();
5352 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005353 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005354 assert(Size <= 8 && "does not support size > 8");
5355 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5356 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005357 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5358 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005359 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5360 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005361 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005362 src, dst, "weakassign");
5363 return;
5364}
5365
5366/// EmitObjCWeakRead - Code gen for loading value of a __weak
5367/// object: objc_read_weak (id *src)
5368///
5369llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5370 CodeGen::CodeGenFunction &CGF,
5371 llvm::Value *AddrWeakObj)
5372{
Eli Friedman8339b352009-03-07 03:57:15 +00005373 const llvm::Type* DestTy =
5374 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005375 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005376 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005377 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005378 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005379 return read_weak;
5380}
5381
5382/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5383/// objc_assign_weak (id src, id *dst)
5384///
5385void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5386 llvm::Value *src, llvm::Value *dst)
5387{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005388 const llvm::Type * SrcTy = src->getType();
5389 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005390 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005391 assert(Size <= 8 && "does not support size > 8");
5392 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5393 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005394 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5395 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005396 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5397 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005398 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005399 src, dst, "weakassign");
5400 return;
5401}
5402
5403/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5404/// objc_assign_global (id src, id *dst)
5405///
5406void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5407 llvm::Value *src, llvm::Value *dst)
5408{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005409 const llvm::Type * SrcTy = src->getType();
5410 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005411 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005412 assert(Size <= 8 && "does not support size > 8");
5413 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5414 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005415 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5416 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005417 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5418 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005419 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005420 src, dst, "globalassign");
5421 return;
5422}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005423
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005424void
5425CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5426 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005427 bool isTry = isa<ObjCAtTryStmt>(S);
5428 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5429 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005430 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005431 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005432 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005433 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5434
5435 // For @synchronized, call objc_sync_enter(sync.expr). The
5436 // evaluation of the expression must occur before we enter the
5437 // @synchronized. We can safely avoid a temp here because jumps into
5438 // @synchronized are illegal & this will dominate uses.
5439 llvm::Value *SyncArg = 0;
5440 if (!isTry) {
5441 SyncArg =
5442 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5443 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005444 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005445 }
5446
5447 // Push an EH context entry, used for handling rethrows and jumps
5448 // through finally.
5449 CGF.PushCleanupBlock(FinallyBlock);
5450
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005451 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005452
5453 CGF.EmitBlock(TryBlock);
5454 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5455 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5456 CGF.EmitBranchThroughCleanup(FinallyEnd);
5457
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005458 // Emit the exception handler.
5459
5460 CGF.EmitBlock(TryHandler);
5461
5462 llvm::Value *llvm_eh_exception =
5463 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5464 llvm::Value *llvm_eh_selector_i64 =
5465 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5466 llvm::Value *llvm_eh_typeid_for_i64 =
5467 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5468 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5469 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5470
5471 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5472 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005473 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005474
5475 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005476 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005477 bool HasCatchAll = false;
5478 if (isTry) {
5479 if (const ObjCAtCatchStmt* CatchStmt =
5480 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5481 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005482 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005483 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005484
5485 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005486 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005487 // Use i8* null here to signal this is a catch all, not a cleanup.
5488 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5489 SelectorArgs.push_back(Null);
5490 HasCatchAll = true;
5491 break;
5492 }
5493
Daniel Dunbarede8de92009-03-06 00:01:21 +00005494 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5495 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496 llvm::Value *IDEHType =
5497 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5498 if (!IDEHType)
5499 IDEHType =
5500 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5501 llvm::GlobalValue::ExternalLinkage,
5502 0, "OBJC_EHTYPE_id", &CGM.getModule());
5503 SelectorArgs.push_back(IDEHType);
5504 HasCatchAll = true;
5505 break;
5506 }
5507
5508 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005509 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005510 assert(PT && "Invalid @catch type.");
5511 const ObjCInterfaceType *IT =
5512 PT->getPointeeType()->getAsObjCInterfaceType();
5513 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005514 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005515 SelectorArgs.push_back(EHType);
5516 }
5517 }
5518 }
5519
5520 // We use a cleanup unless there was already a catch all.
5521 if (!HasCatchAll) {
5522 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005523 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 }
5525
5526 llvm::Value *Selector =
5527 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5528 SelectorArgs.begin(), SelectorArgs.end(),
5529 "selector");
5530 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005531 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005532 const Stmt *CatchBody = Handlers[i].second;
5533
5534 llvm::BasicBlock *Next = 0;
5535
5536 // The last handler always matches.
5537 if (i + 1 != e) {
5538 assert(CatchParam && "Only last handler can be a catch all.");
5539
5540 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5541 Next = CGF.createBasicBlock("catch.next");
5542 llvm::Value *Id =
5543 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5544 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5545 ObjCTypes.Int8PtrTy));
5546 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5547 Match, Next);
5548
5549 CGF.EmitBlock(Match);
5550 }
5551
5552 if (CatchBody) {
5553 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5554 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5555
5556 // Cleanups must call objc_end_catch.
5557 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00005558 // FIXME: It seems incorrect for objc_begin_catch to be inside this
5559 // context, but this matches gcc.
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005560 CGF.PushCleanupBlock(MatchEnd);
5561 CGF.setInvokeDest(MatchHandler);
5562
5563 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005564 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005565
5566 // Bind the catch parameter if it exists.
5567 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005568 ExcObject =
5569 CGF.Builder.CreateBitCast(ExcObject,
5570 CGF.ConvertType(CatchParam->getType()));
5571 // CatchParam is a ParmVarDecl because of the grammar
5572 // construction used to handle this, but for codegen purposes
5573 // we treat this as a local decl.
5574 CGF.EmitLocalBlockVarDecl(*CatchParam);
5575 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 }
5577
5578 CGF.ObjCEHValueStack.push_back(ExcObject);
5579 CGF.EmitStmt(CatchBody);
5580 CGF.ObjCEHValueStack.pop_back();
5581
5582 CGF.EmitBranchThroughCleanup(FinallyEnd);
5583
5584 CGF.EmitBlock(MatchHandler);
5585
5586 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5587 // We are required to emit this call to satisfy LLVM, even
5588 // though we don't use the result.
5589 llvm::SmallVector<llvm::Value*, 8> Args;
5590 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005591 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005592 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5593 0));
5594 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5595 CGF.Builder.CreateStore(Exc, RethrowPtr);
5596 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5597
5598 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5599
5600 CGF.EmitBlock(MatchEnd);
5601
5602 // Unfortunately, we also have to generate another EH frame here
5603 // in case this throws.
5604 llvm::BasicBlock *MatchEndHandler =
5605 CGF.createBasicBlock("match.end.handler");
5606 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005607 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005608 Cont, MatchEndHandler,
5609 Args.begin(), Args.begin());
5610
5611 CGF.EmitBlock(Cont);
5612 if (Info.SwitchBlock)
5613 CGF.EmitBlock(Info.SwitchBlock);
5614 if (Info.EndBlock)
5615 CGF.EmitBlock(Info.EndBlock);
5616
5617 CGF.EmitBlock(MatchEndHandler);
5618 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5619 // We are required to emit this call to satisfy LLVM, even
5620 // though we don't use the result.
5621 Args.clear();
5622 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005623 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005624 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5625 0));
5626 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5627 CGF.Builder.CreateStore(Exc, RethrowPtr);
5628 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5629
5630 if (Next)
5631 CGF.EmitBlock(Next);
5632 } else {
5633 assert(!Next && "catchup should be last handler.");
5634
5635 CGF.Builder.CreateStore(Exc, RethrowPtr);
5636 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5637 }
5638 }
5639
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005640 // Pop the cleanup entry, the @finally is outside this cleanup
5641 // scope.
5642 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5643 CGF.setInvokeDest(PrevLandingPad);
5644
5645 CGF.EmitBlock(FinallyBlock);
5646
5647 if (isTry) {
5648 if (const ObjCAtFinallyStmt* FinallyStmt =
5649 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5650 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5651 } else {
5652 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5653 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005654 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005655 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005656
5657 if (Info.SwitchBlock)
5658 CGF.EmitBlock(Info.SwitchBlock);
5659 if (Info.EndBlock)
5660 CGF.EmitBlock(Info.EndBlock);
5661
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005662 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005663 CGF.EmitBranch(FinallyEnd);
5664
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005665 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005666 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005667 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005668 CGF.Builder.CreateUnreachable();
5669
5670 CGF.EmitBlock(FinallyEnd);
5671}
5672
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005673/// EmitThrowStmt - Generate code for a throw statement.
5674void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5675 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005676 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005677 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005678 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005679 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005680 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5681 "Unexpected rethrow outside @catch block.");
5682 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005683 }
5684
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005685 llvm::Value *ExceptionAsObject =
5686 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5687 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5688 if (InvokeDest) {
5689 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005690 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005691 Cont, InvokeDest,
5692 &ExceptionAsObject, &ExceptionAsObject + 1);
5693 CGF.EmitBlock(Cont);
5694 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005695 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005696 CGF.Builder.CreateUnreachable();
5697
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005698 // Clear the insertion point to indicate we are in unreachable code.
5699 CGF.Builder.ClearInsertionPoint();
5700}
Daniel Dunbare588b992009-03-01 04:46:24 +00005701
5702llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005703CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5704 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005705 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005706
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005707 // If we don't need a definition, return the entry if found or check
5708 // if we use an external reference.
5709 if (!ForDefinition) {
5710 if (Entry)
5711 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005712
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005713 // If this type (or a super class) has the __objc_exception__
5714 // attribute, emit an external reference.
5715 if (hasObjCExceptionAttribute(ID))
5716 return Entry =
5717 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5718 llvm::GlobalValue::ExternalLinkage,
5719 0,
5720 (std::string("OBJC_EHTYPE_$_") +
5721 ID->getIdentifier()->getName()),
5722 &CGM.getModule());
5723 }
5724
5725 // Otherwise we need to either make a new entry or fill in the
5726 // initializer.
5727 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005728 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005729 std::string VTableName = "objc_ehtype_vtable";
5730 llvm::GlobalVariable *VTableGV =
5731 CGM.getModule().getGlobalVariable(VTableName);
5732 if (!VTableGV)
5733 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5734 llvm::GlobalValue::ExternalLinkage,
5735 0, VTableName, &CGM.getModule());
5736
5737 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5738
5739 std::vector<llvm::Constant*> Values(3);
5740 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5741 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005742 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005743 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5744
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005745 if (Entry) {
5746 Entry->setInitializer(Init);
5747 } else {
5748 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5749 llvm::GlobalValue::WeakAnyLinkage,
5750 Init,
5751 (std::string("OBJC_EHTYPE_$_") +
5752 ID->getIdentifier()->getName()),
5753 &CGM.getModule());
5754 }
5755
Daniel Dunbar04d40782009-04-14 06:00:08 +00005756 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005757 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005758 Entry->setAlignment(8);
5759
5760 if (ForDefinition) {
5761 Entry->setSection("__DATA,__objc_const");
5762 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5763 } else {
5764 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5765 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005766
5767 return Entry;
5768}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005769
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005770/* *** */
5771
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005772CodeGen::CGObjCRuntime *
5773CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005774 return new CGObjCMac(CGM);
5775}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005776
5777CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005778CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005779 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005780}