blob: 5571f0f55822d01d9fc804a16d68daac04c8bf89 [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.
56 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(Context),
57 E = OID->prop_end(Context); I != E; ++I) {
58 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) {
59 if (OIVD == Ivar)
60 return OID;
61 ++Index;
62 }
Daniel Dunbara80a0f62009-04-22 17:43:55 +000063 }
64
Daniel Dunbar532d4da2009-05-03 13:15:50 +000065 // Otherwise check in the super class.
Daniel Dunbara81419d2009-05-05 00:36:57 +000066 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Daniel Dunbar532d4da2009-05-03 13:15:50 +000067 return FindIvarInterface(Context, Super, OIVD, Index);
68
69 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000070}
71
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000072static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
73 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000074 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000075 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000076 unsigned Index;
77 const ObjCInterfaceDecl *Container =
78 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
79 assert(Container && "Unable to find ivar container");
80
81 // If we know have an implementation (and the ivar is in it) then
82 // look up in the implementation layout.
83 const ASTRecordLayout *RL;
84 if (ID && ID->getClassInterface() == Container)
85 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
86 else
87 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
88 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000089}
90
91uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
92 const ObjCInterfaceDecl *OID,
93 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000094 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
95}
96
97uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
98 const ObjCImplementationDecl *OID,
99 const ObjCIvarDecl *Ivar) {
100 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +0000101}
102
103LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
104 const ObjCInterfaceDecl *OID,
105 llvm::Value *BaseValue,
106 const ObjCIvarDecl *Ivar,
107 unsigned CVRQualifiers,
108 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000109 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000110 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000111 QualType IvarTy = Ivar->getType();
112 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000113 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000114 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000115 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000116
117 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000118 // We need to compute the bit offset for the bit-field, the offset
119 // is to the byte. Note, there is a subtle invariant here: we can
120 // only call this routine on non-sythesized ivars but we may be
121 // called for synthesized ivars. However, a synthesized ivar can
122 // never be a bit-field so this is safe.
123 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
124
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000125 uint64_t BitFieldSize =
126 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
127 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000128 IvarTy->isSignedIntegerType(),
129 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000130 }
131
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000132 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
133 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000134 LValue::SetObjCIvar(LV, true);
135 return LV;
136}
137
138///
139
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000140namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000141
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000142 typedef std::vector<llvm::Constant*> ConstantVector;
143
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000144 // FIXME: We should find a nicer way to make the labels for
145 // metadata, string concatenation is lame.
146
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000147class ObjCCommonTypesHelper {
148protected:
149 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000150
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000151public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000152 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000153 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000154
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000155 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
156 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000157
158 /// PtrObjectPtrTy - LLVM type for id *
159 const llvm::Type *PtrObjectPtrTy;
160
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000161 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000162 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000163 /// ProtocolPtrTy - LLVM type for external protocol handles
164 /// (typeof(Protocol))
165 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000166
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000167 // SuperCTy - clang type for struct objc_super.
168 QualType SuperCTy;
169 // SuperPtrCTy - clang type for struct objc_super *.
170 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000171
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000172 /// SuperTy - LLVM type for struct objc_super.
173 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000174 /// SuperPtrTy - LLVM type for struct objc_super *.
175 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000176
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000177 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
178 /// in GCC parlance).
179 const llvm::StructType *PropertyTy;
180
181 /// PropertyListTy - LLVM type for struct objc_property_list
182 /// (_prop_list_t in GCC parlance).
183 const llvm::StructType *PropertyListTy;
184 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
185 const llvm::Type *PropertyListPtrTy;
186
187 // MethodTy - LLVM type for struct objc_method.
188 const llvm::StructType *MethodTy;
189
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000190 /// CacheTy - LLVM type for struct objc_cache.
191 const llvm::Type *CacheTy;
192 /// CachePtrTy - LLVM type for struct objc_cache *.
193 const llvm::Type *CachePtrTy;
194
Chris Lattner72db6c32009-04-22 02:44:54 +0000195 llvm::Constant *getGetPropertyFn() {
196 CodeGen::CodeGenTypes &Types = CGM.getTypes();
197 ASTContext &Ctx = CGM.getContext();
198 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
199 llvm::SmallVector<QualType,16> Params;
200 QualType IdType = Ctx.getObjCIdType();
201 QualType SelType = Ctx.getObjCSelType();
202 Params.push_back(IdType);
203 Params.push_back(SelType);
204 Params.push_back(Ctx.LongTy);
205 Params.push_back(Ctx.BoolTy);
206 const llvm::FunctionType *FTy =
207 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
208 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
209 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000210
Chris Lattner72db6c32009-04-22 02:44:54 +0000211 llvm::Constant *getSetPropertyFn() {
212 CodeGen::CodeGenTypes &Types = CGM.getTypes();
213 ASTContext &Ctx = CGM.getContext();
214 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
215 llvm::SmallVector<QualType,16> Params;
216 QualType IdType = Ctx.getObjCIdType();
217 QualType SelType = Ctx.getObjCSelType();
218 Params.push_back(IdType);
219 Params.push_back(SelType);
220 Params.push_back(Ctx.LongTy);
221 Params.push_back(IdType);
222 Params.push_back(Ctx.BoolTy);
223 Params.push_back(Ctx.BoolTy);
224 const llvm::FunctionType *FTy =
225 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
226 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
227 }
228
229 llvm::Constant *getEnumerationMutationFn() {
230 // void objc_enumerationMutation (id)
231 std::vector<const llvm::Type*> Args;
232 Args.push_back(ObjectPtrTy);
233 llvm::FunctionType *FTy =
234 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
235 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
236 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000237
238 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000239 llvm::Constant *getGcReadWeakFn() {
240 // id objc_read_weak (id *)
241 std::vector<const llvm::Type*> Args;
242 Args.push_back(ObjectPtrTy->getPointerTo());
243 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
244 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
245 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000246
247 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000248 llvm::Constant *getGcAssignWeakFn() {
249 // id objc_assign_weak (id, id *)
250 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
251 Args.push_back(ObjectPtrTy->getPointerTo());
252 llvm::FunctionType *FTy =
253 llvm::FunctionType::get(ObjectPtrTy, Args, false);
254 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
255 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000256
257 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000258 llvm::Constant *getGcAssignGlobalFn() {
259 // id objc_assign_global(id, id *)
260 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
261 Args.push_back(ObjectPtrTy->getPointerTo());
262 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
263 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
264 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000265
266 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000267 llvm::Constant *getGcAssignIvarFn() {
268 // id objc_assign_ivar(id, id *)
269 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
270 Args.push_back(ObjectPtrTy->getPointerTo());
271 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
272 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
273 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000274
275 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000276 llvm::Constant *getGcAssignStrongCastFn() {
277 // id objc_assign_global(id, id *)
278 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
279 Args.push_back(ObjectPtrTy->getPointerTo());
280 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
281 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
282 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000283
284 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000285 llvm::Constant *getExceptionThrowFn() {
286 // void objc_exception_throw(id)
287 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
288 llvm::FunctionType *FTy =
289 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
290 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
291 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000292
Daniel Dunbar1c566672009-02-24 01:43:46 +0000293 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000294 llvm::Constant *getSyncEnterFn() {
295 // void objc_sync_enter (id)
296 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
297 llvm::FunctionType *FTy =
298 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
299 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
300 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000301
302 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000303 llvm::Constant *getSyncExitFn() {
304 // void objc_sync_exit (id)
305 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
306 llvm::FunctionType *FTy =
307 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
308 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
309 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000310
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000311 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
312 ~ObjCCommonTypesHelper(){}
313};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000314
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000315/// ObjCTypesHelper - Helper class that encapsulates lazy
316/// construction of varies types used during ObjC generation.
317class ObjCTypesHelper : public ObjCCommonTypesHelper {
318private:
319
Chris Lattner4176b0c2009-04-22 02:32:31 +0000320 llvm::Constant *getMessageSendFn() {
321 // id objc_msgSend (id, SEL, ...)
322 std::vector<const llvm::Type*> Params;
323 Params.push_back(ObjectPtrTy);
324 Params.push_back(SelectorPtrTy);
325 return
326 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
327 Params, true),
328 "objc_msgSend");
329 }
330
331 llvm::Constant *getMessageSendStretFn() {
332 // id objc_msgSend_stret (id, SEL, ...)
333 std::vector<const llvm::Type*> Params;
334 Params.push_back(ObjectPtrTy);
335 Params.push_back(SelectorPtrTy);
336 return
337 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
338 Params, true),
339 "objc_msgSend_stret");
340
341 }
342
343 llvm::Constant *getMessageSendFpretFn() {
344 // FIXME: This should be long double on x86_64?
345 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
346 std::vector<const llvm::Type*> Params;
347 Params.push_back(ObjectPtrTy);
348 Params.push_back(SelectorPtrTy);
349 return
350 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
351 Params,
352 true),
353 "objc_msgSend_fpret");
354
355 }
356
357 llvm::Constant *getMessageSendSuperFn() {
358 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
359 std::vector<const llvm::Type*> Params;
360 Params.push_back(SuperPtrTy);
361 Params.push_back(SelectorPtrTy);
362 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
363 Params, true),
364 "objc_msgSendSuper");
365 }
366 llvm::Constant *getMessageSendSuperStretFn() {
367 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
368 // SEL op, ...)
369 std::vector<const llvm::Type*> Params;
370 Params.push_back(Int8PtrTy);
371 Params.push_back(SuperPtrTy);
372 Params.push_back(SelectorPtrTy);
373 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
374 Params, true),
375 "objc_msgSendSuper_stret");
376 }
377
378 llvm::Constant *getMessageSendSuperFpretFn() {
379 // There is no objc_msgSendSuper_fpret? How can that work?
380 return getMessageSendSuperFn();
381 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382
383public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000384 /// SymtabTy - LLVM type for struct objc_symtab.
385 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000386 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
387 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000388 /// ModuleTy - LLVM type for struct objc_module.
389 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000390
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000391 /// ProtocolTy - LLVM type for struct objc_protocol.
392 const llvm::StructType *ProtocolTy;
393 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
394 const llvm::Type *ProtocolPtrTy;
395 /// ProtocolExtensionTy - LLVM type for struct
396 /// objc_protocol_extension.
397 const llvm::StructType *ProtocolExtensionTy;
398 /// ProtocolExtensionTy - LLVM type for struct
399 /// objc_protocol_extension *.
400 const llvm::Type *ProtocolExtensionPtrTy;
401 /// MethodDescriptionTy - LLVM type for struct
402 /// objc_method_description.
403 const llvm::StructType *MethodDescriptionTy;
404 /// MethodDescriptionListTy - LLVM type for struct
405 /// objc_method_description_list.
406 const llvm::StructType *MethodDescriptionListTy;
407 /// MethodDescriptionListPtrTy - LLVM type for struct
408 /// objc_method_description_list *.
409 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000410 /// ProtocolListTy - LLVM type for struct objc_property_list.
411 const llvm::Type *ProtocolListTy;
412 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
413 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000414 /// CategoryTy - LLVM type for struct objc_category.
415 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000416 /// ClassTy - LLVM type for struct objc_class.
417 const llvm::StructType *ClassTy;
418 /// ClassPtrTy - LLVM type for struct objc_class *.
419 const llvm::Type *ClassPtrTy;
420 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
421 const llvm::StructType *ClassExtensionTy;
422 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
423 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000424 // IvarTy - LLVM type for struct objc_ivar.
425 const llvm::StructType *IvarTy;
426 /// IvarListTy - LLVM type for struct objc_ivar_list.
427 const llvm::Type *IvarListTy;
428 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
429 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000430 /// MethodListTy - LLVM type for struct objc_method_list.
431 const llvm::Type *MethodListTy;
432 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
433 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000434
435 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
436 const llvm::Type *ExceptionDataTy;
437
Anders Carlsson124526b2008-09-09 10:10:21 +0000438 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000439 llvm::Constant *getExceptionTryEnterFn() {
440 std::vector<const llvm::Type*> Params;
441 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
442 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
443 Params, false),
444 "objc_exception_try_enter");
445 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000446
447 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000448 llvm::Constant *getExceptionTryExitFn() {
449 std::vector<const llvm::Type*> Params;
450 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
451 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
452 Params, false),
453 "objc_exception_try_exit");
454 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000455
456 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000457 llvm::Constant *getExceptionExtractFn() {
458 std::vector<const llvm::Type*> Params;
459 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
460 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
461 Params, false),
462 "objc_exception_extract");
463
464 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000465
466 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000467 llvm::Constant *getExceptionMatchFn() {
468 std::vector<const llvm::Type*> Params;
469 Params.push_back(ClassPtrTy);
470 Params.push_back(ObjectPtrTy);
471 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
472 Params, false),
473 "objc_exception_match");
474
475 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000476
477 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000478 llvm::Constant *getSetJmpFn() {
479 std::vector<const llvm::Type*> Params;
480 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
481 return
482 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
483 Params, false),
484 "_setjmp");
485
486 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000487
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000488public:
489 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000490 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000491
492
Chris Lattner74391b42009-03-22 21:03:39 +0000493 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000494 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000495 }
496
Chris Lattner74391b42009-03-22 21:03:39 +0000497 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000498 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000499 }
500
Chris Lattner74391b42009-03-22 21:03:39 +0000501 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000502 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000503 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000504};
505
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000506/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000507/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000508class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000509public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000510
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000511 // MethodListnfABITy - LLVM for struct _method_list_t
512 const llvm::StructType *MethodListnfABITy;
513
514 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
515 const llvm::Type *MethodListnfABIPtrTy;
516
517 // ProtocolnfABITy = LLVM for struct _protocol_t
518 const llvm::StructType *ProtocolnfABITy;
519
Daniel Dunbar948e2582009-02-15 07:36:20 +0000520 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
521 const llvm::Type *ProtocolnfABIPtrTy;
522
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000523 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
524 const llvm::StructType *ProtocolListnfABITy;
525
526 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
527 const llvm::Type *ProtocolListnfABIPtrTy;
528
529 // ClassnfABITy - LLVM for struct _class_t
530 const llvm::StructType *ClassnfABITy;
531
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000532 // ClassnfABIPtrTy - LLVM for struct _class_t*
533 const llvm::Type *ClassnfABIPtrTy;
534
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000535 // IvarnfABITy - LLVM for struct _ivar_t
536 const llvm::StructType *IvarnfABITy;
537
538 // IvarListnfABITy - LLVM for struct _ivar_list_t
539 const llvm::StructType *IvarListnfABITy;
540
541 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
542 const llvm::Type *IvarListnfABIPtrTy;
543
544 // ClassRonfABITy - LLVM for struct _class_ro_t
545 const llvm::StructType *ClassRonfABITy;
546
547 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
548 const llvm::Type *ImpnfABITy;
549
550 // CategorynfABITy - LLVM for struct _category_t
551 const llvm::StructType *CategorynfABITy;
552
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000553 // New types for nonfragile abi messaging.
554
555 // MessageRefTy - LLVM for:
556 // struct _message_ref_t {
557 // IMP messenger;
558 // SEL name;
559 // };
560 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000561 // MessageRefCTy - clang type for struct _message_ref_t
562 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000563
564 // MessageRefPtrTy - LLVM for struct _message_ref_t*
565 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000566 // MessageRefCPtrTy - clang type for struct _message_ref_t*
567 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000568
Fariborz Jahanianef163782009-02-05 01:13:09 +0000569 // MessengerTy - Type of the messenger (shown as IMP above)
570 const llvm::FunctionType *MessengerTy;
571
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000572 // SuperMessageRefTy - LLVM for:
573 // struct _super_message_ref_t {
574 // SUPER_IMP messenger;
575 // SEL name;
576 // };
577 const llvm::StructType *SuperMessageRefTy;
578
579 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
580 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000581
Chris Lattner1c02f862009-04-22 02:53:24 +0000582 llvm::Constant *getMessageSendFixupFn() {
583 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
584 std::vector<const llvm::Type*> Params;
585 Params.push_back(ObjectPtrTy);
586 Params.push_back(MessageRefPtrTy);
587 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
588 Params, true),
589 "objc_msgSend_fixup");
590 }
591
592 llvm::Constant *getMessageSendFpretFixupFn() {
593 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
594 std::vector<const llvm::Type*> Params;
595 Params.push_back(ObjectPtrTy);
596 Params.push_back(MessageRefPtrTy);
597 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
598 Params, true),
599 "objc_msgSend_fpret_fixup");
600 }
601
602 llvm::Constant *getMessageSendStretFixupFn() {
603 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
604 std::vector<const llvm::Type*> Params;
605 Params.push_back(ObjectPtrTy);
606 Params.push_back(MessageRefPtrTy);
607 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
608 Params, true),
609 "objc_msgSend_stret_fixup");
610 }
611
612 llvm::Constant *getMessageSendIdFixupFn() {
613 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
614 std::vector<const llvm::Type*> Params;
615 Params.push_back(ObjectPtrTy);
616 Params.push_back(MessageRefPtrTy);
617 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
618 Params, true),
619 "objc_msgSendId_fixup");
620 }
621
622 llvm::Constant *getMessageSendIdStretFixupFn() {
623 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
624 std::vector<const llvm::Type*> Params;
625 Params.push_back(ObjectPtrTy);
626 Params.push_back(MessageRefPtrTy);
627 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
628 Params, true),
629 "objc_msgSendId_stret_fixup");
630 }
631 llvm::Constant *getMessageSendSuper2FixupFn() {
632 // id objc_msgSendSuper2_fixup (struct objc_super *,
633 // struct _super_message_ref_t*, ...)
634 std::vector<const llvm::Type*> Params;
635 Params.push_back(SuperPtrTy);
636 Params.push_back(SuperMessageRefPtrTy);
637 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
638 Params, true),
639 "objc_msgSendSuper2_fixup");
640 }
641
642 llvm::Constant *getMessageSendSuper2StretFixupFn() {
643 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
644 // struct _super_message_ref_t*, ...)
645 std::vector<const llvm::Type*> Params;
646 Params.push_back(SuperPtrTy);
647 Params.push_back(SuperMessageRefPtrTy);
648 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
649 Params, true),
650 "objc_msgSendSuper2_stret_fixup");
651 }
652
653
654
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000655 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
656 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000657 llvm::Value *getEHPersonalityPtr() {
658 llvm::Constant *Personality =
659 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
660 std::vector<const llvm::Type*>(),
661 true),
662 "__objc_personality_v0");
663 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
664 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000665
Chris Lattner8a569112009-04-22 02:15:23 +0000666 llvm::Constant *getUnwindResumeOrRethrowFn() {
667 std::vector<const llvm::Type*> Params;
668 Params.push_back(Int8PtrTy);
669 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
670 Params, false),
671 "_Unwind_Resume_or_Rethrow");
672 }
673
674 llvm::Constant *getObjCEndCatchFn() {
675 std::vector<const llvm::Type*> Params;
676 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
677 Params, false),
678 "objc_end_catch");
679
680 }
681
682 llvm::Constant *getObjCBeginCatchFn() {
683 std::vector<const llvm::Type*> Params;
684 Params.push_back(Int8PtrTy);
685 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
686 Params, false),
687 "objc_begin_catch");
688 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000689
690 const llvm::StructType *EHTypeTy;
691 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000692
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000693 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
694 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000695};
696
697class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000698public:
699 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000700 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000701 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000702 unsigned ivar_bytepos;
703 unsigned ivar_size;
704 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
705 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000706
707 // Allow sorting based on byte pos.
708 bool operator<(const GC_IVAR &b) const {
709 return ivar_bytepos < b.ivar_bytepos;
710 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000711 };
712
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000713 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000714 public:
715 unsigned skip;
716 unsigned scan;
717 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
718 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000719 };
720
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000721protected:
722 CodeGen::CodeGenModule &CGM;
723 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000724 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000725
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000726 // gc ivar layout bitmap calculation helper caches.
727 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
728 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000729
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000730 /// LazySymbols - Symbols to generate a lazy reference for. See
731 /// DefinedSymbols and FinishModule().
732 std::set<IdentifierInfo*> LazySymbols;
733
734 /// DefinedSymbols - External symbols which are defined by this
735 /// module. The symbols in this list and LazySymbols are used to add
736 /// special linker symbols which ensure that Objective-C modules are
737 /// linked properly.
738 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000739
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000740 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000741 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000742
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000743 /// MethodVarNames - uniqued method variable names.
744 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000745
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000746 /// MethodVarTypes - uniqued method type signatures. We have to use
747 /// a StringMap here because have no other unique reference.
748 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000749
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000750 /// MethodDefinitions - map of methods which have been defined in
751 /// this translation unit.
752 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000753
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000754 /// PropertyNames - uniqued method variable names.
755 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000756
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000757 /// ClassReferences - uniqued class references.
758 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000759
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000760 /// SelectorReferences - uniqued selector references.
761 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000762
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000763 /// Protocols - Protocols for which an objc_protocol structure has
764 /// been emitted. Forward declarations are handled by creating an
765 /// empty structure whose initializer is filled in when/if defined.
766 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000767
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000768 /// DefinedProtocols - Protocols which have actually been
769 /// defined. We should not need this, see FIXME in GenerateProtocol.
770 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000771
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000772 /// DefinedClasses - List of defined classes.
773 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000774
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000775 /// DefinedCategories - List of defined categories.
776 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000777
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000778 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000779 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000780 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000781
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000782 /// GetNameForMethod - Return a name for the given method.
783 /// \param[out] NameOut - The return value.
784 void GetNameForMethod(const ObjCMethodDecl *OMD,
785 const ObjCContainerDecl *CD,
786 std::string &NameOut);
787
788 /// GetMethodVarName - Return a unique constant for the given
789 /// selector's name. The return value has type char *.
790 llvm::Constant *GetMethodVarName(Selector Sel);
791 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
792 llvm::Constant *GetMethodVarName(const std::string &Name);
793
794 /// GetMethodVarType - Return a unique constant for the given
795 /// selector's name. The return value has type char *.
796
797 // FIXME: This is a horrible name.
798 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000799 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000800
801 /// GetPropertyName - Return a unique constant for the given
802 /// name. The return value has type char *.
803 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
804
805 // FIXME: This can be dropped once string functions are unified.
806 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
807 const Decl *Container);
808
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000809 /// GetClassName - Return a unique constant for the given selector's
810 /// name. The return value has type char *.
811 llvm::Constant *GetClassName(IdentifierInfo *Ident);
812
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000813 /// BuildIvarLayout - Builds ivar layout bitmap for the class
814 /// implementation for the __strong or __weak case.
815 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000816 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
817 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000818
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000819 void BuildAggrIvarRecordLayout(const RecordType *RT,
820 unsigned int BytePos, bool ForStrongLayout,
821 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000822 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000823 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000824 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000825 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000826 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000827 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000828
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000829 /// GetIvarLayoutName - Returns a unique constant for the given
830 /// ivar layout bitmap.
831 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
832 const ObjCCommonTypesHelper &ObjCTypes);
833
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000834 /// EmitPropertyList - Emit the given property list. The return
835 /// value has type PropertyListPtrTy.
836 llvm::Constant *EmitPropertyList(const std::string &Name,
837 const Decl *Container,
838 const ObjCContainerDecl *OCD,
839 const ObjCCommonTypesHelper &ObjCTypes);
840
Fariborz Jahanianda320092009-01-29 19:24:30 +0000841 /// GetProtocolRef - Return a reference to the internal protocol
842 /// description, creating an empty one if it has not been
843 /// defined. The return value has type ProtocolPtrTy.
844 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000845
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000846 /// CreateMetadataVar - Create a global variable with internal
847 /// linkage for use by the Objective-C runtime.
848 ///
849 /// This is a convenience wrapper which not only creates the
850 /// variable, but also sets the section and alignment and adds the
851 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000852 ///
853 /// \param Name - The variable name.
854 /// \param Init - The variable initializer; this is also used to
855 /// define the type of the variable.
856 /// \param Section - The section the variable should go into, or 0.
857 /// \param Align - The alignment for the variable, or 0.
858 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000859 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000860 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
861 llvm::Constant *Init,
862 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000863 unsigned Align,
864 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000865
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000866 /// GetNamedIvarList - Return the list of ivars in the interface
867 /// itself (not including super classes and not including unnamed
868 /// bitfields).
869 ///
870 /// For the non-fragile ABI, this also includes synthesized property
871 /// ivars.
872 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
873 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
874
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000875public:
876 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
877 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000878
Steve Naroff33fdb732009-03-31 16:53:37 +0000879 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000880
881 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
882 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000883
884 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
885
886 /// GetOrEmitProtocol - Get the protocol object for the given
887 /// declaration, emitting it if necessary. The return value has type
888 /// ProtocolPtrTy.
889 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
890
891 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
892 /// object for the given declaration, emitting it if needed. These
893 /// forward references will be filled in with empty bodies if no
894 /// definition is seen. The return value has type ProtocolPtrTy.
895 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000896};
897
898class CGObjCMac : public CGObjCCommonMac {
899private:
900 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000901 /// EmitImageInfo - Emit the image info marker used to encode some module
902 /// level information.
903 void EmitImageInfo();
904
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000905 /// EmitModuleInfo - Another marker encoding module level
906 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000907 void EmitModuleInfo();
908
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000909 /// EmitModuleSymols - Emit module symbols, the list of defined
910 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000911 llvm::Constant *EmitModuleSymbols();
912
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000913 /// FinishModule - Write out global data structures at the end of
914 /// processing a translation unit.
915 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000916
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000917 /// EmitClassExtension - Generate the class extension structure used
918 /// to store the weak ivar layout and properties. The return value
919 /// has type ClassExtensionPtrTy.
920 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
921
922 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
923 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000924 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000925 const ObjCInterfaceDecl *ID);
926
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000927 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000928 QualType ResultType,
929 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000930 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000931 QualType Arg0Ty,
932 bool IsSuper,
933 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000934
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000935 /// EmitIvarList - Emit the ivar list for the given
936 /// implementation. If ForClass is true the list of class ivars
937 /// (i.e. metaclass ivars) is emitted, otherwise the list of
938 /// interface ivars will be emitted. The return value has type
939 /// IvarListPtrTy.
940 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000941 bool ForClass);
942
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000943 /// EmitMetaClass - Emit a forward reference to the class structure
944 /// for the metaclass of the given interface. The return value has
945 /// type ClassPtrTy.
946 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
947
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000948 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000949 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000950 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
951 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000952 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000953
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000954 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000955
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000956 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000957
958 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000959 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000960 llvm::Constant *EmitMethodList(const std::string &Name,
961 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000962 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000963
964 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000965 /// method declarations.
966 /// - TypeName: The name for the type containing the methods.
967 /// - IsProtocol: True iff these methods are for a protocol.
968 /// - ClassMethds: True iff these are class methods.
969 /// - Required: When true, only "required" methods are
970 /// listed. Similarly, when false only "optional" methods are
971 /// listed. For classes this should always be true.
972 /// - begin, end: The method list to output.
973 ///
974 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000975 llvm::Constant *EmitMethodDescList(const std::string &Name,
976 const char *Section,
977 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000978
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000979 /// GetOrEmitProtocol - Get the protocol object for the given
980 /// declaration, emitting it if necessary. The return value has type
981 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000982 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000983
984 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
985 /// object for the given declaration, emitting it if needed. These
986 /// forward references will be filled in with empty bodies if no
987 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000988 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000989
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000990 /// EmitProtocolExtension - Generate the protocol extension
991 /// structure used to store optional instance and class methods, and
992 /// protocol properties. The return value has type
993 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000994 llvm::Constant *
995 EmitProtocolExtension(const ObjCProtocolDecl *PD,
996 const ConstantVector &OptInstanceMethods,
997 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000998
999 /// EmitProtocolList - Generate the list of referenced
1000 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001001 llvm::Constant *EmitProtocolList(const std::string &Name,
1002 ObjCProtocolDecl::protocol_iterator begin,
1003 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001004
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001005 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1006 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001007 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001008
Fariborz Jahanianda320092009-01-29 19:24:30 +00001009 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001010 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001011
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001012 virtual llvm::Function *ModuleInitFunction();
1013
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001014 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001015 QualType ResultType,
1016 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001017 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001018 bool IsClassMessage,
1019 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001020
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001021 virtual CodeGen::RValue
1022 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001023 QualType ResultType,
1024 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001025 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001026 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001027 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001028 bool IsClassMessage,
1029 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001030
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001031 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001032 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001033
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001034 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001035
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001036 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001037
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001038 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001040 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001041 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001042
Chris Lattner74391b42009-03-22 21:03:39 +00001043 virtual llvm::Constant *GetPropertyGetFunction();
1044 virtual llvm::Constant *GetPropertySetFunction();
1045 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001046
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001047 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1048 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001049 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1050 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001051 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001052 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001053 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1054 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001055 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1056 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001057 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1058 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001059 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1060 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001061
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001062 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1063 QualType ObjectTy,
1064 llvm::Value *BaseValue,
1065 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001066 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001067 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001068 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001069 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001070};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001071
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001072class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001073private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001074 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001075 llvm::GlobalVariable* ObjCEmptyCacheVar;
1076 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001077
Daniel Dunbar11394522009-04-18 08:51:00 +00001078 /// SuperClassReferences - uniqued super class references.
1079 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1080
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001081 /// MetaClassReferences - uniqued meta class references.
1082 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001083
1084 /// EHTypeReferences - uniqued class ehtype references.
1085 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001086
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001087 /// FinishNonFragileABIModule - Write out global data structures at the end of
1088 /// processing a translation unit.
1089 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001090
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001091 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1092 unsigned InstanceStart,
1093 unsigned InstanceSize,
1094 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001095 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1096 llvm::Constant *IsAGV,
1097 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001098 llvm::Constant *ClassRoGV,
1099 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001100
1101 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1102
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001103 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1104
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001105 /// EmitMethodList - Emit the method list for the given
1106 /// implementation. The return value has type MethodListnfABITy.
1107 llvm::Constant *EmitMethodList(const std::string &Name,
1108 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001109 const ConstantVector &Methods);
1110 /// EmitIvarList - Emit the ivar list for the given
1111 /// implementation. If ForClass is true the list of class ivars
1112 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1113 /// interface ivars will be emitted. The return value has type
1114 /// IvarListnfABIPtrTy.
1115 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001116
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001117 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001118 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001119 unsigned long int offset);
1120
Fariborz Jahanianda320092009-01-29 19:24:30 +00001121 /// GetOrEmitProtocol - Get the protocol object for the given
1122 /// declaration, emitting it if necessary. The return value has type
1123 /// ProtocolPtrTy.
1124 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1125
1126 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1127 /// object for the given declaration, emitting it if needed. These
1128 /// forward references will be filled in with empty bodies if no
1129 /// definition is seen. The return value has type ProtocolPtrTy.
1130 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1131
1132 /// EmitProtocolList - Generate the list of referenced
1133 /// protocols. The return value has type ProtocolListPtrTy.
1134 llvm::Constant *EmitProtocolList(const std::string &Name,
1135 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001136 ObjCProtocolDecl::protocol_iterator end);
1137
1138 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1139 QualType ResultType,
1140 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001141 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001142 QualType Arg0Ty,
1143 bool IsSuper,
1144 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001145
1146 /// GetClassGlobal - Return the global variable for the Objective-C
1147 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001148 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1149
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001150 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001151 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001152 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001153 const ObjCInterfaceDecl *ID);
1154
1155 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1156 /// for the given super class reference.
1157 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1158 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001159
1160 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1161 /// meta-data
1162 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1163 const ObjCInterfaceDecl *ID);
1164
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001165 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1166 /// the given ivar.
1167 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001168 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001169 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001170 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001171
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001172 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1173 /// for the given selector.
1174 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001175
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001176 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001177 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001178 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1179 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001180
1181 const char *getMetaclassSymbolPrefix() const {
1182 return "OBJC_METACLASS_$_";
1183 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001184
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001185 const char *getClassSymbolPrefix() const {
1186 return "OBJC_CLASS_$_";
1187 }
1188
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001189 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001190 uint32_t &InstanceStart,
1191 uint32_t &InstanceSize);
1192
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001193public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001194 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001195 // FIXME. All stubs for now!
1196 virtual llvm::Function *ModuleInitFunction();
1197
1198 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1199 QualType ResultType,
1200 Selector Sel,
1201 llvm::Value *Receiver,
1202 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001203 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001204
1205 virtual CodeGen::RValue
1206 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1207 QualType ResultType,
1208 Selector Sel,
1209 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001210 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001211 llvm::Value *Receiver,
1212 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001213 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001214
1215 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001216 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001217
1218 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001219 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001220
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001221 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001222
1223 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001224 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001225 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001226
Chris Lattner74391b42009-03-22 21:03:39 +00001227 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001228 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001229 }
Chris Lattner74391b42009-03-22 21:03:39 +00001230 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001231 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001232 }
Chris Lattner74391b42009-03-22 21:03:39 +00001233 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001234 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001235 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001236
1237 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001238 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001239 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001240 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001241 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001242 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001243 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001244 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001245 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001246 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001247 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001248 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001249 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001250 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001251 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1252 QualType ObjectTy,
1253 llvm::Value *BaseValue,
1254 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001255 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001256 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001257 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001258 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001259};
1260
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001261} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001262
1263/* *** Helper Functions *** */
1264
1265/// getConstantGEP() - Help routine to construct simple GEPs.
1266static llvm::Constant *getConstantGEP(llvm::Constant *C,
1267 unsigned idx0,
1268 unsigned idx1) {
1269 llvm::Value *Idxs[] = {
1270 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1271 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1272 };
1273 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1274}
1275
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001276/// hasObjCExceptionAttribute - Return true if this class or any super
1277/// class has the __objc_exception__ attribute.
1278static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001279 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001280 return true;
1281 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1282 return hasObjCExceptionAttribute(Super);
1283 return false;
1284}
1285
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001286/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001287
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001288CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1289 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001290{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001291 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001292 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001293}
1294
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001295/// GetClass - Return a reference to the class for the given interface
1296/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001297llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001298 const ObjCInterfaceDecl *ID) {
1299 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001300}
1301
1302/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001303llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001304 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001305}
1306
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001307/// Generate a constant CFString object.
1308/*
1309 struct __builtin_CFString {
1310 const int *isa; // point to __CFConstantStringClassReference
1311 int flags;
1312 const char *str;
1313 long length;
1314 };
1315*/
1316
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001317llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001318 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001319 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001320}
1321
1322/// Generates a message send where the super is the receiver. This is
1323/// a message send to self with special delivery semantics indicating
1324/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001325CodeGen::RValue
1326CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001327 QualType ResultType,
1328 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001329 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001330 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001331 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001332 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001333 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001334 // Create and init a super structure; this is a (receiver, class)
1335 // pair we will pass to objc_msgSendSuper.
1336 llvm::Value *ObjCSuper =
1337 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1338 llvm::Value *ReceiverAsObject =
1339 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1340 CGF.Builder.CreateStore(ReceiverAsObject,
1341 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001342
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001343 // If this is a class message the metaclass is passed as the target.
1344 llvm::Value *Target;
1345 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001346 if (isCategoryImpl) {
1347 // Message sent to 'super' in a class method defined in a category
1348 // implementation requires an odd treatment.
1349 // If we are in a class method, we must retrieve the
1350 // _metaclass_ for the current class, pointed at by
1351 // the class's "isa" pointer. The following assumes that
1352 // isa" is the first ivar in a class (which it must be).
1353 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1354 Target = CGF.Builder.CreateStructGEP(Target, 0);
1355 Target = CGF.Builder.CreateLoad(Target);
1356 }
1357 else {
1358 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1359 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1360 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1361 Target = Super;
1362 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001363 } else {
1364 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1365 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001366 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1367 // and ObjCTypes types.
1368 const llvm::Type *ClassTy =
1369 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001370 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001371 CGF.Builder.CreateStore(Target,
1372 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1373
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001374 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001375 ObjCSuper, ObjCTypes.SuperPtrCTy,
1376 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001377}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001378
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001379/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001380CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001381 QualType ResultType,
1382 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001383 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001384 bool IsClassMessage,
1385 const CallArgList &CallArgs) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001386 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001387 Receiver, CGF.getContext().getObjCIdType(),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001388 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001389}
1390
1391CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001392 QualType ResultType,
1393 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001394 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001395 QualType Arg0Ty,
1396 bool IsSuper,
1397 const CallArgList &CallArgs) {
1398 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001399 if (!IsSuper)
1400 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001401 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1402 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1403 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001404 CGF.getContext().getObjCSelType()));
1405 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001406
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001407 CodeGenTypes &Types = CGM.getTypes();
1408 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian65257ca2009-04-29 22:47:27 +00001409 // FIXME. vararg flag must be true when this API is used for 64bit code gen.
1410 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001411
1412 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001413 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001414 Fn = ObjCTypes.getSendStretFn(IsSuper);
1415 } else if (ResultType->isFloatingType()) {
1416 // FIXME: Sadly, this is wrong. This actually depends on the
1417 // architecture. This happens to be right for x86-32 though.
1418 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1419 } else {
1420 Fn = ObjCTypes.getSendFn(IsSuper);
1421 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001422 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001423 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001424}
1425
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001426llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001427 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001428 // FIXME: I don't understand why gcc generates this, or where it is
1429 // resolved. Investigate. Its also wasteful to look this up over and
1430 // over.
1431 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1432
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001433 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1434 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001435}
1436
Fariborz Jahanianda320092009-01-29 19:24:30 +00001437void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001438 // FIXME: We shouldn't need this, the protocol decl should contain
1439 // enough information to tell us whether this was a declaration or a
1440 // definition.
1441 DefinedProtocols.insert(PD->getIdentifier());
1442
1443 // If we have generated a forward reference to this protocol, emit
1444 // it now. Otherwise do nothing, the protocol objects are lazily
1445 // emitted.
1446 if (Protocols.count(PD->getIdentifier()))
1447 GetOrEmitProtocol(PD);
1448}
1449
Fariborz Jahanianda320092009-01-29 19:24:30 +00001450llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001451 if (DefinedProtocols.count(PD->getIdentifier()))
1452 return GetOrEmitProtocol(PD);
1453 return GetOrEmitProtocolRef(PD);
1454}
1455
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001456/*
1457 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1458 struct _objc_protocol {
1459 struct _objc_protocol_extension *isa;
1460 char *protocol_name;
1461 struct _objc_protocol_list *protocol_list;
1462 struct _objc__method_prototype_list *instance_methods;
1463 struct _objc__method_prototype_list *class_methods
1464 };
1465
1466 See EmitProtocolExtension().
1467*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001468llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1469 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1470
1471 // Early exit if a defining object has already been generated.
1472 if (Entry && Entry->hasInitializer())
1473 return Entry;
1474
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001475 // FIXME: I don't understand why gcc generates this, or where it is
1476 // resolved. Investigate. Its also wasteful to look this up over and
1477 // over.
1478 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1479
Chris Lattner8ec03f52008-11-24 03:54:41 +00001480 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001481
1482 // Construct method lists.
1483 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1484 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001485 for (ObjCProtocolDecl::instmeth_iterator
1486 i = PD->instmeth_begin(CGM.getContext()),
1487 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001488 ObjCMethodDecl *MD = *i;
1489 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1490 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1491 OptInstanceMethods.push_back(C);
1492 } else {
1493 InstanceMethods.push_back(C);
1494 }
1495 }
1496
Douglas Gregor6ab35242009-04-09 21:40:53 +00001497 for (ObjCProtocolDecl::classmeth_iterator
1498 i = PD->classmeth_begin(CGM.getContext()),
1499 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001500 ObjCMethodDecl *MD = *i;
1501 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1502 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1503 OptClassMethods.push_back(C);
1504 } else {
1505 ClassMethods.push_back(C);
1506 }
1507 }
1508
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001509 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001510 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001511 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001512 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001513 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001514 PD->protocol_begin(),
1515 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001516 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001517 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1518 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001519 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1520 InstanceMethods);
1521 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001522 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1523 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001524 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1525 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001526 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1527 Values);
1528
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001529 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001530 // Already created, fix the linkage and update the initializer.
1531 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001532 Entry->setInitializer(Init);
1533 } else {
1534 Entry =
1535 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1536 llvm::GlobalValue::InternalLinkage,
1537 Init,
1538 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1539 &CGM.getModule());
1540 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001541 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001542 UsedGlobals.push_back(Entry);
1543 // FIXME: Is this necessary? Why only for protocol?
1544 Entry->setAlignment(4);
1545 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001546
1547 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001548}
1549
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001550llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001551 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1552
1553 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001554 // We use the initializer as a marker of whether this is a forward
1555 // reference or not. At module finalization we add the empty
1556 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001557 Entry =
1558 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001559 llvm::GlobalValue::ExternalLinkage,
1560 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001561 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001562 &CGM.getModule());
1563 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001564 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001565 UsedGlobals.push_back(Entry);
1566 // FIXME: Is this necessary? Why only for protocol?
1567 Entry->setAlignment(4);
1568 }
1569
1570 return Entry;
1571}
1572
1573/*
1574 struct _objc_protocol_extension {
1575 uint32_t size;
1576 struct objc_method_description_list *optional_instance_methods;
1577 struct objc_method_description_list *optional_class_methods;
1578 struct objc_property_list *instance_properties;
1579 };
1580*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001581llvm::Constant *
1582CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1583 const ConstantVector &OptInstanceMethods,
1584 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001585 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001586 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001587 std::vector<llvm::Constant*> Values(4);
1588 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001589 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001590 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1591 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001592 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1593 OptInstanceMethods);
1594 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001595 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1596 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001597 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1598 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001599 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1600 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001601 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001602
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001603 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001604 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1605 Values[3]->isNullValue())
1606 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1607
1608 llvm::Constant *Init =
1609 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001610
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001611 // No special section, but goes in llvm.used
1612 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1613 Init,
1614 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001615}
1616
1617/*
1618 struct objc_protocol_list {
1619 struct objc_protocol_list *next;
1620 long count;
1621 Protocol *list[];
1622 };
1623*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001624llvm::Constant *
1625CGObjCMac::EmitProtocolList(const std::string &Name,
1626 ObjCProtocolDecl::protocol_iterator begin,
1627 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001628 std::vector<llvm::Constant*> ProtocolRefs;
1629
Daniel Dunbardbc933702008-08-21 21:57:41 +00001630 for (; begin != end; ++begin)
1631 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001632
1633 // Just return null for empty protocol lists
1634 if (ProtocolRefs.empty())
1635 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1636
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001637 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001638 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1639
1640 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001641 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001642 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1643 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1644 Values[2] =
1645 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1646 ProtocolRefs.size()),
1647 ProtocolRefs);
1648
1649 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1650 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001651 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001652 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001653 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1654}
1655
1656/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001657 struct _objc_property {
1658 const char * const name;
1659 const char * const attributes;
1660 };
1661
1662 struct _objc_property_list {
1663 uint32_t entsize; // sizeof (struct _objc_property)
1664 uint32_t prop_count;
1665 struct _objc_property[prop_count];
1666 };
1667*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001668llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1669 const Decl *Container,
1670 const ObjCContainerDecl *OCD,
1671 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001672 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001673 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1674 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001675 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001676 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001677 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001678 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1679 Prop));
1680 }
1681
1682 // Return null for empty list.
1683 if (Properties.empty())
1684 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1685
1686 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001687 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001688 std::vector<llvm::Constant*> Values(3);
1689 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1690 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1691 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1692 Properties.size());
1693 Values[2] = llvm::ConstantArray::get(AT, Properties);
1694 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1695
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001696 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001697 CreateMetadataVar(Name, Init,
1698 (ObjCABI == 2) ? "__DATA, __objc_const" :
1699 "__OBJC,__property,regular,no_dead_strip",
1700 (ObjCABI == 2) ? 8 : 4,
1701 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001702 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001703}
1704
1705/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001706 struct objc_method_description_list {
1707 int count;
1708 struct objc_method_description list[];
1709 };
1710*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001711llvm::Constant *
1712CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1713 std::vector<llvm::Constant*> Desc(2);
1714 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1715 ObjCTypes.SelectorPtrTy);
1716 Desc[1] = GetMethodVarType(MD);
1717 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1718 Desc);
1719}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001720
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001721llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1722 const char *Section,
1723 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001724 // Return null for empty list.
1725 if (Methods.empty())
1726 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1727
1728 std::vector<llvm::Constant*> Values(2);
1729 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1730 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1731 Methods.size());
1732 Values[1] = llvm::ConstantArray::get(AT, Methods);
1733 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1734
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001735 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001736 return llvm::ConstantExpr::getBitCast(GV,
1737 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001738}
1739
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001740/*
1741 struct _objc_category {
1742 char *category_name;
1743 char *class_name;
1744 struct _objc_method_list *instance_methods;
1745 struct _objc_method_list *class_methods;
1746 struct _objc_protocol_list *protocols;
1747 uint32_t size; // <rdar://4585769>
1748 struct _objc_property_list *instance_properties;
1749 };
1750 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001751void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001752 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001753
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001754 // FIXME: This is poor design, the OCD should have a pointer to the
1755 // category decl. Additionally, note that Category can be null for
1756 // the @implementation w/o an @interface case. Sema should just
1757 // create one for us as it does for @implementation so everyone else
1758 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001759 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001760 const ObjCCategoryDecl *Category =
1761 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001762 std::string ExtName(Interface->getNameAsString() + "_" +
1763 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001764
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001765 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001766 for (ObjCCategoryImplDecl::instmeth_iterator
1767 i = OCD->instmeth_begin(CGM.getContext()),
1768 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001769 // Instance methods should always be defined.
1770 InstanceMethods.push_back(GetMethodConstant(*i));
1771 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001772 for (ObjCCategoryImplDecl::classmeth_iterator
1773 i = OCD->classmeth_begin(CGM.getContext()),
1774 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001775 // Class methods should always be defined.
1776 ClassMethods.push_back(GetMethodConstant(*i));
1777 }
1778
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001779 std::vector<llvm::Constant*> Values(7);
1780 Values[0] = GetClassName(OCD->getIdentifier());
1781 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001782 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001783 Values[2] =
1784 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1785 ExtName,
1786 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001787 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001788 Values[3] =
1789 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001790 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001791 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001792 if (Category) {
1793 Values[4] =
1794 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1795 Category->protocol_begin(),
1796 Category->protocol_end());
1797 } else {
1798 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1799 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001800 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001801
1802 // If there is no category @interface then there can be no properties.
1803 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001804 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001805 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001806 } else {
1807 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1808 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001809
1810 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1811 Values);
1812
1813 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001814 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1815 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001816 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001817 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001818}
1819
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001820// FIXME: Get from somewhere?
1821enum ClassFlags {
1822 eClassFlags_Factory = 0x00001,
1823 eClassFlags_Meta = 0x00002,
1824 // <rdr://5142207>
1825 eClassFlags_HasCXXStructors = 0x02000,
1826 eClassFlags_Hidden = 0x20000,
1827 eClassFlags_ABI2_Hidden = 0x00010,
1828 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1829};
1830
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001831/*
1832 struct _objc_class {
1833 Class isa;
1834 Class super_class;
1835 const char *name;
1836 long version;
1837 long info;
1838 long instance_size;
1839 struct _objc_ivar_list *ivars;
1840 struct _objc_method_list *methods;
1841 struct _objc_cache *cache;
1842 struct _objc_protocol_list *protocols;
1843 // Objective-C 1.0 extensions (<rdr://4585769>)
1844 const char *ivar_layout;
1845 struct _objc_class_ext *ext;
1846 };
1847
1848 See EmitClassExtension();
1849 */
1850void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001851 DefinedSymbols.insert(ID->getIdentifier());
1852
Chris Lattner8ec03f52008-11-24 03:54:41 +00001853 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001854 // FIXME: Gross
1855 ObjCInterfaceDecl *Interface =
1856 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001857 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001858 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001859 Interface->protocol_begin(),
1860 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001861 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001862 unsigned Size =
1863 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001864
1865 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001866 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001867 Flags |= eClassFlags_Hidden;
1868
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001869 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001870 for (ObjCImplementationDecl::instmeth_iterator
1871 i = ID->instmeth_begin(CGM.getContext()),
1872 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001873 // Instance methods should always be defined.
1874 InstanceMethods.push_back(GetMethodConstant(*i));
1875 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001876 for (ObjCImplementationDecl::classmeth_iterator
1877 i = ID->classmeth_begin(CGM.getContext()),
1878 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001879 // Class methods should always be defined.
1880 ClassMethods.push_back(GetMethodConstant(*i));
1881 }
1882
Douglas Gregor653f1b12009-04-23 01:02:12 +00001883 for (ObjCImplementationDecl::propimpl_iterator
1884 i = ID->propimpl_begin(CGM.getContext()),
1885 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001886 ObjCPropertyImplDecl *PID = *i;
1887
1888 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1889 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1890
1891 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1892 if (llvm::Constant *C = GetMethodConstant(MD))
1893 InstanceMethods.push_back(C);
1894 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1895 if (llvm::Constant *C = GetMethodConstant(MD))
1896 InstanceMethods.push_back(C);
1897 }
1898 }
1899
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001900 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00001901 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001902 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001903 // Record a reference to the super class.
1904 LazySymbols.insert(Super->getIdentifier());
1905
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001906 Values[ 1] =
1907 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1908 ObjCTypes.ClassPtrTy);
1909 } else {
1910 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1911 }
1912 Values[ 2] = GetClassName(ID->getIdentifier());
1913 // Version is always 0.
1914 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1915 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1916 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001917 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001918 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001919 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001920 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001921 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001922 // cache is always NULL.
1923 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1924 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001925 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001926 Values[11] = EmitClassExtension(ID);
1927 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1928 Values);
1929
1930 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001931 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1932 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001933 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001934 DefinedClasses.push_back(GV);
1935}
1936
1937llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1938 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001939 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001940 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001941 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001942
Daniel Dunbar04d40782009-04-14 06:00:08 +00001943 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001944 Flags |= eClassFlags_Hidden;
1945
1946 std::vector<llvm::Constant*> Values(12);
1947 // The isa for the metaclass is the root of the hierarchy.
1948 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1949 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1950 Root = Super;
1951 Values[ 0] =
1952 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1953 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001954 // The super class for the metaclass is emitted as the name of the
1955 // super class. The runtime fixes this up to point to the
1956 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001957 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1958 Values[ 1] =
1959 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1960 ObjCTypes.ClassPtrTy);
1961 } else {
1962 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1963 }
1964 Values[ 2] = GetClassName(ID->getIdentifier());
1965 // Version is always 0.
1966 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1967 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1968 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001969 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001970 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001971 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001972 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001973 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001974 // cache is always NULL.
1975 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1976 Values[ 9] = Protocols;
1977 // ivar_layout for metaclass is always NULL.
1978 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1979 // The class extension is always unused for metaclasses.
1980 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1981 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1982 Values);
1983
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001984 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001985 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001986
1987 // Check for a forward reference.
1988 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1989 if (GV) {
1990 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1991 "Forward metaclass reference has incorrect type.");
1992 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1993 GV->setInitializer(Init);
1994 } else {
1995 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1996 llvm::GlobalValue::InternalLinkage,
1997 Init, Name,
1998 &CGM.getModule());
1999 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002001 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002002 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002003
2004 return GV;
2005}
2006
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002007llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002008 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002009
2010 // FIXME: Should we look these up somewhere other than the
2011 // module. Its a bit silly since we only generate these while
2012 // processing an implementation, so exactly one pointer would work
2013 // if know when we entered/exitted an implementation block.
2014
2015 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002016 // Previously, metaclass with internal linkage may have been defined.
2017 // pass 'true' as 2nd argument so it is returned.
2018 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002019 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2020 "Forward metaclass reference has incorrect type.");
2021 return GV;
2022 } else {
2023 // Generate as an external reference to keep a consistent
2024 // module. This will be patched up when we emit the metaclass.
2025 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2026 llvm::GlobalValue::ExternalLinkage,
2027 0,
2028 Name,
2029 &CGM.getModule());
2030 }
2031}
2032
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002033/*
2034 struct objc_class_ext {
2035 uint32_t size;
2036 const char *weak_ivar_layout;
2037 struct _objc_property_list *properties;
2038 };
2039*/
2040llvm::Constant *
2041CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2042 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002043 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002044
2045 std::vector<llvm::Constant*> Values(3);
2046 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002047 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002048 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002049 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002050
2051 // Return null if no extension bits are used.
2052 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2053 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2054
2055 llvm::Constant *Init =
2056 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002057 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002058 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2059 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002060}
2061
2062/*
2063 struct objc_ivar {
2064 char *ivar_name;
2065 char *ivar_type;
2066 int ivar_offset;
2067 };
2068
2069 struct objc_ivar_list {
2070 int ivar_count;
2071 struct objc_ivar list[count];
2072 };
2073 */
2074llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002075 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002076 std::vector<llvm::Constant*> Ivars, Ivar(3);
2077
2078 // When emitting the root class GCC emits ivar entries for the
2079 // actual class structure. It is not clear if we need to follow this
2080 // behavior; for now lets try and get away with not doing it. If so,
2081 // the cleanest solution would be to make up an ObjCInterfaceDecl
2082 // for the class.
2083 if (ForClass)
2084 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002085
2086 ObjCInterfaceDecl *OID =
2087 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002088
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002089 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2090 GetNamedIvarList(OID, OIvars);
2091
2092 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2093 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002094 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2095 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002096 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002097 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002098 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002099 }
2100
2101 // Return null for empty list.
2102 if (Ivars.empty())
2103 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2104
2105 std::vector<llvm::Constant*> Values(2);
2106 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2107 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2108 Ivars.size());
2109 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2110 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2111
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002112 llvm::GlobalVariable *GV;
2113 if (ForClass)
2114 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002115 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2116 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002117 else
2118 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2119 + ID->getNameAsString(),
2120 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002121 4, true);
2122 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002123}
2124
2125/*
2126 struct objc_method {
2127 SEL method_name;
2128 char *method_types;
2129 void *method;
2130 };
2131
2132 struct objc_method_list {
2133 struct objc_method_list *obsolete;
2134 int count;
2135 struct objc_method methods_list[count];
2136 };
2137*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002138
2139/// GetMethodConstant - Return a struct objc_method constant for the
2140/// given method if it has been defined. The result is null if the
2141/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002142llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002143 // FIXME: Use DenseMap::lookup
2144 llvm::Function *Fn = MethodDefinitions[MD];
2145 if (!Fn)
2146 return 0;
2147
2148 std::vector<llvm::Constant*> Method(3);
2149 Method[0] =
2150 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2151 ObjCTypes.SelectorPtrTy);
2152 Method[1] = GetMethodVarType(MD);
2153 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2154 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2155}
2156
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002157llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2158 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002159 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002160 // Return null for empty list.
2161 if (Methods.empty())
2162 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2163
2164 std::vector<llvm::Constant*> Values(3);
2165 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2166 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2167 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2168 Methods.size());
2169 Values[2] = llvm::ConstantArray::get(AT, Methods);
2170 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2171
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002172 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002173 return llvm::ConstantExpr::getBitCast(GV,
2174 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002175}
2176
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002177llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002178 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002179 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002180 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002181
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002182 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002183 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002184 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002185 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002186 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002187 llvm::GlobalValue::InternalLinkage,
2188 Name,
2189 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002190 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002191
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002192 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002193}
2194
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002195llvm::GlobalVariable *
2196CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2197 llvm::Constant *Init,
2198 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002199 unsigned Align,
2200 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002201 const llvm::Type *Ty = Init->getType();
2202 llvm::GlobalVariable *GV =
2203 new llvm::GlobalVariable(Ty, false,
2204 llvm::GlobalValue::InternalLinkage,
2205 Init,
2206 Name,
2207 &CGM.getModule());
2208 if (Section)
2209 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002210 if (Align)
2211 GV->setAlignment(Align);
2212 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002213 UsedGlobals.push_back(GV);
2214 return GV;
2215}
2216
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002217llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002218 // Abuse this interface function as a place to finalize.
2219 FinishModule();
2220
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002221 return NULL;
2222}
2223
Chris Lattner74391b42009-03-22 21:03:39 +00002224llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002225 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002226}
2227
Chris Lattner74391b42009-03-22 21:03:39 +00002228llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002229 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002230}
2231
Chris Lattner74391b42009-03-22 21:03:39 +00002232llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002233 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002234}
2235
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002236/*
2237
2238Objective-C setjmp-longjmp (sjlj) Exception Handling
2239--
2240
2241The basic framework for a @try-catch-finally is as follows:
2242{
2243 objc_exception_data d;
2244 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002245 bool _call_try_exit = true;
2246
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002247 objc_exception_try_enter(&d);
2248 if (!setjmp(d.jmp_buf)) {
2249 ... try body ...
2250 } else {
2251 // exception path
2252 id _caught = objc_exception_extract(&d);
2253
2254 // enter new try scope for handlers
2255 if (!setjmp(d.jmp_buf)) {
2256 ... match exception and execute catch blocks ...
2257
2258 // fell off end, rethrow.
2259 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002260 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002261 } else {
2262 // exception in catch block
2263 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002264 _call_try_exit = false;
2265 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002266 }
2267 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002268 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002269
2270finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002271 if (_call_try_exit)
2272 objc_exception_try_exit(&d);
2273
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002274 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002275 ... dispatch to finally destination ...
2276
2277finally_rethrow:
2278 objc_exception_throw(_rethrow);
2279
2280finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002281}
2282
2283This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002284uses _rethrow to determine if objc_exception_try_exit should be called
2285and if the object should be rethrown. This breaks in the face of
2286throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002287
2288We specialize this framework for a few particular circumstances:
2289
2290 - If there are no catch blocks, then we avoid emitting the second
2291 exception handling context.
2292
2293 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2294 e)) we avoid emitting the code to rethrow an uncaught exception.
2295
2296 - FIXME: If there is no @finally block we can do a few more
2297 simplifications.
2298
2299Rethrows and Jumps-Through-Finally
2300--
2301
2302Support for implicit rethrows and jumping through the finally block is
2303handled by storing the current exception-handling context in
2304ObjCEHStack.
2305
Daniel Dunbar898d5082008-09-30 01:06:03 +00002306In order to implement proper @finally semantics, we support one basic
2307mechanism for jumping through the finally block to an arbitrary
2308destination. Constructs which generate exits from a @try or @catch
2309block use this mechanism to implement the proper semantics by chaining
2310jumps, as necessary.
2311
2312This mechanism works like the one used for indirect goto: we
2313arbitrarily assign an ID to each destination and store the ID for the
2314destination in a variable prior to entering the finally block. At the
2315end of the finally block we simply create a switch to the proper
2316destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002317
2318Code gen for @synchronized(expr) stmt;
2319Effectively generating code for:
2320objc_sync_enter(expr);
2321@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002322*/
2323
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002324void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2325 const Stmt &S) {
2326 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002327 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002328 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002329 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002330 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2331 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2332 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002333
2334 // For @synchronized, call objc_sync_enter(sync.expr). The
2335 // evaluation of the expression must occur before we enter the
2336 // @synchronized. We can safely avoid a temp here because jumps into
2337 // @synchronized are illegal & this will dominate uses.
2338 llvm::Value *SyncArg = 0;
2339 if (!isTry) {
2340 SyncArg =
2341 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2342 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002343 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002344 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002345
2346 // Push an EH context entry, used for handling rethrows and jumps
2347 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002348 CGF.PushCleanupBlock(FinallyBlock);
2349
Anders Carlsson273558f2009-02-07 21:37:21 +00002350 CGF.ObjCEHValueStack.push_back(0);
2351
Daniel Dunbar898d5082008-09-30 01:06:03 +00002352 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002353 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2354 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002355 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2356 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002357 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2358 "_call_try_exit");
2359 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2360
Anders Carlsson80f25672008-09-09 17:59:25 +00002361 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002362 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002363 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2364 "jmpbufarray");
2365 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002366 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002367 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002368
Daniel Dunbar55e87422008-11-11 02:29:29 +00002369 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2370 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002371 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002372 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002373
2374 // Emit the @try block.
2375 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002376 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2377 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002378 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002379
2380 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002381 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002382
2383 // Retrieve the exception object. We may emit multiple blocks but
2384 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002385 llvm::Value *Caught =
2386 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2387 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002388 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002389 if (!isTry)
2390 {
2391 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002392 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002393 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002394 }
2395 else if (const ObjCAtCatchStmt* CatchStmt =
2396 cast<ObjCAtTryStmt>(S).getCatchStmts())
2397 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002398 // Enter a new exception try block (in case a @catch block throws
2399 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002400 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002401
Chris Lattner34b02a12009-04-22 02:26:14 +00002402 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002403 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002404 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002405
Daniel Dunbar55e87422008-11-11 02:29:29 +00002406 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2407 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002408 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002409
2410 CGF.EmitBlock(CatchBlock);
2411
Daniel Dunbar55e40722008-09-27 07:03:52 +00002412 // Handle catch list. As a special case we check if everything is
2413 // matched and avoid generating code for falling off the end if
2414 // so.
2415 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002416 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002417 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002418
Steve Naroff7ba138a2009-03-03 19:52:17 +00002419 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002420 const PointerType *PT = 0;
2421
Anders Carlsson80f25672008-09-09 17:59:25 +00002422 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002423 if (!CatchParam) {
2424 AllMatched = true;
2425 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002426 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002427
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002428 // catch(id e) always matches.
2429 // FIXME: For the time being we also match id<X>; this should
2430 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002431 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002432 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002433 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002434 }
2435
Daniel Dunbar55e40722008-09-27 07:03:52 +00002436 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002437 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002438 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002439 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002440 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002441 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002442
Anders Carlssondde0a942008-09-11 09:15:33 +00002443 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002444 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002445 break;
2446 }
2447
Daniel Dunbar129271a2008-09-27 07:36:24 +00002448 assert(PT && "Unexpected non-pointer type in @catch");
2449 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002450 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002451 assert(ObjCType && "Catch parameter must have Objective-C type!");
2452
2453 // Check if the @catch block matches the exception object.
2454 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2455
Chris Lattner34b02a12009-04-22 02:26:14 +00002456 llvm::Value *Match =
2457 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2458 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002459
Daniel Dunbar55e87422008-11-11 02:29:29 +00002460 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002461
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002462 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002463 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002464
2465 // Emit the @catch block.
2466 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002467 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002468 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002469
2470 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002471 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002472 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002473 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002474
2475 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002476 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002477
2478 CGF.EmitBlock(NextCatchBlock);
2479 }
2480
Daniel Dunbar55e40722008-09-27 07:03:52 +00002481 if (!AllMatched) {
2482 // None of the handlers caught the exception, so store it to be
2483 // rethrown at the end of the @finally block.
2484 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002485 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002486 }
2487
2488 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002489 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002490 CGF.Builder.CreateStore(
2491 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2492 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002493 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002494 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002495 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002496 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002497 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002498 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002499 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002500 }
2501
Daniel Dunbar898d5082008-09-30 01:06:03 +00002502 // Pop the exception-handling stack entry. It is important to do
2503 // this now, because the code in the @finally block is not in this
2504 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002505 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2506
Anders Carlsson273558f2009-02-07 21:37:21 +00002507 CGF.ObjCEHValueStack.pop_back();
2508
Anders Carlsson80f25672008-09-09 17:59:25 +00002509 // Emit the @finally block.
2510 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002511 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2512
2513 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2514
2515 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002516 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002517
2518 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002519 if (isTry) {
2520 if (const ObjCAtFinallyStmt* FinallyStmt =
2521 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2522 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002523 } else {
2524 // Emit objc_sync_exit(expr); as finally's sole statement for
2525 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002526 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002527 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002528
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002529 // Emit the switch block
2530 if (Info.SwitchBlock)
2531 CGF.EmitBlock(Info.SwitchBlock);
2532 if (Info.EndBlock)
2533 CGF.EmitBlock(Info.EndBlock);
2534
Daniel Dunbar898d5082008-09-30 01:06:03 +00002535 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002536 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002537 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002538 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002539
2540 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002541}
2542
2543void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002544 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002545 llvm::Value *ExceptionAsObject;
2546
2547 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2548 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2549 ExceptionAsObject =
2550 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2551 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002552 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002553 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002554 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002555 }
2556
Chris Lattnerbbccd612009-04-22 02:38:11 +00002557 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002558 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002559
2560 // Clear the insertion point to indicate we are in unreachable code.
2561 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002562}
2563
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002564/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002565/// object: objc_read_weak (id *src)
2566///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002567llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002568 llvm::Value *AddrWeakObj)
2569{
Eli Friedman8339b352009-03-07 03:57:15 +00002570 const llvm::Type* DestTy =
2571 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002572 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002573 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002574 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002575 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002576 return read_weak;
2577}
2578
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002579/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2580/// objc_assign_weak (id src, id *dst)
2581///
2582void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2583 llvm::Value *src, llvm::Value *dst)
2584{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002585 const llvm::Type * SrcTy = src->getType();
2586 if (!isa<llvm::PointerType>(SrcTy)) {
2587 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2588 assert(Size <= 8 && "does not support size > 8");
2589 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2590 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002591 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2592 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002593 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2594 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002595 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002596 src, dst, "weakassign");
2597 return;
2598}
2599
Fariborz Jahanian58626502008-11-19 00:59:10 +00002600/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2601/// objc_assign_global (id src, id *dst)
2602///
2603void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2604 llvm::Value *src, llvm::Value *dst)
2605{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002606 const llvm::Type * SrcTy = src->getType();
2607 if (!isa<llvm::PointerType>(SrcTy)) {
2608 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2609 assert(Size <= 8 && "does not support size > 8");
2610 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2611 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002612 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2613 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002614 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2615 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002616 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002617 src, dst, "globalassign");
2618 return;
2619}
2620
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002621/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2622/// objc_assign_ivar (id src, id *dst)
2623///
2624void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2625 llvm::Value *src, llvm::Value *dst)
2626{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002627 const llvm::Type * SrcTy = src->getType();
2628 if (!isa<llvm::PointerType>(SrcTy)) {
2629 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2630 assert(Size <= 8 && "does not support size > 8");
2631 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2632 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002633 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2634 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002635 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2636 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002637 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002638 src, dst, "assignivar");
2639 return;
2640}
2641
Fariborz Jahanian58626502008-11-19 00:59:10 +00002642/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2643/// objc_assign_strongCast (id src, id *dst)
2644///
2645void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2646 llvm::Value *src, llvm::Value *dst)
2647{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002648 const llvm::Type * SrcTy = src->getType();
2649 if (!isa<llvm::PointerType>(SrcTy)) {
2650 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2651 assert(Size <= 8 && "does not support size > 8");
2652 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2653 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002654 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2655 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002656 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2657 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002658 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002659 src, dst, "weakassign");
2660 return;
2661}
2662
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002663/// EmitObjCValueForIvar - Code Gen for ivar reference.
2664///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002665LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2666 QualType ObjectTy,
2667 llvm::Value *BaseValue,
2668 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002669 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002670 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002671 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2672 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002673}
2674
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002675llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002676 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002677 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002678 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002679 return llvm::ConstantInt::get(
2680 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2681 Offset);
2682}
2683
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002684/* *** Private Interface *** */
2685
2686/// EmitImageInfo - Emit the image info marker used to encode some module
2687/// level information.
2688///
2689/// See: <rdr://4810609&4810587&4810587>
2690/// struct IMAGE_INFO {
2691/// unsigned version;
2692/// unsigned flags;
2693/// };
2694enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002695 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2696 // this implies.
2697 eImageInfo_GarbageCollected = (1 << 1),
2698 eImageInfo_GCOnly = (1 << 2),
2699 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2700
2701 // A flag indicating that the module has no instances of an
2702 // @synthesize of a superclass variable. <rdar://problem/6803242>
2703 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002704};
2705
2706void CGObjCMac::EmitImageInfo() {
2707 unsigned version = 0; // Version is unused?
2708 unsigned flags = 0;
2709
2710 // FIXME: Fix and continue?
2711 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2712 flags |= eImageInfo_GarbageCollected;
2713 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2714 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002715
2716 // We never allow @synthesize of a superclass property.
2717 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002718
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002719 // Emitted as int[2];
2720 llvm::Constant *values[2] = {
2721 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2722 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2723 };
2724 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002725
2726 const char *Section;
2727 if (ObjCABI == 1)
2728 Section = "__OBJC, __image_info,regular";
2729 else
2730 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002731 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002732 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2733 llvm::ConstantArray::get(AT, values, 2),
2734 Section,
2735 0,
2736 true);
2737 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002738}
2739
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002740
2741// struct objc_module {
2742// unsigned long version;
2743// unsigned long size;
2744// const char *name;
2745// Symtab symtab;
2746// };
2747
2748// FIXME: Get from somewhere
2749static const int ModuleVersion = 7;
2750
2751void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002752 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002753
2754 std::vector<llvm::Constant*> Values(4);
2755 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2756 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002757 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002758 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002759 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002760 CreateMetadataVar("\01L_OBJC_MODULES",
2761 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2762 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002763 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002764}
2765
2766llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002767 unsigned NumClasses = DefinedClasses.size();
2768 unsigned NumCategories = DefinedCategories.size();
2769
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002770 // Return null if no symbols were defined.
2771 if (!NumClasses && !NumCategories)
2772 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2773
2774 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002775 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2776 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2777 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2778 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2779
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002780 // The runtime expects exactly the list of defined classes followed
2781 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002782 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002783 for (unsigned i=0; i<NumClasses; i++)
2784 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2785 ObjCTypes.Int8PtrTy);
2786 for (unsigned i=0; i<NumCategories; i++)
2787 Symbols[NumClasses + i] =
2788 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2789 ObjCTypes.Int8PtrTy);
2790
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002791 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002792 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002793 NumClasses + NumCategories),
2794 Symbols);
2795
2796 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2797
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002798 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002799 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2800 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002801 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002802 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2803}
2804
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002805llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002806 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002807 LazySymbols.insert(ID->getIdentifier());
2808
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002809 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2810
2811 if (!Entry) {
2812 llvm::Constant *Casted =
2813 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2814 ObjCTypes.ClassPtrTy);
2815 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002816 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2817 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002818 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002819 }
2820
2821 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002822}
2823
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002824llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002825 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2826
2827 if (!Entry) {
2828 llvm::Constant *Casted =
2829 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2830 ObjCTypes.SelectorPtrTy);
2831 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002832 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2833 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002834 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002835 }
2836
2837 return Builder.CreateLoad(Entry, false, "tmp");
2838}
2839
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002840llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002841 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002842
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002843 if (!Entry)
2844 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2845 llvm::ConstantArray::get(Ident->getName()),
2846 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002847 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002848
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002849 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002850}
2851
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002852/// GetIvarLayoutName - Returns a unique constant for the given
2853/// ivar layout bitmap.
2854llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2855 const ObjCCommonTypesHelper &ObjCTypes) {
2856 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2857}
2858
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002859static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2860 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002861 if (FQT.isObjCGCStrong())
2862 return QualType::Strong;
2863
2864 if (FQT.isObjCGCWeak())
2865 return QualType::Weak;
2866
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002867 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002868 return QualType::Strong;
2869
2870 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002871 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002872
2873 return QualType::GCNone;
2874}
2875
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002876void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2877 unsigned int BytePos,
2878 bool ForStrongLayout,
2879 bool &HasUnion) {
2880 const RecordDecl *RD = RT->getDecl();
2881 // FIXME - Use iterator.
2882 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2883 RD->field_end(CGM.getContext()));
2884 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2885 const llvm::StructLayout *RecLayout =
2886 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2887
2888 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2889 ForStrongLayout, HasUnion);
2890}
2891
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002892void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002893 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002894 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002895 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002896 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002897 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002898 bool IsUnion = (RD && RD->isUnion());
2899 uint64_t MaxUnionIvarSize = 0;
2900 uint64_t MaxSkippedUnionIvarSize = 0;
2901 FieldDecl *MaxField = 0;
2902 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002903 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00002904 uint64_t MaxFieldOffset = 0;
2905 uint64_t MaxSkippedFieldOffset = 0;
2906 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002907
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002908 if (RecFields.empty())
2909 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00002910 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2911 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2912
Chris Lattnerf1690852009-03-31 08:48:01 +00002913 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002914 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00002915 uint64_t FieldOffset;
2916 if (RD)
2917 FieldOffset =
2918 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2919 else
2920 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002921
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002922 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002923 if (!Field->getIdentifier() || Field->isBitField()) {
2924 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00002925 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002926 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002927 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002928
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002929 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002930 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002931 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002932 if (FQT->isUnionType())
2933 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002934
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002935 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002936 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002937 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002938 continue;
2939 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002940
2941 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002942 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002943 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002944 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002945 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002946 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002947 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2948 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002949 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002950 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002951 FQT = CArray->getElementType();
2952 }
2953
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002954 assert(!FQT->isUnionType() &&
2955 "layout for array of unions not supported");
2956 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002957 int OldIndex = IvarsInfo.size() - 1;
2958 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002959
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002960 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002961 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002962 ForStrongLayout, HasUnion);
2963
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002964 // Replicate layout information for each array element. Note that
2965 // one element is already done.
2966 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002967 for (int FirstIndex = IvarsInfo.size() - 1,
2968 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002969 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00002970 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2971 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
2972 IvarsInfo[i].ivar_size));
2973 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
2974 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
2975 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002976 }
2977 continue;
2978 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002979 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002980 // At this point, we are done with Record/Union and array there of.
2981 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002982 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002983
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00002984 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002985 if ((ForStrongLayout && GCAttr == QualType::Strong)
2986 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00002987 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00002988 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00002989 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002990 MaxUnionIvarSize = UnionIvarSize;
2991 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00002992 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002993 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00002994 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002995 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00002996 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002997 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00002998 } else if ((ForStrongLayout &&
2999 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3000 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3001 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003002 // FIXME: Why the asymmetry? We divide by word size in bits on
3003 // other side.
3004 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003005 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003006 MaxSkippedUnionIvarSize = UnionIvarSize;
3007 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003008 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003009 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003010 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003011 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003012 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003013 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003014 }
3015 }
3016 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003017
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003018 if (LastFieldBitfield) {
3019 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003020 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3021 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003022 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003023 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003024 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003025 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3026 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003027 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003028 }
3029
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003030 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003031 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003032 MaxUnionIvarSize));
3033 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003034 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003035 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003036}
3037
3038/// BuildIvarLayout - Builds ivar layout bitmap for the class
3039/// implementation for the __strong or __weak case.
3040/// The layout map displays which words in ivar list must be skipped
3041/// and which must be scanned by GC (see below). String is built of bytes.
3042/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3043/// of words to skip and right nibble is count of words to scan. So, each
3044/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3045/// represented by a 0x00 byte which also ends the string.
3046/// 1. when ForStrongLayout is true, following ivars are scanned:
3047/// - id, Class
3048/// - object *
3049/// - __strong anything
3050///
3051/// 2. When ForStrongLayout is false, following ivars are scanned:
3052/// - __weak anything
3053///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003054llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003055 const ObjCImplementationDecl *OMD,
3056 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003057 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003058
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003059 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003060 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3061 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3062 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003063
Chris Lattnerf1690852009-03-31 08:48:01 +00003064 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003065 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003066 CGM.getContext().CollectObjCIvars(OI, RecFields);
Daniel Dunbar37153282009-05-04 04:10:48 +00003067
3068 // Add this implementations synthesized ivars.
3069 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(CGM.getContext()),
3070 E = OI->prop_end(CGM.getContext()); I != E; ++I) {
3071 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
3072 RecFields.push_back(cast<FieldDecl>(IV));
3073 }
3074
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003075 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003076 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003077
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003078 SkipIvars.clear();
3079 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003080
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003081 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003082 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003083 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003084
3085 // Sort on byte position in case we encounterred a union nested in
3086 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003087 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003088 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003089 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003090 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003091
3092 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003093 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003094 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003095 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003096 if (IvarsInfo[0].ivar_bytepos == 0) {
3097 WordsToSkip = 0;
3098 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003099 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003100 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3101 WordsToScan = IvarsInfo[0].ivar_size;
3102 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003103 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003104 unsigned int TailPrevGCObjC =
3105 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003106 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003107 // consecutive 'scanned' object pointers.
3108 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003109 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003110 // Skip over 'gc'able object pointer which lay over each other.
3111 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3112 continue;
3113 // Must skip over 1 or more words. We save current skip/scan values
3114 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003115 SKIP_SCAN SkScan;
3116 SkScan.skip = WordsToSkip;
3117 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003118 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003119
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003120 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003121 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3122 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003123 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003124 WordsToSkip = 0;
3125 WordsToScan = IvarsInfo[i].ivar_size;
3126 }
3127 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003128 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003129 SKIP_SCAN SkScan;
3130 SkScan.skip = WordsToSkip;
3131 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003132 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003133 }
3134
3135 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003136 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003137 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003138 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003139 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3140 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003141 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003142 IvarsInfo[LastIndex].ivar_bytepos +
3143 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003144 BytesSkipped = (LastByteSkipped > LastByteScanned);
3145 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003146 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003147 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003148 SKIP_SCAN SkScan;
3149 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3150 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003151 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003152 }
3153 }
3154 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3155 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003156 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003157 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003158 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3159 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3160 // 0xM0 followed by 0x0N detected.
3161 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3162 for (int j = i+1; j < SkipScan; j++)
3163 SkipScanIvars[j] = SkipScanIvars[j+1];
3164 --SkipScan;
3165 }
3166 }
3167
3168 // Generate the string.
3169 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003170 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003171 unsigned char byte;
3172 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3173 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3174 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3175 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3176
3177 if (skip_small > 0 || skip_big > 0)
3178 BytesSkipped = true;
3179 // first skip big.
3180 for (unsigned int ix = 0; ix < skip_big; ix++)
3181 BitMap += (unsigned char)(0xf0);
3182
3183 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003184 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003185 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003186 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003187 byte |= 0xf;
3188 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003189 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003190 byte |= scan_small;
3191 scan_small = 0;
3192 }
3193 BitMap += byte;
3194 }
3195 // next scan big
3196 for (unsigned int ix = 0; ix < scan_big; ix++)
3197 BitMap += (unsigned char)(0x0f);
3198 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003199 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003200 byte = scan_small;
3201 BitMap += byte;
3202 }
3203 }
3204 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003205 unsigned char zero = 0;
3206 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003207
3208 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3209 printf("\n%s ivar layout for class '%s': ",
3210 ForStrongLayout ? "strong" : "weak",
3211 OMD->getClassInterface()->getNameAsCString());
3212 const unsigned char *s = (unsigned char*)BitMap.c_str();
3213 for (unsigned i = 0; i < BitMap.size(); i++)
3214 if (!(s[i] & 0xf0))
3215 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3216 else
3217 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3218 printf("\n");
3219 }
3220
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003221 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3222 // final layout.
3223 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003224 return llvm::Constant::getNullValue(PtrTy);
3225 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3226 llvm::ConstantArray::get(BitMap.c_str()),
3227 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003228 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003229 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003230}
3231
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003232llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003233 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3234
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003235 // FIXME: Avoid std::string copying.
3236 if (!Entry)
3237 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3238 llvm::ConstantArray::get(Sel.getAsString()),
3239 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003240 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003241
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003242 return getConstantGEP(Entry, 0, 0);
3243}
3244
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003245// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003246llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003247 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3248}
3249
3250// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003251llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003252 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3253}
3254
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003255llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003256 std::string TypeStr;
3257 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3258
3259 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003260
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003261 if (!Entry)
3262 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3263 llvm::ConstantArray::get(TypeStr),
3264 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003265 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003266
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003267 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003268}
3269
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003270llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003271 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003272 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3273 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003274
3275 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3276
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003277 if (!Entry)
3278 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3279 llvm::ConstantArray::get(TypeStr),
3280 "__TEXT,__cstring,cstring_literals",
3281 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003282
3283 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003284}
3285
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003286// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003287llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003288 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3289
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003290 if (!Entry)
3291 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3292 llvm::ConstantArray::get(Ident->getName()),
3293 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003294 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003295
3296 return getConstantGEP(Entry, 0, 0);
3297}
3298
3299// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003300// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003301llvm::Constant *
3302 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3303 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003304 std::string TypeStr;
3305 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003306 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3307}
3308
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003309void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3310 const ObjCContainerDecl *CD,
3311 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003312 NameOut = '\01';
3313 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003314 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003315 assert (CD && "Missing container decl in GetNameForMethod");
3316 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003317 if (const ObjCCategoryImplDecl *CID =
3318 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3319 NameOut += '(';
3320 NameOut += CID->getNameAsString();
3321 NameOut+= ')';
3322 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003323 NameOut += ' ';
3324 NameOut += D->getSelector().getAsString();
3325 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003326}
3327
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003328void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003329 EmitModuleInfo();
3330
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003331 // Emit the dummy bodies for any protocols which were referenced but
3332 // never defined.
3333 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3334 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3335 if (i->second->hasInitializer())
3336 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003337
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003338 std::vector<llvm::Constant*> Values(5);
3339 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3340 Values[1] = GetClassName(i->first);
3341 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3342 Values[3] = Values[4] =
3343 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3344 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3345 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3346 Values));
3347 }
3348
3349 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003350 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003351 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003352 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003353 }
3354
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003355 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003356 llvm::GlobalValue *GV =
3357 new llvm::GlobalVariable(AT, false,
3358 llvm::GlobalValue::AppendingLinkage,
3359 llvm::ConstantArray::get(AT, Used),
3360 "llvm.used",
3361 &CGM.getModule());
3362
3363 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003364
3365 // Add assembler directives to add lazy undefined symbol references
3366 // for classes which are referenced but not defined. This is
3367 // important for correct linker interaction.
3368
3369 // FIXME: Uh, this isn't particularly portable.
3370 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003371
3372 if (!CGM.getModule().getModuleInlineAsm().empty())
3373 s << "\n";
3374
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003375 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3376 e = LazySymbols.end(); i != e; ++i) {
3377 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3378 }
3379 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3380 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003381 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003382 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3383 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003384
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003385 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003386}
3387
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003388CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003389 : CGObjCCommonMac(cgm),
3390 ObjCTypes(cgm)
3391{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003392 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003393 ObjCABI = 2;
3394}
3395
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003396/* *** */
3397
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003398ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3399: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003400{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003401 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3402 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003403
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003404 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003405 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003406 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003407 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003408 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3409
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003410 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003411 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003412 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003413
3414 // FIXME: It would be nice to unify this with the opaque type, so
3415 // that the IR comes out a bit cleaner.
3416 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3417 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003418
3419 // I'm not sure I like this. The implicit coordination is a bit
3420 // gross. We should solve this in a reasonable fashion because this
3421 // is a pretty common task (match some runtime data structure with
3422 // an LLVM data structure).
3423
3424 // FIXME: This is leaked.
3425 // FIXME: Merge with rewriter code?
3426
3427 // struct _objc_super {
3428 // id self;
3429 // Class cls;
3430 // }
3431 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3432 SourceLocation(),
3433 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003434 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3435 Ctx.getObjCIdType(), 0, false));
3436 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3437 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003438 RD->completeDefinition(Ctx);
3439
3440 SuperCTy = Ctx.getTagDeclType(RD);
3441 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3442
3443 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003444 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3445
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003446 // struct _prop_t {
3447 // char *name;
3448 // char *attributes;
3449 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003450 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003451 CGM.getModule().addTypeName("struct._prop_t",
3452 PropertyTy);
3453
3454 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003455 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003456 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003457 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003458 // }
3459 PropertyListTy = llvm::StructType::get(IntTy,
3460 IntTy,
3461 llvm::ArrayType::get(PropertyTy, 0),
3462 NULL);
3463 CGM.getModule().addTypeName("struct._prop_list_t",
3464 PropertyListTy);
3465 // struct _prop_list_t *
3466 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3467
3468 // struct _objc_method {
3469 // SEL _cmd;
3470 // char *method_type;
3471 // char *_imp;
3472 // }
3473 MethodTy = llvm::StructType::get(SelectorPtrTy,
3474 Int8PtrTy,
3475 Int8PtrTy,
3476 NULL);
3477 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003478
3479 // struct _objc_cache *
3480 CacheTy = llvm::OpaqueType::get();
3481 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3482 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003483}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003484
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003485ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3486 : ObjCCommonTypesHelper(cgm)
3487{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003488 // struct _objc_method_description {
3489 // SEL name;
3490 // char *types;
3491 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003492 MethodDescriptionTy =
3493 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003494 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003495 NULL);
3496 CGM.getModule().addTypeName("struct._objc_method_description",
3497 MethodDescriptionTy);
3498
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003499 // struct _objc_method_description_list {
3500 // int count;
3501 // struct _objc_method_description[1];
3502 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003503 MethodDescriptionListTy =
3504 llvm::StructType::get(IntTy,
3505 llvm::ArrayType::get(MethodDescriptionTy, 0),
3506 NULL);
3507 CGM.getModule().addTypeName("struct._objc_method_description_list",
3508 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003509
3510 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003511 MethodDescriptionListPtrTy =
3512 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3513
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003514 // Protocol description structures
3515
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003516 // struct _objc_protocol_extension {
3517 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3518 // struct _objc_method_description_list *optional_instance_methods;
3519 // struct _objc_method_description_list *optional_class_methods;
3520 // struct _objc_property_list *instance_properties;
3521 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003522 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003523 llvm::StructType::get(IntTy,
3524 MethodDescriptionListPtrTy,
3525 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003526 PropertyListPtrTy,
3527 NULL);
3528 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3529 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003530
3531 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003532 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3533
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003534 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003535
3536 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3537 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3538
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003539 const llvm::Type *T =
3540 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3541 LongTy,
3542 llvm::ArrayType::get(ProtocolTyHolder, 0),
3543 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003544 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3545
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003546 // struct _objc_protocol {
3547 // struct _objc_protocol_extension *isa;
3548 // char *protocol_name;
3549 // struct _objc_protocol **_objc_protocol_list;
3550 // struct _objc_method_description_list *instance_methods;
3551 // struct _objc_method_description_list *class_methods;
3552 // }
3553 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003554 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003555 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3556 MethodDescriptionListPtrTy,
3557 MethodDescriptionListPtrTy,
3558 NULL);
3559 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3560
3561 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3562 CGM.getModule().addTypeName("struct._objc_protocol_list",
3563 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003564 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003565 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3566
3567 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003568 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003569 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003570
3571 // Class description structures
3572
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003573 // struct _objc_ivar {
3574 // char *ivar_name;
3575 // char *ivar_type;
3576 // int ivar_offset;
3577 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003578 IvarTy = llvm::StructType::get(Int8PtrTy,
3579 Int8PtrTy,
3580 IntTy,
3581 NULL);
3582 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3583
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003584 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003585 IvarListTy = llvm::OpaqueType::get();
3586 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3587 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3588
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003589 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003590 MethodListTy = llvm::OpaqueType::get();
3591 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3592 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3593
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003594 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003595 ClassExtensionTy =
3596 llvm::StructType::get(IntTy,
3597 Int8PtrTy,
3598 PropertyListPtrTy,
3599 NULL);
3600 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3601 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3602
3603 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3604
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003605 // struct _objc_class {
3606 // Class isa;
3607 // Class super_class;
3608 // char *name;
3609 // long version;
3610 // long info;
3611 // long instance_size;
3612 // struct _objc_ivar_list *ivars;
3613 // struct _objc_method_list *methods;
3614 // struct _objc_cache *cache;
3615 // struct _objc_protocol_list *protocols;
3616 // char *ivar_layout;
3617 // struct _objc_class_ext *ext;
3618 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003619 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3620 llvm::PointerType::getUnqual(ClassTyHolder),
3621 Int8PtrTy,
3622 LongTy,
3623 LongTy,
3624 LongTy,
3625 IvarListPtrTy,
3626 MethodListPtrTy,
3627 CachePtrTy,
3628 ProtocolListPtrTy,
3629 Int8PtrTy,
3630 ClassExtensionPtrTy,
3631 NULL);
3632 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3633
3634 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3635 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3636 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3637
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003638 // struct _objc_category {
3639 // char *category_name;
3640 // char *class_name;
3641 // struct _objc_method_list *instance_method;
3642 // struct _objc_method_list *class_method;
3643 // uint32_t size; // sizeof(struct _objc_category)
3644 // struct _objc_property_list *instance_properties;// category's @property
3645 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003646 CategoryTy = llvm::StructType::get(Int8PtrTy,
3647 Int8PtrTy,
3648 MethodListPtrTy,
3649 MethodListPtrTy,
3650 ProtocolListPtrTy,
3651 IntTy,
3652 PropertyListPtrTy,
3653 NULL);
3654 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3655
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003656 // Global metadata structures
3657
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003658 // struct _objc_symtab {
3659 // long sel_ref_cnt;
3660 // SEL *refs;
3661 // short cls_def_cnt;
3662 // short cat_def_cnt;
3663 // char *defs[cls_def_cnt + cat_def_cnt];
3664 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003665 SymtabTy = llvm::StructType::get(LongTy,
3666 SelectorPtrTy,
3667 ShortTy,
3668 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003669 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003670 NULL);
3671 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3672 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3673
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003674 // struct _objc_module {
3675 // long version;
3676 // long size; // sizeof(struct _objc_module)
3677 // char *name;
3678 // struct _objc_symtab* symtab;
3679 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003680 ModuleTy =
3681 llvm::StructType::get(LongTy,
3682 LongTy,
3683 Int8PtrTy,
3684 SymtabPtrTy,
3685 NULL);
3686 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003687
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003688
Anders Carlsson124526b2008-09-09 10:10:21 +00003689 // FIXME: This is the size of the setjmp buffer and should be
3690 // target specific. 18 is what's used on 32-bit X86.
3691 uint64_t SetJmpBufferSize = 18;
3692
3693 // Exceptions
3694 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003695 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003696
3697 ExceptionDataTy =
3698 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3699 SetJmpBufferSize),
3700 StackPtrTy, NULL);
3701 CGM.getModule().addTypeName("struct._objc_exception_data",
3702 ExceptionDataTy);
3703
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003704}
3705
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003706ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003707: ObjCCommonTypesHelper(cgm)
3708{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003709 // struct _method_list_t {
3710 // uint32_t entsize; // sizeof(struct _objc_method)
3711 // uint32_t method_count;
3712 // struct _objc_method method_list[method_count];
3713 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003714 MethodListnfABITy = llvm::StructType::get(IntTy,
3715 IntTy,
3716 llvm::ArrayType::get(MethodTy, 0),
3717 NULL);
3718 CGM.getModule().addTypeName("struct.__method_list_t",
3719 MethodListnfABITy);
3720 // struct method_list_t *
3721 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003722
3723 // struct _protocol_t {
3724 // id isa; // NULL
3725 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003726 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003727 // const struct method_list_t * const instance_methods;
3728 // const struct method_list_t * const class_methods;
3729 // const struct method_list_t *optionalInstanceMethods;
3730 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003731 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003732 // const uint32_t size; // sizeof(struct _protocol_t)
3733 // const uint32_t flags; // = 0
3734 // }
3735
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003736 // Holder for struct _protocol_list_t *
3737 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3738
3739 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3740 Int8PtrTy,
3741 llvm::PointerType::getUnqual(
3742 ProtocolListTyHolder),
3743 MethodListnfABIPtrTy,
3744 MethodListnfABIPtrTy,
3745 MethodListnfABIPtrTy,
3746 MethodListnfABIPtrTy,
3747 PropertyListPtrTy,
3748 IntTy,
3749 IntTy,
3750 NULL);
3751 CGM.getModule().addTypeName("struct._protocol_t",
3752 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003753
3754 // struct _protocol_t*
3755 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003756
Fariborz Jahanianda320092009-01-29 19:24:30 +00003757 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003758 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003759 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003760 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003761 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3762 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003763 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003764 NULL);
3765 CGM.getModule().addTypeName("struct._objc_protocol_list",
3766 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003767 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3768 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003769
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003770 // struct _objc_protocol_list*
3771 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003772
3773 // struct _ivar_t {
3774 // unsigned long int *offset; // pointer to ivar offset location
3775 // char *name;
3776 // char *type;
3777 // uint32_t alignment;
3778 // uint32_t size;
3779 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003780 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3781 Int8PtrTy,
3782 Int8PtrTy,
3783 IntTy,
3784 IntTy,
3785 NULL);
3786 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3787
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003788 // struct _ivar_list_t {
3789 // uint32 entsize; // sizeof(struct _ivar_t)
3790 // uint32 count;
3791 // struct _iver_t list[count];
3792 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003793 IvarListnfABITy = llvm::StructType::get(IntTy,
3794 IntTy,
3795 llvm::ArrayType::get(
3796 IvarnfABITy, 0),
3797 NULL);
3798 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3799
3800 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003801
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003802 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003803 // uint32_t const flags;
3804 // uint32_t const instanceStart;
3805 // uint32_t const instanceSize;
3806 // uint32_t const reserved; // only when building for 64bit targets
3807 // const uint8_t * const ivarLayout;
3808 // const char *const name;
3809 // const struct _method_list_t * const baseMethods;
3810 // const struct _objc_protocol_list *const baseProtocols;
3811 // const struct _ivar_list_t *const ivars;
3812 // const uint8_t * const weakIvarLayout;
3813 // const struct _prop_list_t * const properties;
3814 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003815
3816 // FIXME. Add 'reserved' field in 64bit abi mode!
3817 ClassRonfABITy = llvm::StructType::get(IntTy,
3818 IntTy,
3819 IntTy,
3820 Int8PtrTy,
3821 Int8PtrTy,
3822 MethodListnfABIPtrTy,
3823 ProtocolListnfABIPtrTy,
3824 IvarListnfABIPtrTy,
3825 Int8PtrTy,
3826 PropertyListPtrTy,
3827 NULL);
3828 CGM.getModule().addTypeName("struct._class_ro_t",
3829 ClassRonfABITy);
3830
3831 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3832 std::vector<const llvm::Type*> Params;
3833 Params.push_back(ObjectPtrTy);
3834 Params.push_back(SelectorPtrTy);
3835 ImpnfABITy = llvm::PointerType::getUnqual(
3836 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3837
3838 // struct _class_t {
3839 // struct _class_t *isa;
3840 // struct _class_t * const superclass;
3841 // void *cache;
3842 // IMP *vtable;
3843 // struct class_ro_t *ro;
3844 // }
3845
3846 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3847 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3848 llvm::PointerType::getUnqual(ClassTyHolder),
3849 CachePtrTy,
3850 llvm::PointerType::getUnqual(ImpnfABITy),
3851 llvm::PointerType::getUnqual(
3852 ClassRonfABITy),
3853 NULL);
3854 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3855
3856 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3857 ClassnfABITy);
3858
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003859 // LLVM for struct _class_t *
3860 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3861
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003862 // struct _category_t {
3863 // const char * const name;
3864 // struct _class_t *const cls;
3865 // const struct _method_list_t * const instance_methods;
3866 // const struct _method_list_t * const class_methods;
3867 // const struct _protocol_list_t * const protocols;
3868 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003869 // }
3870 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003871 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003872 MethodListnfABIPtrTy,
3873 MethodListnfABIPtrTy,
3874 ProtocolListnfABIPtrTy,
3875 PropertyListPtrTy,
3876 NULL);
3877 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003878
3879 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003880 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3881 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003882
3883 // MessageRefTy - LLVM for:
3884 // struct _message_ref_t {
3885 // IMP messenger;
3886 // SEL name;
3887 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003888
3889 // First the clang type for struct _message_ref_t
3890 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3891 SourceLocation(),
3892 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003893 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3894 Ctx.VoidPtrTy, 0, false));
3895 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3896 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003897 RD->completeDefinition(Ctx);
3898
3899 MessageRefCTy = Ctx.getTagDeclType(RD);
3900 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3901 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003902
3903 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3904 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3905
3906 // SuperMessageRefTy - LLVM for:
3907 // struct _super_message_ref_t {
3908 // SUPER_IMP messenger;
3909 // SEL name;
3910 // };
3911 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3912 SelectorPtrTy,
3913 NULL);
3914 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3915
3916 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3917 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3918
Daniel Dunbare588b992009-03-01 04:46:24 +00003919
3920 // struct objc_typeinfo {
3921 // const void** vtable; // objc_ehtype_vtable + 2
3922 // const char* name; // c++ typeinfo string
3923 // Class cls;
3924 // };
3925 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3926 Int8PtrTy,
3927 ClassnfABIPtrTy,
3928 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003929 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003930 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003931}
3932
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003933llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3934 FinishNonFragileABIModule();
3935
3936 return NULL;
3937}
3938
3939void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3940 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003941
3942 // Build list of all implemented classe addresses in array
3943 // L_OBJC_LABEL_CLASS_$.
3944 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3945 // list of 'nonlazy' implementations (defined as those with a +load{}
3946 // method!!).
3947 unsigned NumClasses = DefinedClasses.size();
3948 if (NumClasses) {
3949 std::vector<llvm::Constant*> Symbols(NumClasses);
3950 for (unsigned i=0; i<NumClasses; i++)
3951 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3952 ObjCTypes.Int8PtrTy);
3953 llvm::Constant* Init =
3954 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3955 NumClasses),
3956 Symbols);
3957
3958 llvm::GlobalVariable *GV =
3959 new llvm::GlobalVariable(Init->getType(), false,
3960 llvm::GlobalValue::InternalLinkage,
3961 Init,
3962 "\01L_OBJC_LABEL_CLASS_$",
3963 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003964 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003965 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3966 UsedGlobals.push_back(GV);
3967 }
3968
3969 // Build list of all implemented category addresses in array
3970 // L_OBJC_LABEL_CATEGORY_$.
3971 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3972 // list of 'nonlazy' category implementations (defined as those with a +load{}
3973 // method!!).
3974 unsigned NumCategory = DefinedCategories.size();
3975 if (NumCategory) {
3976 std::vector<llvm::Constant*> Symbols(NumCategory);
3977 for (unsigned i=0; i<NumCategory; i++)
3978 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3979 ObjCTypes.Int8PtrTy);
3980 llvm::Constant* Init =
3981 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3982 NumCategory),
3983 Symbols);
3984
3985 llvm::GlobalVariable *GV =
3986 new llvm::GlobalVariable(Init->getType(), false,
3987 llvm::GlobalValue::InternalLinkage,
3988 Init,
3989 "\01L_OBJC_LABEL_CATEGORY_$",
3990 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003991 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003992 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3993 UsedGlobals.push_back(GV);
3994 }
3995
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003996 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3997 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3998 std::vector<llvm::Constant*> Values(2);
3999 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004000 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004001 // FIXME: Fix and continue?
4002 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4003 flags |= eImageInfo_GarbageCollected;
4004 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4005 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004006 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004007 llvm::Constant* Init = llvm::ConstantArray::get(
4008 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4009 Values);
4010 llvm::GlobalVariable *IMGV =
4011 new llvm::GlobalVariable(Init->getType(), false,
4012 llvm::GlobalValue::InternalLinkage,
4013 Init,
4014 "\01L_OBJC_IMAGE_INFO",
4015 &CGM.getModule());
4016 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004017 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004018 UsedGlobals.push_back(IMGV);
4019
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004020 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004021
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004022 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4023 e = UsedGlobals.end(); i != e; ++i) {
4024 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4025 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004026
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004027 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4028 llvm::GlobalValue *GV =
4029 new llvm::GlobalVariable(AT, false,
4030 llvm::GlobalValue::AppendingLinkage,
4031 llvm::ConstantArray::get(AT, Used),
4032 "llvm.used",
4033 &CGM.getModule());
4034
4035 GV->setSection("llvm.metadata");
4036
4037}
4038
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004039// Metadata flags
4040enum MetaDataDlags {
4041 CLS = 0x0,
4042 CLS_META = 0x1,
4043 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004044 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004045 CLS_EXCEPTION = 0x20
4046};
4047/// BuildClassRoTInitializer - generate meta-data for:
4048/// struct _class_ro_t {
4049/// uint32_t const flags;
4050/// uint32_t const instanceStart;
4051/// uint32_t const instanceSize;
4052/// uint32_t const reserved; // only when building for 64bit targets
4053/// const uint8_t * const ivarLayout;
4054/// const char *const name;
4055/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004056/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004057/// const struct _ivar_list_t *const ivars;
4058/// const uint8_t * const weakIvarLayout;
4059/// const struct _prop_list_t * const properties;
4060/// }
4061///
4062llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4063 unsigned flags,
4064 unsigned InstanceStart,
4065 unsigned InstanceSize,
4066 const ObjCImplementationDecl *ID) {
4067 std::string ClassName = ID->getNameAsString();
4068 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4069 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4070 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4071 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4072 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004073 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4074 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004075 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004076 // const struct _method_list_t * const baseMethods;
4077 std::vector<llvm::Constant*> Methods;
4078 std::string MethodListName("\01l_OBJC_$_");
4079 if (flags & CLS_META) {
4080 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004081 for (ObjCImplementationDecl::classmeth_iterator
4082 i = ID->classmeth_begin(CGM.getContext()),
4083 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004084 // Class methods should always be defined.
4085 Methods.push_back(GetMethodConstant(*i));
4086 }
4087 } else {
4088 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004089 for (ObjCImplementationDecl::instmeth_iterator
4090 i = ID->instmeth_begin(CGM.getContext()),
4091 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004092 // Instance methods should always be defined.
4093 Methods.push_back(GetMethodConstant(*i));
4094 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004095 for (ObjCImplementationDecl::propimpl_iterator
4096 i = ID->propimpl_begin(CGM.getContext()),
4097 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004098 ObjCPropertyImplDecl *PID = *i;
4099
4100 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4101 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4102
4103 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4104 if (llvm::Constant *C = GetMethodConstant(MD))
4105 Methods.push_back(C);
4106 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4107 if (llvm::Constant *C = GetMethodConstant(MD))
4108 Methods.push_back(C);
4109 }
4110 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004111 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004112 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004113 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004114
4115 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4116 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4117 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4118 + OID->getNameAsString(),
4119 OID->protocol_begin(),
4120 OID->protocol_end());
4121
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004122 if (flags & CLS_META)
4123 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4124 else
4125 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004126 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4127 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004128 if (flags & CLS_META)
4129 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4130 else
4131 Values[ 9] =
4132 EmitPropertyList(
4133 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4134 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004135 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4136 Values);
4137 llvm::GlobalVariable *CLASS_RO_GV =
4138 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4139 llvm::GlobalValue::InternalLinkage,
4140 Init,
4141 (flags & CLS_META) ?
4142 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4143 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4144 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004145 CLASS_RO_GV->setAlignment(
4146 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004147 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004148 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004149
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004150}
4151
4152/// BuildClassMetaData - This routine defines that to-level meta-data
4153/// for the given ClassName for:
4154/// struct _class_t {
4155/// struct _class_t *isa;
4156/// struct _class_t * const superclass;
4157/// void *cache;
4158/// IMP *vtable;
4159/// struct class_ro_t *ro;
4160/// }
4161///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004162llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4163 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004164 llvm::Constant *IsAGV,
4165 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004166 llvm::Constant *ClassRoGV,
4167 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004168 std::vector<llvm::Constant*> Values(5);
4169 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004170 Values[1] = SuperClassGV
4171 ? SuperClassGV
4172 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004173 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4174 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4175 Values[4] = ClassRoGV; // &CLASS_RO_GV
4176 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4177 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004178 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4179 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004180 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004181 GV->setAlignment(
4182 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004183 if (HiddenVisibility)
4184 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004185 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004186}
4187
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004188void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004189 uint32_t &InstanceStart,
4190 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004191 const ASTRecordLayout &RL =
4192 CGM.getContext().getASTObjCImplementationLayout(OID);
4193
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004194 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004195 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004196
4197 // If there are no fields, the start is the same as the end.
4198 if (!RL.getFieldCount())
4199 InstanceStart = InstanceSize;
4200 else
4201 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004202}
4203
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4205 std::string ClassName = ID->getNameAsString();
4206 if (!ObjCEmptyCacheVar) {
4207 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004208 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004209 false,
4210 llvm::GlobalValue::ExternalLinkage,
4211 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004212 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004213 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004214
4215 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004216 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004217 false,
4218 llvm::GlobalValue::ExternalLinkage,
4219 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004220 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004221 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004222 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004223 assert(ID->getClassInterface() &&
4224 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004225 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004226 uint32_t InstanceStart =
4227 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4228 uint32_t InstanceSize = InstanceStart;
4229 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004230 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4231 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004232
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004233 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004234
Daniel Dunbar04d40782009-04-14 06:00:08 +00004235 bool classIsHidden =
4236 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004237 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004238 flags |= OBJC2_CLS_HIDDEN;
4239 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004240 // class is root
4241 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004242 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004243 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004244 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004245 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004246 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4247 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4248 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004249 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004250 // work on super class metadata symbol.
4251 std::string SuperClassName =
4252 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004253 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004254 }
4255 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4256 InstanceStart,
4257 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004258 std::string TClassName = ObjCMetaClassName + ClassName;
4259 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004260 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4261 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004262
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004263 // Metadata for the class
4264 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004265 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004266 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004267
4268 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4269 flags |= CLS_EXCEPTION;
4270
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004271 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004272 flags |= CLS_ROOT;
4273 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004274 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004275 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004276 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004277 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004278 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004279 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004280 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004281 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004282 InstanceStart,
4283 InstanceSize,
4284 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004285
4286 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004287 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004288 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4289 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004290 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004291
4292 // Force the definition of the EHType if necessary.
4293 if (flags & CLS_EXCEPTION)
4294 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004295}
4296
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004297/// GenerateProtocolRef - This routine is called to generate code for
4298/// a protocol reference expression; as in:
4299/// @code
4300/// @protocol(Proto1);
4301/// @endcode
4302/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4303/// which will hold address of the protocol meta-data.
4304///
4305llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4306 const ObjCProtocolDecl *PD) {
4307
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004308 // This routine is called for @protocol only. So, we must build definition
4309 // of protocol's meta-data (not a reference to it!)
4310 //
4311 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004312 ObjCTypes.ExternalProtocolPtrTy);
4313
4314 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4315 ProtocolName += PD->getNameAsCString();
4316
4317 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4318 if (PTGV)
4319 return Builder.CreateLoad(PTGV, false, "tmp");
4320 PTGV = new llvm::GlobalVariable(
4321 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004322 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004323 Init,
4324 ProtocolName,
4325 &CGM.getModule());
4326 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4327 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4328 UsedGlobals.push_back(PTGV);
4329 return Builder.CreateLoad(PTGV, false, "tmp");
4330}
4331
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004332/// GenerateCategory - Build metadata for a category implementation.
4333/// struct _category_t {
4334/// const char * const name;
4335/// struct _class_t *const cls;
4336/// const struct _method_list_t * const instance_methods;
4337/// const struct _method_list_t * const class_methods;
4338/// const struct _protocol_list_t * const protocols;
4339/// const struct _prop_list_t * const properties;
4340/// }
4341///
4342void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4343{
4344 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004345 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4346 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004347 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004348 std::string ExtClassName(getClassSymbolPrefix() +
4349 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004350
4351 std::vector<llvm::Constant*> Values(6);
4352 Values[0] = GetClassName(OCD->getIdentifier());
4353 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004354 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004355 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004356 std::vector<llvm::Constant*> Methods;
4357 std::string MethodListName(Prefix);
4358 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4359 "_$_" + OCD->getNameAsString();
4360
Douglas Gregor653f1b12009-04-23 01:02:12 +00004361 for (ObjCCategoryImplDecl::instmeth_iterator
4362 i = OCD->instmeth_begin(CGM.getContext()),
4363 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004364 // Instance methods should always be defined.
4365 Methods.push_back(GetMethodConstant(*i));
4366 }
4367
4368 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004369 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004370 Methods);
4371
4372 MethodListName = Prefix;
4373 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4374 OCD->getNameAsString();
4375 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004376 for (ObjCCategoryImplDecl::classmeth_iterator
4377 i = OCD->classmeth_begin(CGM.getContext()),
4378 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004379 // Class methods should always be defined.
4380 Methods.push_back(GetMethodConstant(*i));
4381 }
4382
4383 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004384 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004385 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004386 const ObjCCategoryDecl *Category =
4387 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004388 if (Category) {
4389 std::string ExtName(Interface->getNameAsString() + "_$_" +
4390 OCD->getNameAsString());
4391 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4392 + Interface->getNameAsString() + "_$_"
4393 + Category->getNameAsString(),
4394 Category->protocol_begin(),
4395 Category->protocol_end());
4396 Values[5] =
4397 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4398 OCD, Category, ObjCTypes);
4399 }
4400 else {
4401 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4402 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4403 }
4404
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004405 llvm::Constant *Init =
4406 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4407 Values);
4408 llvm::GlobalVariable *GCATV
4409 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4410 false,
4411 llvm::GlobalValue::InternalLinkage,
4412 Init,
4413 ExtCatName,
4414 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004415 GCATV->setAlignment(
4416 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004417 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004418 UsedGlobals.push_back(GCATV);
4419 DefinedCategories.push_back(GCATV);
4420}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004421
4422/// GetMethodConstant - Return a struct objc_method constant for the
4423/// given method if it has been defined. The result is null if the
4424/// method has not been defined. The return value has type MethodPtrTy.
4425llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4426 const ObjCMethodDecl *MD) {
4427 // FIXME: Use DenseMap::lookup
4428 llvm::Function *Fn = MethodDefinitions[MD];
4429 if (!Fn)
4430 return 0;
4431
4432 std::vector<llvm::Constant*> Method(3);
4433 Method[0] =
4434 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4435 ObjCTypes.SelectorPtrTy);
4436 Method[1] = GetMethodVarType(MD);
4437 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4438 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4439}
4440
4441/// EmitMethodList - Build meta-data for method declarations
4442/// struct _method_list_t {
4443/// uint32_t entsize; // sizeof(struct _objc_method)
4444/// uint32_t method_count;
4445/// struct _objc_method method_list[method_count];
4446/// }
4447///
4448llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4449 const std::string &Name,
4450 const char *Section,
4451 const ConstantVector &Methods) {
4452 // Return null for empty list.
4453 if (Methods.empty())
4454 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4455
4456 std::vector<llvm::Constant*> Values(3);
4457 // sizeof(struct _objc_method)
4458 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4459 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4460 // method_count
4461 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4462 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4463 Methods.size());
4464 Values[2] = llvm::ConstantArray::get(AT, Methods);
4465 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4466
4467 llvm::GlobalVariable *GV =
4468 new llvm::GlobalVariable(Init->getType(), false,
4469 llvm::GlobalValue::InternalLinkage,
4470 Init,
4471 Name,
4472 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004473 GV->setAlignment(
4474 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004475 GV->setSection(Section);
4476 UsedGlobals.push_back(GV);
4477 return llvm::ConstantExpr::getBitCast(GV,
4478 ObjCTypes.MethodListnfABIPtrTy);
4479}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004480
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004481/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4482/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004483llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004484 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004485 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004486 // FIXME: We shouldn't need to do this lookup.
4487 unsigned Index;
4488 const ObjCInterfaceDecl *Container =
4489 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4490 assert(Container && "Unable to find ivar container!");
4491 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004492 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004493 llvm::GlobalVariable *IvarOffsetGV =
4494 CGM.getModule().getGlobalVariable(Name);
4495 if (!IvarOffsetGV)
4496 IvarOffsetGV =
4497 new llvm::GlobalVariable(ObjCTypes.LongTy,
4498 false,
4499 llvm::GlobalValue::ExternalLinkage,
4500 0,
4501 Name,
4502 &CGM.getModule());
4503 return IvarOffsetGV;
4504}
4505
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004506llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004507 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004508 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004509 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004510 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4511 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4512 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004513 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004514 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004515
4516 // FIXME: This matches gcc, but shouldn't the visibility be set on
4517 // the use as well (i.e., in ObjCIvarOffsetVariable).
4518 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4519 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4520 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004521 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004522 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004523 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004524 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004525 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004526}
4527
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004528/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004529/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004530/// IvarListnfABIPtrTy.
4531/// struct _ivar_t {
4532/// unsigned long int *offset; // pointer to ivar offset location
4533/// char *name;
4534/// char *type;
4535/// uint32_t alignment;
4536/// uint32_t size;
4537/// }
4538/// struct _ivar_list_t {
4539/// uint32 entsize; // sizeof(struct _ivar_t)
4540/// uint32 count;
4541/// struct _iver_t list[count];
4542/// }
4543///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004544
4545void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4546 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4547 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4548 E = OID->ivar_end(); I != E; ++I) {
4549 // Ignore unnamed bit-fields.
4550 if (!(*I)->getDeclName())
4551 continue;
4552
4553 Res.push_back(*I);
4554 }
4555
4556 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4557 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4558 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4559 Res.push_back(IV);
4560}
4561
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004562llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4563 const ObjCImplementationDecl *ID) {
4564
4565 std::vector<llvm::Constant*> Ivars, Ivar(5);
4566
4567 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4568 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4569
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004570 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004571
Daniel Dunbar91636d62009-04-20 00:33:43 +00004572 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004573 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004574 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004575
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004576 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4577 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004578 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004579 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004580 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4581 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004582 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004583 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004584 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4585 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004586 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587 Align = llvm::Log2_32(Align);
4588 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004589 // NOTE. Size of a bitfield does not match gcc's, because of the
4590 // way bitfields are treated special in each. But I am told that
4591 // 'size' for bitfield ivars is ignored by the runtime so it does
4592 // not matter. If it matters, there is enough info to get the
4593 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004594 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4595 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4596 }
4597 // Return null for empty list.
4598 if (Ivars.empty())
4599 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4600 std::vector<llvm::Constant*> Values(3);
4601 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4602 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4603 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4604 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4605 Ivars.size());
4606 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4607 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4608 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4609 llvm::GlobalVariable *GV =
4610 new llvm::GlobalVariable(Init->getType(), false,
4611 llvm::GlobalValue::InternalLinkage,
4612 Init,
4613 Prefix + OID->getNameAsString(),
4614 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004615 GV->setAlignment(
4616 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004617 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004618
4619 UsedGlobals.push_back(GV);
4620 return llvm::ConstantExpr::getBitCast(GV,
4621 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004622}
4623
4624llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4625 const ObjCProtocolDecl *PD) {
4626 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4627
4628 if (!Entry) {
4629 // We use the initializer as a marker of whether this is a forward
4630 // reference or not. At module finalization we add the empty
4631 // contents for protocols which were referenced but never defined.
4632 Entry =
4633 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4634 llvm::GlobalValue::ExternalLinkage,
4635 0,
4636 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4637 &CGM.getModule());
4638 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4639 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004640 }
4641
4642 return Entry;
4643}
4644
4645/// GetOrEmitProtocol - Generate the protocol meta-data:
4646/// @code
4647/// struct _protocol_t {
4648/// id isa; // NULL
4649/// const char * const protocol_name;
4650/// const struct _protocol_list_t * protocol_list; // super protocols
4651/// const struct method_list_t * const instance_methods;
4652/// const struct method_list_t * const class_methods;
4653/// const struct method_list_t *optionalInstanceMethods;
4654/// const struct method_list_t *optionalClassMethods;
4655/// const struct _prop_list_t * properties;
4656/// const uint32_t size; // sizeof(struct _protocol_t)
4657/// const uint32_t flags; // = 0
4658/// }
4659/// @endcode
4660///
4661
4662llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4663 const ObjCProtocolDecl *PD) {
4664 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4665
4666 // Early exit if a defining object has already been generated.
4667 if (Entry && Entry->hasInitializer())
4668 return Entry;
4669
4670 const char *ProtocolName = PD->getNameAsCString();
4671
4672 // Construct method lists.
4673 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4674 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004675 for (ObjCProtocolDecl::instmeth_iterator
4676 i = PD->instmeth_begin(CGM.getContext()),
4677 e = PD->instmeth_end(CGM.getContext());
4678 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004679 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004680 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004681 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4682 OptInstanceMethods.push_back(C);
4683 } else {
4684 InstanceMethods.push_back(C);
4685 }
4686 }
4687
Douglas Gregor6ab35242009-04-09 21:40:53 +00004688 for (ObjCProtocolDecl::classmeth_iterator
4689 i = PD->classmeth_begin(CGM.getContext()),
4690 e = PD->classmeth_end(CGM.getContext());
4691 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004692 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004693 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004694 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4695 OptClassMethods.push_back(C);
4696 } else {
4697 ClassMethods.push_back(C);
4698 }
4699 }
4700
4701 std::vector<llvm::Constant*> Values(10);
4702 // isa is NULL
4703 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4704 Values[1] = GetClassName(PD->getIdentifier());
4705 Values[2] = EmitProtocolList(
4706 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4707 PD->protocol_begin(),
4708 PD->protocol_end());
4709
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004710 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004711 + PD->getNameAsString(),
4712 "__DATA, __objc_const",
4713 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004714 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004715 + PD->getNameAsString(),
4716 "__DATA, __objc_const",
4717 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004718 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004719 + PD->getNameAsString(),
4720 "__DATA, __objc_const",
4721 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004722 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004723 + PD->getNameAsString(),
4724 "__DATA, __objc_const",
4725 OptClassMethods);
4726 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4727 0, PD, ObjCTypes);
4728 uint32_t Size =
4729 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4730 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4731 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4732 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4733 Values);
4734
4735 if (Entry) {
4736 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004737 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004738 Entry->setInitializer(Init);
4739 } else {
4740 Entry =
4741 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004742 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 Init,
4744 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4745 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004746 Entry->setAlignment(
4747 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004748 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004750 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4751
4752 // Use this protocol meta-data to build protocol list table in section
4753 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004754 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004755 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004756 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004757 Entry,
4758 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4759 +ProtocolName,
4760 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004761 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004762 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004763 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004764 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4765 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 return Entry;
4767}
4768
4769/// EmitProtocolList - Generate protocol list meta-data:
4770/// @code
4771/// struct _protocol_list_t {
4772/// long protocol_count; // Note, this is 32/64 bit
4773/// struct _protocol_t[protocol_count];
4774/// }
4775/// @endcode
4776///
4777llvm::Constant *
4778CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4779 ObjCProtocolDecl::protocol_iterator begin,
4780 ObjCProtocolDecl::protocol_iterator end) {
4781 std::vector<llvm::Constant*> ProtocolRefs;
4782
Fariborz Jahanianda320092009-01-29 19:24:30 +00004783 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004784 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4786
Daniel Dunbar948e2582009-02-15 07:36:20 +00004787 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004788 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4789 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004790 return llvm::ConstantExpr::getBitCast(GV,
4791 ObjCTypes.ProtocolListnfABIPtrTy);
4792
4793 for (; begin != end; ++begin)
4794 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4795
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 // This list is null terminated.
4797 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004798 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799
4800 std::vector<llvm::Constant*> Values(2);
4801 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4802 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004803 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004804 ProtocolRefs.size()),
4805 ProtocolRefs);
4806
4807 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4808 GV = new llvm::GlobalVariable(Init->getType(), false,
4809 llvm::GlobalValue::InternalLinkage,
4810 Init,
4811 Name,
4812 &CGM.getModule());
4813 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004814 GV->setAlignment(
4815 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004817 return llvm::ConstantExpr::getBitCast(GV,
4818 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004819}
4820
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004821/// GetMethodDescriptionConstant - This routine build following meta-data:
4822/// struct _objc_method {
4823/// SEL _cmd;
4824/// char *method_type;
4825/// char *_imp;
4826/// }
4827
4828llvm::Constant *
4829CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4830 std::vector<llvm::Constant*> Desc(3);
4831 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4832 ObjCTypes.SelectorPtrTy);
4833 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004834 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004835 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4836 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4837}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004838
4839/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4840/// This code gen. amounts to generating code for:
4841/// @code
4842/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4843/// @encode
4844///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004845LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004846 CodeGen::CodeGenFunction &CGF,
4847 QualType ObjectTy,
4848 llvm::Value *BaseValue,
4849 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004850 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004851 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004852 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4853 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004854}
4855
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004856llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4857 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004858 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004859 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004860 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4861 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004862}
4863
Fariborz Jahanian46551122009-02-04 00:22:57 +00004864CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4865 CodeGen::CodeGenFunction &CGF,
4866 QualType ResultType,
4867 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004868 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004869 QualType Arg0Ty,
4870 bool IsSuper,
4871 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004872 // FIXME. Even though IsSuper is passes. This function doese not
4873 // handle calls to 'super' receivers.
4874 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004875 llvm::Value *Arg0 = Receiver;
4876 if (!IsSuper)
4877 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004878
4879 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004880 // FIXME. This is too much work to get the ABI-specific result type
4881 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004882 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4883 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004884 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004885 std::string Name("\01l_");
4886 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004887#if 0
4888 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004889 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004890 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004891 // FIXME. Is there a better way of getting these names.
4892 // They are available in RuntimeFunctions vector pair.
4893 Name += "objc_msgSendId_stret_fixup";
4894 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004895 else
4896#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004897 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004898 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004899 Name += "objc_msgSendSuper2_stret_fixup";
4900 }
4901 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004902 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004903 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004904 Name += "objc_msgSend_stret_fixup";
4905 }
4906 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00004907 else if (!IsSuper && ResultType->isFloatingType()) {
4908 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
4909 BuiltinType::Kind k = BT->getKind();
4910 if (k == BuiltinType::LongDouble) {
4911 Fn = ObjCTypes.getMessageSendFpretFixupFn();
4912 Name += "objc_msgSend_fpret_fixup";
4913 }
4914 else {
4915 Fn = ObjCTypes.getMessageSendFixupFn();
4916 Name += "objc_msgSend_fixup";
4917 }
4918 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004919 }
4920 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004921#if 0
4922// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004923 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004924 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004925 Name += "objc_msgSendId_fixup";
4926 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004927 else
4928#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004929 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004930 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004931 Name += "objc_msgSendSuper2_fixup";
4932 }
4933 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004934 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004935 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004936 Name += "objc_msgSend_fixup";
4937 }
4938 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004939 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004940 Name += '_';
4941 std::string SelName(Sel.getAsString());
4942 // Replace all ':' in selector name with '_' ouch!
4943 for(unsigned i = 0; i < SelName.size(); i++)
4944 if (SelName[i] == ':')
4945 SelName[i] = '_';
4946 Name += SelName;
4947 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4948 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004949 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950 std::vector<llvm::Constant*> Values(2);
4951 Values[0] = Fn;
4952 Values[1] = GetMethodVarName(Sel);
4953 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4954 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004955 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 Init,
4957 Name,
4958 &CGM.getModule());
4959 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00004960 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004961 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004962 }
4963 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004964
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004965 CallArgList ActualArgs;
4966 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4967 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4968 ObjCTypes.MessageRefCPtrTy));
4969 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004970 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4971 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4972 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004973 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004974 Callee = CGF.Builder.CreateBitCast(Callee,
4975 llvm::PointerType::getUnqual(FTy));
4976 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004977}
4978
4979/// Generate code for a message send expression in the nonfragile abi.
4980CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4981 CodeGen::CodeGenFunction &CGF,
4982 QualType ResultType,
4983 Selector Sel,
4984 llvm::Value *Receiver,
4985 bool IsClassMessage,
4986 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004987 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004989 false, CallArgs);
4990}
4991
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004992llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004993CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004994 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4995
Daniel Dunbardfff2302009-03-02 05:18:14 +00004996 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004997 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4998 llvm::GlobalValue::ExternalLinkage,
4999 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005000 }
5001
5002 return GV;
5003}
5004
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005005llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005006 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005007 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5008
5009 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005010 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005011 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005012 Entry =
5013 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5014 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005015 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005016 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005017 &CGM.getModule());
5018 Entry->setAlignment(
5019 CGM.getTargetData().getPrefTypeAlignment(
5020 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005021 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5022 UsedGlobals.push_back(Entry);
5023 }
5024
5025 return Builder.CreateLoad(Entry, false, "tmp");
5026}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005027
Daniel Dunbar11394522009-04-18 08:51:00 +00005028llvm::Value *
5029CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5030 const ObjCInterfaceDecl *ID) {
5031 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5032
5033 if (!Entry) {
5034 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5035 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5036 Entry =
5037 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5038 llvm::GlobalValue::InternalLinkage,
5039 ClassGV,
5040 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5041 &CGM.getModule());
5042 Entry->setAlignment(
5043 CGM.getTargetData().getPrefTypeAlignment(
5044 ObjCTypes.ClassnfABIPtrTy));
5045 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005046 UsedGlobals.push_back(Entry);
5047 }
5048
5049 return Builder.CreateLoad(Entry, false, "tmp");
5050}
5051
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005052/// EmitMetaClassRef - Return a Value * of the address of _class_t
5053/// meta-data
5054///
5055llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5056 const ObjCInterfaceDecl *ID) {
5057 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5058 if (Entry)
5059 return Builder.CreateLoad(Entry, false, "tmp");
5060
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005061 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005062 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005063 Entry =
5064 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5065 llvm::GlobalValue::InternalLinkage,
5066 MetaClassGV,
5067 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5068 &CGM.getModule());
5069 Entry->setAlignment(
5070 CGM.getTargetData().getPrefTypeAlignment(
5071 ObjCTypes.ClassnfABIPtrTy));
5072
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005073 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005074 UsedGlobals.push_back(Entry);
5075
5076 return Builder.CreateLoad(Entry, false, "tmp");
5077}
5078
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005079/// GetClass - Return a reference to the class for the given interface
5080/// decl.
5081llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5082 const ObjCInterfaceDecl *ID) {
5083 return EmitClassRef(Builder, ID);
5084}
5085
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005086/// Generates a message send where the super is the receiver. This is
5087/// a message send to self with special delivery semantics indicating
5088/// which class's method should be called.
5089CodeGen::RValue
5090CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5091 QualType ResultType,
5092 Selector Sel,
5093 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005094 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005095 llvm::Value *Receiver,
5096 bool IsClassMessage,
5097 const CodeGen::CallArgList &CallArgs) {
5098 // ...
5099 // Create and init a super structure; this is a (receiver, class)
5100 // pair we will pass to objc_msgSendSuper.
5101 llvm::Value *ObjCSuper =
5102 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5103
5104 llvm::Value *ReceiverAsObject =
5105 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5106 CGF.Builder.CreateStore(ReceiverAsObject,
5107 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5108
5109 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005110 llvm::Value *Target;
5111 if (IsClassMessage) {
5112 if (isCategoryImpl) {
5113 // Message sent to "super' in a class method defined in
5114 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005115 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005116 Target = CGF.Builder.CreateStructGEP(Target, 0);
5117 Target = CGF.Builder.CreateLoad(Target);
5118 }
5119 else
5120 Target = EmitMetaClassRef(CGF.Builder, Class);
5121 }
5122 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005123 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005124
5125 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5126 // and ObjCTypes types.
5127 const llvm::Type *ClassTy =
5128 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5129 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5130 CGF.Builder.CreateStore(Target,
5131 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5132
5133 return EmitMessageSend(CGF, ResultType, Sel,
5134 ObjCSuper, ObjCTypes.SuperPtrCTy,
5135 true, CallArgs);
5136}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005137
5138llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5139 Selector Sel) {
5140 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5141
5142 if (!Entry) {
5143 llvm::Constant *Casted =
5144 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5145 ObjCTypes.SelectorPtrTy);
5146 Entry =
5147 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5148 llvm::GlobalValue::InternalLinkage,
5149 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5150 &CGM.getModule());
5151 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5152 UsedGlobals.push_back(Entry);
5153 }
5154
5155 return Builder.CreateLoad(Entry, false, "tmp");
5156}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005157/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5158/// objc_assign_ivar (id src, id *dst)
5159///
5160void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5161 llvm::Value *src, llvm::Value *dst)
5162{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005163 const llvm::Type * SrcTy = src->getType();
5164 if (!isa<llvm::PointerType>(SrcTy)) {
5165 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5166 assert(Size <= 8 && "does not support size > 8");
5167 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5168 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005169 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5170 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005171 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5172 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005173 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005174 src, dst, "assignivar");
5175 return;
5176}
5177
5178/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5179/// objc_assign_strongCast (id src, id *dst)
5180///
5181void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5182 CodeGen::CodeGenFunction &CGF,
5183 llvm::Value *src, llvm::Value *dst)
5184{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005185 const llvm::Type * SrcTy = src->getType();
5186 if (!isa<llvm::PointerType>(SrcTy)) {
5187 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5188 assert(Size <= 8 && "does not support size > 8");
5189 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5190 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005191 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5192 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005193 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5194 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005195 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005196 src, dst, "weakassign");
5197 return;
5198}
5199
5200/// EmitObjCWeakRead - Code gen for loading value of a __weak
5201/// object: objc_read_weak (id *src)
5202///
5203llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5204 CodeGen::CodeGenFunction &CGF,
5205 llvm::Value *AddrWeakObj)
5206{
Eli Friedman8339b352009-03-07 03:57:15 +00005207 const llvm::Type* DestTy =
5208 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005209 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005210 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005211 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005212 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005213 return read_weak;
5214}
5215
5216/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5217/// objc_assign_weak (id src, id *dst)
5218///
5219void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5220 llvm::Value *src, llvm::Value *dst)
5221{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005222 const llvm::Type * SrcTy = src->getType();
5223 if (!isa<llvm::PointerType>(SrcTy)) {
5224 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5225 assert(Size <= 8 && "does not support size > 8");
5226 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5227 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005228 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5229 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005230 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5231 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005232 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005233 src, dst, "weakassign");
5234 return;
5235}
5236
5237/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5238/// objc_assign_global (id src, id *dst)
5239///
5240void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5241 llvm::Value *src, llvm::Value *dst)
5242{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005243 const llvm::Type * SrcTy = src->getType();
5244 if (!isa<llvm::PointerType>(SrcTy)) {
5245 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5246 assert(Size <= 8 && "does not support size > 8");
5247 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5248 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005249 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5250 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005251 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5252 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005253 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005254 src, dst, "globalassign");
5255 return;
5256}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005257
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005258void
5259CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5260 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005261 bool isTry = isa<ObjCAtTryStmt>(S);
5262 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5263 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005264 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005265 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005266 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005267 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5268
5269 // For @synchronized, call objc_sync_enter(sync.expr). The
5270 // evaluation of the expression must occur before we enter the
5271 // @synchronized. We can safely avoid a temp here because jumps into
5272 // @synchronized are illegal & this will dominate uses.
5273 llvm::Value *SyncArg = 0;
5274 if (!isTry) {
5275 SyncArg =
5276 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5277 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005278 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005279 }
5280
5281 // Push an EH context entry, used for handling rethrows and jumps
5282 // through finally.
5283 CGF.PushCleanupBlock(FinallyBlock);
5284
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005285 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005286
5287 CGF.EmitBlock(TryBlock);
5288 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5289 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5290 CGF.EmitBranchThroughCleanup(FinallyEnd);
5291
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005292 // Emit the exception handler.
5293
5294 CGF.EmitBlock(TryHandler);
5295
5296 llvm::Value *llvm_eh_exception =
5297 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5298 llvm::Value *llvm_eh_selector_i64 =
5299 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5300 llvm::Value *llvm_eh_typeid_for_i64 =
5301 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5302 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5303 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5304
5305 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5306 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005307 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005308
5309 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005310 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005311 bool HasCatchAll = false;
5312 if (isTry) {
5313 if (const ObjCAtCatchStmt* CatchStmt =
5314 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5315 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005316 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005317 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005318
5319 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005320 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005321 // Use i8* null here to signal this is a catch all, not a cleanup.
5322 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5323 SelectorArgs.push_back(Null);
5324 HasCatchAll = true;
5325 break;
5326 }
5327
Daniel Dunbarede8de92009-03-06 00:01:21 +00005328 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5329 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005330 llvm::Value *IDEHType =
5331 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5332 if (!IDEHType)
5333 IDEHType =
5334 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5335 llvm::GlobalValue::ExternalLinkage,
5336 0, "OBJC_EHTYPE_id", &CGM.getModule());
5337 SelectorArgs.push_back(IDEHType);
5338 HasCatchAll = true;
5339 break;
5340 }
5341
5342 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005343 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005344 assert(PT && "Invalid @catch type.");
5345 const ObjCInterfaceType *IT =
5346 PT->getPointeeType()->getAsObjCInterfaceType();
5347 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005348 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005349 SelectorArgs.push_back(EHType);
5350 }
5351 }
5352 }
5353
5354 // We use a cleanup unless there was already a catch all.
5355 if (!HasCatchAll) {
5356 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005357 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358 }
5359
5360 llvm::Value *Selector =
5361 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5362 SelectorArgs.begin(), SelectorArgs.end(),
5363 "selector");
5364 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005365 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005366 const Stmt *CatchBody = Handlers[i].second;
5367
5368 llvm::BasicBlock *Next = 0;
5369
5370 // The last handler always matches.
5371 if (i + 1 != e) {
5372 assert(CatchParam && "Only last handler can be a catch all.");
5373
5374 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5375 Next = CGF.createBasicBlock("catch.next");
5376 llvm::Value *Id =
5377 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5378 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5379 ObjCTypes.Int8PtrTy));
5380 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5381 Match, Next);
5382
5383 CGF.EmitBlock(Match);
5384 }
5385
5386 if (CatchBody) {
5387 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5388 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5389
5390 // Cleanups must call objc_end_catch.
5391 //
5392 // FIXME: It seems incorrect for objc_begin_catch to be inside
5393 // this context, but this matches gcc.
5394 CGF.PushCleanupBlock(MatchEnd);
5395 CGF.setInvokeDest(MatchHandler);
5396
5397 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005398 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005399
5400 // Bind the catch parameter if it exists.
5401 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005402 ExcObject =
5403 CGF.Builder.CreateBitCast(ExcObject,
5404 CGF.ConvertType(CatchParam->getType()));
5405 // CatchParam is a ParmVarDecl because of the grammar
5406 // construction used to handle this, but for codegen purposes
5407 // we treat this as a local decl.
5408 CGF.EmitLocalBlockVarDecl(*CatchParam);
5409 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005410 }
5411
5412 CGF.ObjCEHValueStack.push_back(ExcObject);
5413 CGF.EmitStmt(CatchBody);
5414 CGF.ObjCEHValueStack.pop_back();
5415
5416 CGF.EmitBranchThroughCleanup(FinallyEnd);
5417
5418 CGF.EmitBlock(MatchHandler);
5419
5420 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5421 // We are required to emit this call to satisfy LLVM, even
5422 // though we don't use the result.
5423 llvm::SmallVector<llvm::Value*, 8> Args;
5424 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005425 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005426 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5427 0));
5428 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5429 CGF.Builder.CreateStore(Exc, RethrowPtr);
5430 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5431
5432 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5433
5434 CGF.EmitBlock(MatchEnd);
5435
5436 // Unfortunately, we also have to generate another EH frame here
5437 // in case this throws.
5438 llvm::BasicBlock *MatchEndHandler =
5439 CGF.createBasicBlock("match.end.handler");
5440 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005441 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005442 Cont, MatchEndHandler,
5443 Args.begin(), Args.begin());
5444
5445 CGF.EmitBlock(Cont);
5446 if (Info.SwitchBlock)
5447 CGF.EmitBlock(Info.SwitchBlock);
5448 if (Info.EndBlock)
5449 CGF.EmitBlock(Info.EndBlock);
5450
5451 CGF.EmitBlock(MatchEndHandler);
5452 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5453 // We are required to emit this call to satisfy LLVM, even
5454 // though we don't use the result.
5455 Args.clear();
5456 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005457 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005458 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5459 0));
5460 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5461 CGF.Builder.CreateStore(Exc, RethrowPtr);
5462 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5463
5464 if (Next)
5465 CGF.EmitBlock(Next);
5466 } else {
5467 assert(!Next && "catchup should be last handler.");
5468
5469 CGF.Builder.CreateStore(Exc, RethrowPtr);
5470 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5471 }
5472 }
5473
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005474 // Pop the cleanup entry, the @finally is outside this cleanup
5475 // scope.
5476 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5477 CGF.setInvokeDest(PrevLandingPad);
5478
5479 CGF.EmitBlock(FinallyBlock);
5480
5481 if (isTry) {
5482 if (const ObjCAtFinallyStmt* FinallyStmt =
5483 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5484 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5485 } else {
5486 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5487 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005488 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005489 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005490
5491 if (Info.SwitchBlock)
5492 CGF.EmitBlock(Info.SwitchBlock);
5493 if (Info.EndBlock)
5494 CGF.EmitBlock(Info.EndBlock);
5495
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005497 CGF.EmitBranch(FinallyEnd);
5498
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005499 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005500 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005501 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005502 CGF.Builder.CreateUnreachable();
5503
5504 CGF.EmitBlock(FinallyEnd);
5505}
5506
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005507/// EmitThrowStmt - Generate code for a throw statement.
5508void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5509 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005510 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005511 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005512 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005513 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005514 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5515 "Unexpected rethrow outside @catch block.");
5516 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005517 }
5518
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005519 llvm::Value *ExceptionAsObject =
5520 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5521 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5522 if (InvokeDest) {
5523 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005524 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005525 Cont, InvokeDest,
5526 &ExceptionAsObject, &ExceptionAsObject + 1);
5527 CGF.EmitBlock(Cont);
5528 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005529 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005530 CGF.Builder.CreateUnreachable();
5531
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005532 // Clear the insertion point to indicate we are in unreachable code.
5533 CGF.Builder.ClearInsertionPoint();
5534}
Daniel Dunbare588b992009-03-01 04:46:24 +00005535
5536llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005537CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5538 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005539 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005540
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005541 // If we don't need a definition, return the entry if found or check
5542 // if we use an external reference.
5543 if (!ForDefinition) {
5544 if (Entry)
5545 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005546
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005547 // If this type (or a super class) has the __objc_exception__
5548 // attribute, emit an external reference.
5549 if (hasObjCExceptionAttribute(ID))
5550 return Entry =
5551 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5552 llvm::GlobalValue::ExternalLinkage,
5553 0,
5554 (std::string("OBJC_EHTYPE_$_") +
5555 ID->getIdentifier()->getName()),
5556 &CGM.getModule());
5557 }
5558
5559 // Otherwise we need to either make a new entry or fill in the
5560 // initializer.
5561 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005562 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005563 std::string VTableName = "objc_ehtype_vtable";
5564 llvm::GlobalVariable *VTableGV =
5565 CGM.getModule().getGlobalVariable(VTableName);
5566 if (!VTableGV)
5567 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5568 llvm::GlobalValue::ExternalLinkage,
5569 0, VTableName, &CGM.getModule());
5570
5571 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5572
5573 std::vector<llvm::Constant*> Values(3);
5574 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5575 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005576 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005577 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5578
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005579 if (Entry) {
5580 Entry->setInitializer(Init);
5581 } else {
5582 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5583 llvm::GlobalValue::WeakAnyLinkage,
5584 Init,
5585 (std::string("OBJC_EHTYPE_$_") +
5586 ID->getIdentifier()->getName()),
5587 &CGM.getModule());
5588 }
5589
Daniel Dunbar04d40782009-04-14 06:00:08 +00005590 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005591 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005592 Entry->setAlignment(8);
5593
5594 if (ForDefinition) {
5595 Entry->setSection("__DATA,__objc_const");
5596 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5597 } else {
5598 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5599 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005600
5601 return Entry;
5602}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005603
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005604/* *** */
5605
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005606CodeGen::CGObjCRuntime *
5607CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005608 return new CGObjCMac(CGM);
5609}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005610
5611CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005612CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005613 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005614}