blob: 1a1ef831232e5475097f7fa0b6b18f497ca06ee4 [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) {
46 const ObjCInterfaceDecl *Super = OID->getSuperClass();
Daniel Dunbara80a0f62009-04-22 17:43:55 +000047
Daniel Dunbar532d4da2009-05-03 13:15:50 +000048 // FIXME: The index here is closely tied to how
49 // ASTContext::getObjCLayout is implemented. This should be fixed to
50 // get the information from the layout directly.
51 Index = 0;
52 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(),
53 IVE = OID->ivar_end(); IVI != IVE; ++IVI, ++Index)
54 if (OIVD == *IVI)
55 return OID;
56
57 // Also look in synthesized ivars.
58 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(Context),
59 E = OID->prop_end(Context); I != E; ++I) {
60 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) {
61 if (OIVD == Ivar)
62 return OID;
63 ++Index;
64 }
Daniel Dunbara80a0f62009-04-22 17:43:55 +000065 }
66
Daniel Dunbar532d4da2009-05-03 13:15:50 +000067 // Otherwise check in the super class.
68 if (Super)
69 return FindIvarInterface(Context, Super, OIVD, Index);
70
71 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000072}
73
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000074static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
75 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000076 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000077 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000078 unsigned Index;
79 const ObjCInterfaceDecl *Container =
80 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
81 assert(Container && "Unable to find ivar container");
82
83 // If we know have an implementation (and the ivar is in it) then
84 // look up in the implementation layout.
85 const ASTRecordLayout *RL;
86 if (ID && ID->getClassInterface() == Container)
87 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
88 else
89 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
90 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000091}
92
93uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
94 const ObjCInterfaceDecl *OID,
95 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000096 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
97}
98
99uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
100 const ObjCImplementationDecl *OID,
101 const ObjCIvarDecl *Ivar) {
102 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +0000103}
104
105LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
106 const ObjCInterfaceDecl *OID,
107 llvm::Value *BaseValue,
108 const ObjCIvarDecl *Ivar,
109 unsigned CVRQualifiers,
110 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000111 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000112 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000113 QualType IvarTy = Ivar->getType();
114 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000115 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000116 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000117 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000118
119 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000120 // We need to compute the bit offset for the bit-field, the offset
121 // is to the byte. Note, there is a subtle invariant here: we can
122 // only call this routine on non-sythesized ivars but we may be
123 // called for synthesized ivars. However, a synthesized ivar can
124 // never be a bit-field so this is safe.
125 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
126
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000127 uint64_t BitFieldSize =
128 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
129 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000130 IvarTy->isSignedIntegerType(),
131 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000132 }
133
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000134 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
135 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000136 LValue::SetObjCIvar(LV, true);
137 return LV;
138}
139
140///
141
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000142namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000143
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000144 typedef std::vector<llvm::Constant*> ConstantVector;
145
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000146 // FIXME: We should find a nicer way to make the labels for
147 // metadata, string concatenation is lame.
148
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000149class ObjCCommonTypesHelper {
150protected:
151 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000152
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000153public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000154 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000155 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000156
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000157 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
158 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000159
160 /// PtrObjectPtrTy - LLVM type for id *
161 const llvm::Type *PtrObjectPtrTy;
162
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000163 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000164 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000165 /// ProtocolPtrTy - LLVM type for external protocol handles
166 /// (typeof(Protocol))
167 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000168
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000169 // SuperCTy - clang type for struct objc_super.
170 QualType SuperCTy;
171 // SuperPtrCTy - clang type for struct objc_super *.
172 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000173
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000174 /// SuperTy - LLVM type for struct objc_super.
175 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000176 /// SuperPtrTy - LLVM type for struct objc_super *.
177 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000178
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000179 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
180 /// in GCC parlance).
181 const llvm::StructType *PropertyTy;
182
183 /// PropertyListTy - LLVM type for struct objc_property_list
184 /// (_prop_list_t in GCC parlance).
185 const llvm::StructType *PropertyListTy;
186 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
187 const llvm::Type *PropertyListPtrTy;
188
189 // MethodTy - LLVM type for struct objc_method.
190 const llvm::StructType *MethodTy;
191
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000192 /// CacheTy - LLVM type for struct objc_cache.
193 const llvm::Type *CacheTy;
194 /// CachePtrTy - LLVM type for struct objc_cache *.
195 const llvm::Type *CachePtrTy;
196
Chris Lattner72db6c32009-04-22 02:44:54 +0000197 llvm::Constant *getGetPropertyFn() {
198 CodeGen::CodeGenTypes &Types = CGM.getTypes();
199 ASTContext &Ctx = CGM.getContext();
200 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
201 llvm::SmallVector<QualType,16> Params;
202 QualType IdType = Ctx.getObjCIdType();
203 QualType SelType = Ctx.getObjCSelType();
204 Params.push_back(IdType);
205 Params.push_back(SelType);
206 Params.push_back(Ctx.LongTy);
207 Params.push_back(Ctx.BoolTy);
208 const llvm::FunctionType *FTy =
209 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
210 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
211 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000212
Chris Lattner72db6c32009-04-22 02:44:54 +0000213 llvm::Constant *getSetPropertyFn() {
214 CodeGen::CodeGenTypes &Types = CGM.getTypes();
215 ASTContext &Ctx = CGM.getContext();
216 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
217 llvm::SmallVector<QualType,16> Params;
218 QualType IdType = Ctx.getObjCIdType();
219 QualType SelType = Ctx.getObjCSelType();
220 Params.push_back(IdType);
221 Params.push_back(SelType);
222 Params.push_back(Ctx.LongTy);
223 Params.push_back(IdType);
224 Params.push_back(Ctx.BoolTy);
225 Params.push_back(Ctx.BoolTy);
226 const llvm::FunctionType *FTy =
227 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
228 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
229 }
230
231 llvm::Constant *getEnumerationMutationFn() {
232 // void objc_enumerationMutation (id)
233 std::vector<const llvm::Type*> Args;
234 Args.push_back(ObjectPtrTy);
235 llvm::FunctionType *FTy =
236 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
237 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
238 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000239
240 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000241 llvm::Constant *getGcReadWeakFn() {
242 // id objc_read_weak (id *)
243 std::vector<const llvm::Type*> Args;
244 Args.push_back(ObjectPtrTy->getPointerTo());
245 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
246 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
247 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000248
249 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000250 llvm::Constant *getGcAssignWeakFn() {
251 // id objc_assign_weak (id, id *)
252 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
253 Args.push_back(ObjectPtrTy->getPointerTo());
254 llvm::FunctionType *FTy =
255 llvm::FunctionType::get(ObjectPtrTy, Args, false);
256 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
257 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000258
259 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000260 llvm::Constant *getGcAssignGlobalFn() {
261 // id objc_assign_global(id, id *)
262 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
263 Args.push_back(ObjectPtrTy->getPointerTo());
264 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
265 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
266 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000267
268 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000269 llvm::Constant *getGcAssignIvarFn() {
270 // id objc_assign_ivar(id, id *)
271 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
272 Args.push_back(ObjectPtrTy->getPointerTo());
273 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
274 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
275 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000276
277 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000278 llvm::Constant *getGcAssignStrongCastFn() {
279 // id objc_assign_global(id, id *)
280 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
281 Args.push_back(ObjectPtrTy->getPointerTo());
282 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
283 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
284 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000285
286 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000287 llvm::Constant *getExceptionThrowFn() {
288 // void objc_exception_throw(id)
289 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
290 llvm::FunctionType *FTy =
291 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
292 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
293 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000294
Daniel Dunbar1c566672009-02-24 01:43:46 +0000295 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000296 llvm::Constant *getSyncEnterFn() {
297 // void objc_sync_enter (id)
298 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
299 llvm::FunctionType *FTy =
300 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
301 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
302 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000303
304 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000305 llvm::Constant *getSyncExitFn() {
306 // void objc_sync_exit (id)
307 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
308 llvm::FunctionType *FTy =
309 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
310 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
311 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000312
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000313 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
314 ~ObjCCommonTypesHelper(){}
315};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000316
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000317/// ObjCTypesHelper - Helper class that encapsulates lazy
318/// construction of varies types used during ObjC generation.
319class ObjCTypesHelper : public ObjCCommonTypesHelper {
320private:
321
Chris Lattner4176b0c2009-04-22 02:32:31 +0000322 llvm::Constant *getMessageSendFn() {
323 // id objc_msgSend (id, SEL, ...)
324 std::vector<const llvm::Type*> Params;
325 Params.push_back(ObjectPtrTy);
326 Params.push_back(SelectorPtrTy);
327 return
328 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
329 Params, true),
330 "objc_msgSend");
331 }
332
333 llvm::Constant *getMessageSendStretFn() {
334 // id objc_msgSend_stret (id, SEL, ...)
335 std::vector<const llvm::Type*> Params;
336 Params.push_back(ObjectPtrTy);
337 Params.push_back(SelectorPtrTy);
338 return
339 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
340 Params, true),
341 "objc_msgSend_stret");
342
343 }
344
345 llvm::Constant *getMessageSendFpretFn() {
346 // FIXME: This should be long double on x86_64?
347 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
348 std::vector<const llvm::Type*> Params;
349 Params.push_back(ObjectPtrTy);
350 Params.push_back(SelectorPtrTy);
351 return
352 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
353 Params,
354 true),
355 "objc_msgSend_fpret");
356
357 }
358
359 llvm::Constant *getMessageSendSuperFn() {
360 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
361 std::vector<const llvm::Type*> Params;
362 Params.push_back(SuperPtrTy);
363 Params.push_back(SelectorPtrTy);
364 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
365 Params, true),
366 "objc_msgSendSuper");
367 }
368 llvm::Constant *getMessageSendSuperStretFn() {
369 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
370 // SEL op, ...)
371 std::vector<const llvm::Type*> Params;
372 Params.push_back(Int8PtrTy);
373 Params.push_back(SuperPtrTy);
374 Params.push_back(SelectorPtrTy);
375 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
376 Params, true),
377 "objc_msgSendSuper_stret");
378 }
379
380 llvm::Constant *getMessageSendSuperFpretFn() {
381 // There is no objc_msgSendSuper_fpret? How can that work?
382 return getMessageSendSuperFn();
383 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000384
385public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000386 /// SymtabTy - LLVM type for struct objc_symtab.
387 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
389 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000390 /// ModuleTy - LLVM type for struct objc_module.
391 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000392
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000393 /// ProtocolTy - LLVM type for struct objc_protocol.
394 const llvm::StructType *ProtocolTy;
395 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
396 const llvm::Type *ProtocolPtrTy;
397 /// ProtocolExtensionTy - LLVM type for struct
398 /// objc_protocol_extension.
399 const llvm::StructType *ProtocolExtensionTy;
400 /// ProtocolExtensionTy - LLVM type for struct
401 /// objc_protocol_extension *.
402 const llvm::Type *ProtocolExtensionPtrTy;
403 /// MethodDescriptionTy - LLVM type for struct
404 /// objc_method_description.
405 const llvm::StructType *MethodDescriptionTy;
406 /// MethodDescriptionListTy - LLVM type for struct
407 /// objc_method_description_list.
408 const llvm::StructType *MethodDescriptionListTy;
409 /// MethodDescriptionListPtrTy - LLVM type for struct
410 /// objc_method_description_list *.
411 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000412 /// ProtocolListTy - LLVM type for struct objc_property_list.
413 const llvm::Type *ProtocolListTy;
414 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
415 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000416 /// CategoryTy - LLVM type for struct objc_category.
417 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000418 /// ClassTy - LLVM type for struct objc_class.
419 const llvm::StructType *ClassTy;
420 /// ClassPtrTy - LLVM type for struct objc_class *.
421 const llvm::Type *ClassPtrTy;
422 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
423 const llvm::StructType *ClassExtensionTy;
424 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
425 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000426 // IvarTy - LLVM type for struct objc_ivar.
427 const llvm::StructType *IvarTy;
428 /// IvarListTy - LLVM type for struct objc_ivar_list.
429 const llvm::Type *IvarListTy;
430 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
431 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000432 /// MethodListTy - LLVM type for struct objc_method_list.
433 const llvm::Type *MethodListTy;
434 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
435 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000436
437 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
438 const llvm::Type *ExceptionDataTy;
439
Anders Carlsson124526b2008-09-09 10:10:21 +0000440 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000441 llvm::Constant *getExceptionTryEnterFn() {
442 std::vector<const llvm::Type*> Params;
443 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
444 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
445 Params, false),
446 "objc_exception_try_enter");
447 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000448
449 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000450 llvm::Constant *getExceptionTryExitFn() {
451 std::vector<const llvm::Type*> Params;
452 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
453 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
454 Params, false),
455 "objc_exception_try_exit");
456 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000457
458 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000459 llvm::Constant *getExceptionExtractFn() {
460 std::vector<const llvm::Type*> Params;
461 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
462 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
463 Params, false),
464 "objc_exception_extract");
465
466 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000467
468 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000469 llvm::Constant *getExceptionMatchFn() {
470 std::vector<const llvm::Type*> Params;
471 Params.push_back(ClassPtrTy);
472 Params.push_back(ObjectPtrTy);
473 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
474 Params, false),
475 "objc_exception_match");
476
477 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000478
479 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000480 llvm::Constant *getSetJmpFn() {
481 std::vector<const llvm::Type*> Params;
482 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
483 return
484 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
485 Params, false),
486 "_setjmp");
487
488 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000489
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000490public:
491 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000492 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000493
494
Chris Lattner74391b42009-03-22 21:03:39 +0000495 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000496 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000497 }
498
Chris Lattner74391b42009-03-22 21:03:39 +0000499 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000500 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000501 }
502
Chris Lattner74391b42009-03-22 21:03:39 +0000503 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000504 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000505 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000506};
507
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000508/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000509/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000510class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000511public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000512
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000513 // MethodListnfABITy - LLVM for struct _method_list_t
514 const llvm::StructType *MethodListnfABITy;
515
516 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
517 const llvm::Type *MethodListnfABIPtrTy;
518
519 // ProtocolnfABITy = LLVM for struct _protocol_t
520 const llvm::StructType *ProtocolnfABITy;
521
Daniel Dunbar948e2582009-02-15 07:36:20 +0000522 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
523 const llvm::Type *ProtocolnfABIPtrTy;
524
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000525 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
526 const llvm::StructType *ProtocolListnfABITy;
527
528 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
529 const llvm::Type *ProtocolListnfABIPtrTy;
530
531 // ClassnfABITy - LLVM for struct _class_t
532 const llvm::StructType *ClassnfABITy;
533
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000534 // ClassnfABIPtrTy - LLVM for struct _class_t*
535 const llvm::Type *ClassnfABIPtrTy;
536
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000537 // IvarnfABITy - LLVM for struct _ivar_t
538 const llvm::StructType *IvarnfABITy;
539
540 // IvarListnfABITy - LLVM for struct _ivar_list_t
541 const llvm::StructType *IvarListnfABITy;
542
543 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
544 const llvm::Type *IvarListnfABIPtrTy;
545
546 // ClassRonfABITy - LLVM for struct _class_ro_t
547 const llvm::StructType *ClassRonfABITy;
548
549 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
550 const llvm::Type *ImpnfABITy;
551
552 // CategorynfABITy - LLVM for struct _category_t
553 const llvm::StructType *CategorynfABITy;
554
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000555 // New types for nonfragile abi messaging.
556
557 // MessageRefTy - LLVM for:
558 // struct _message_ref_t {
559 // IMP messenger;
560 // SEL name;
561 // };
562 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000563 // MessageRefCTy - clang type for struct _message_ref_t
564 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000565
566 // MessageRefPtrTy - LLVM for struct _message_ref_t*
567 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000568 // MessageRefCPtrTy - clang type for struct _message_ref_t*
569 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000570
Fariborz Jahanianef163782009-02-05 01:13:09 +0000571 // MessengerTy - Type of the messenger (shown as IMP above)
572 const llvm::FunctionType *MessengerTy;
573
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000574 // SuperMessageRefTy - LLVM for:
575 // struct _super_message_ref_t {
576 // SUPER_IMP messenger;
577 // SEL name;
578 // };
579 const llvm::StructType *SuperMessageRefTy;
580
581 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
582 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000583
Chris Lattner1c02f862009-04-22 02:53:24 +0000584 llvm::Constant *getMessageSendFixupFn() {
585 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
586 std::vector<const llvm::Type*> Params;
587 Params.push_back(ObjectPtrTy);
588 Params.push_back(MessageRefPtrTy);
589 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
590 Params, true),
591 "objc_msgSend_fixup");
592 }
593
594 llvm::Constant *getMessageSendFpretFixupFn() {
595 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
596 std::vector<const llvm::Type*> Params;
597 Params.push_back(ObjectPtrTy);
598 Params.push_back(MessageRefPtrTy);
599 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
600 Params, true),
601 "objc_msgSend_fpret_fixup");
602 }
603
604 llvm::Constant *getMessageSendStretFixupFn() {
605 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
606 std::vector<const llvm::Type*> Params;
607 Params.push_back(ObjectPtrTy);
608 Params.push_back(MessageRefPtrTy);
609 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
610 Params, true),
611 "objc_msgSend_stret_fixup");
612 }
613
614 llvm::Constant *getMessageSendIdFixupFn() {
615 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
616 std::vector<const llvm::Type*> Params;
617 Params.push_back(ObjectPtrTy);
618 Params.push_back(MessageRefPtrTy);
619 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
620 Params, true),
621 "objc_msgSendId_fixup");
622 }
623
624 llvm::Constant *getMessageSendIdStretFixupFn() {
625 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
626 std::vector<const llvm::Type*> Params;
627 Params.push_back(ObjectPtrTy);
628 Params.push_back(MessageRefPtrTy);
629 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
630 Params, true),
631 "objc_msgSendId_stret_fixup");
632 }
633 llvm::Constant *getMessageSendSuper2FixupFn() {
634 // id objc_msgSendSuper2_fixup (struct objc_super *,
635 // struct _super_message_ref_t*, ...)
636 std::vector<const llvm::Type*> Params;
637 Params.push_back(SuperPtrTy);
638 Params.push_back(SuperMessageRefPtrTy);
639 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
640 Params, true),
641 "objc_msgSendSuper2_fixup");
642 }
643
644 llvm::Constant *getMessageSendSuper2StretFixupFn() {
645 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
646 // struct _super_message_ref_t*, ...)
647 std::vector<const llvm::Type*> Params;
648 Params.push_back(SuperPtrTy);
649 Params.push_back(SuperMessageRefPtrTy);
650 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
651 Params, true),
652 "objc_msgSendSuper2_stret_fixup");
653 }
654
655
656
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000657 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
658 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000659 llvm::Value *getEHPersonalityPtr() {
660 llvm::Constant *Personality =
661 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
662 std::vector<const llvm::Type*>(),
663 true),
664 "__objc_personality_v0");
665 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
666 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000667
Chris Lattner8a569112009-04-22 02:15:23 +0000668 llvm::Constant *getUnwindResumeOrRethrowFn() {
669 std::vector<const llvm::Type*> Params;
670 Params.push_back(Int8PtrTy);
671 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
672 Params, false),
673 "_Unwind_Resume_or_Rethrow");
674 }
675
676 llvm::Constant *getObjCEndCatchFn() {
677 std::vector<const llvm::Type*> Params;
678 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
679 Params, false),
680 "objc_end_catch");
681
682 }
683
684 llvm::Constant *getObjCBeginCatchFn() {
685 std::vector<const llvm::Type*> Params;
686 Params.push_back(Int8PtrTy);
687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
688 Params, false),
689 "objc_begin_catch");
690 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000691
692 const llvm::StructType *EHTypeTy;
693 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000694
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000695 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
696 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697};
698
699class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000700public:
701 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000702 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000703 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000704 unsigned ivar_bytepos;
705 unsigned ivar_size;
706 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
707 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000708
709 // Allow sorting based on byte pos.
710 bool operator<(const GC_IVAR &b) const {
711 return ivar_bytepos < b.ivar_bytepos;
712 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000713 };
714
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000715 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000716 public:
717 unsigned skip;
718 unsigned scan;
719 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
720 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000721 };
722
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000723protected:
724 CodeGen::CodeGenModule &CGM;
725 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000726 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000727
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000728 // gc ivar layout bitmap calculation helper caches.
729 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
730 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000731
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000732 /// LazySymbols - Symbols to generate a lazy reference for. See
733 /// DefinedSymbols and FinishModule().
734 std::set<IdentifierInfo*> LazySymbols;
735
736 /// DefinedSymbols - External symbols which are defined by this
737 /// module. The symbols in this list and LazySymbols are used to add
738 /// special linker symbols which ensure that Objective-C modules are
739 /// linked properly.
740 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000741
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000742 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000743 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000744
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000745 /// MethodVarNames - uniqued method variable names.
746 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000747
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000748 /// MethodVarTypes - uniqued method type signatures. We have to use
749 /// a StringMap here because have no other unique reference.
750 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000751
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000752 /// MethodDefinitions - map of methods which have been defined in
753 /// this translation unit.
754 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000755
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000756 /// PropertyNames - uniqued method variable names.
757 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000758
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000759 /// ClassReferences - uniqued class references.
760 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000761
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000762 /// SelectorReferences - uniqued selector references.
763 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000764
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000765 /// Protocols - Protocols for which an objc_protocol structure has
766 /// been emitted. Forward declarations are handled by creating an
767 /// empty structure whose initializer is filled in when/if defined.
768 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000769
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000770 /// DefinedProtocols - Protocols which have actually been
771 /// defined. We should not need this, see FIXME in GenerateProtocol.
772 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000773
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000774 /// DefinedClasses - List of defined classes.
775 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000776
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000777 /// DefinedCategories - List of defined categories.
778 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000779
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000780 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000781 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000782 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000783
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000784 /// GetNameForMethod - Return a name for the given method.
785 /// \param[out] NameOut - The return value.
786 void GetNameForMethod(const ObjCMethodDecl *OMD,
787 const ObjCContainerDecl *CD,
788 std::string &NameOut);
789
790 /// GetMethodVarName - Return a unique constant for the given
791 /// selector's name. The return value has type char *.
792 llvm::Constant *GetMethodVarName(Selector Sel);
793 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
794 llvm::Constant *GetMethodVarName(const std::string &Name);
795
796 /// GetMethodVarType - Return a unique constant for the given
797 /// selector's name. The return value has type char *.
798
799 // FIXME: This is a horrible name.
800 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000801 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000802
803 /// GetPropertyName - Return a unique constant for the given
804 /// name. The return value has type char *.
805 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
806
807 // FIXME: This can be dropped once string functions are unified.
808 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
809 const Decl *Container);
810
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000811 /// GetClassName - Return a unique constant for the given selector's
812 /// name. The return value has type char *.
813 llvm::Constant *GetClassName(IdentifierInfo *Ident);
814
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000815 /// BuildIvarLayout - Builds ivar layout bitmap for the class
816 /// implementation for the __strong or __weak case.
817 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000818 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
819 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000820
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000821 void BuildAggrIvarRecordLayout(const RecordType *RT,
822 unsigned int BytePos, bool ForStrongLayout,
823 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000824 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000825 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000826 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000827 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000828 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000829 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000830
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000831 /// GetIvarLayoutName - Returns a unique constant for the given
832 /// ivar layout bitmap.
833 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
834 const ObjCCommonTypesHelper &ObjCTypes);
835
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000836 /// EmitPropertyList - Emit the given property list. The return
837 /// value has type PropertyListPtrTy.
838 llvm::Constant *EmitPropertyList(const std::string &Name,
839 const Decl *Container,
840 const ObjCContainerDecl *OCD,
841 const ObjCCommonTypesHelper &ObjCTypes);
842
Fariborz Jahanianda320092009-01-29 19:24:30 +0000843 /// GetProtocolRef - Return a reference to the internal protocol
844 /// description, creating an empty one if it has not been
845 /// defined. The return value has type ProtocolPtrTy.
846 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000847
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000848 /// CreateMetadataVar - Create a global variable with internal
849 /// linkage for use by the Objective-C runtime.
850 ///
851 /// This is a convenience wrapper which not only creates the
852 /// variable, but also sets the section and alignment and adds the
853 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000854 ///
855 /// \param Name - The variable name.
856 /// \param Init - The variable initializer; this is also used to
857 /// define the type of the variable.
858 /// \param Section - The section the variable should go into, or 0.
859 /// \param Align - The alignment for the variable, or 0.
860 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000861 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000862 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
863 llvm::Constant *Init,
864 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000865 unsigned Align,
866 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000867
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000868 /// GetNamedIvarList - Return the list of ivars in the interface
869 /// itself (not including super classes and not including unnamed
870 /// bitfields).
871 ///
872 /// For the non-fragile ABI, this also includes synthesized property
873 /// ivars.
874 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
875 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
876
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000877public:
878 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
879 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000880
Steve Naroff33fdb732009-03-31 16:53:37 +0000881 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000882
883 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
884 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000885
886 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
887
888 /// GetOrEmitProtocol - Get the protocol object for the given
889 /// declaration, emitting it if necessary. The return value has type
890 /// ProtocolPtrTy.
891 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
892
893 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
894 /// object for the given declaration, emitting it if needed. These
895 /// forward references will be filled in with empty bodies if no
896 /// definition is seen. The return value has type ProtocolPtrTy.
897 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000898};
899
900class CGObjCMac : public CGObjCCommonMac {
901private:
902 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000903 /// EmitImageInfo - Emit the image info marker used to encode some module
904 /// level information.
905 void EmitImageInfo();
906
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000907 /// EmitModuleInfo - Another marker encoding module level
908 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000909 void EmitModuleInfo();
910
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000911 /// EmitModuleSymols - Emit module symbols, the list of defined
912 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000913 llvm::Constant *EmitModuleSymbols();
914
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000915 /// FinishModule - Write out global data structures at the end of
916 /// processing a translation unit.
917 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000918
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000919 /// EmitClassExtension - Generate the class extension structure used
920 /// to store the weak ivar layout and properties. The return value
921 /// has type ClassExtensionPtrTy.
922 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
923
924 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
925 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000926 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000927 const ObjCInterfaceDecl *ID);
928
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000929 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000930 QualType ResultType,
931 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000932 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000933 QualType Arg0Ty,
934 bool IsSuper,
935 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000936
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000937 /// EmitIvarList - Emit the ivar list for the given
938 /// implementation. If ForClass is true the list of class ivars
939 /// (i.e. metaclass ivars) is emitted, otherwise the list of
940 /// interface ivars will be emitted. The return value has type
941 /// IvarListPtrTy.
942 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000943 bool ForClass);
944
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000945 /// EmitMetaClass - Emit a forward reference to the class structure
946 /// for the metaclass of the given interface. The return value has
947 /// type ClassPtrTy.
948 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
949
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000950 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000951 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000952 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
953 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000954 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000955
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000956 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000957
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000958 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000959
960 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000961 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000962 llvm::Constant *EmitMethodList(const std::string &Name,
963 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000964 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000965
966 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000967 /// method declarations.
968 /// - TypeName: The name for the type containing the methods.
969 /// - IsProtocol: True iff these methods are for a protocol.
970 /// - ClassMethds: True iff these are class methods.
971 /// - Required: When true, only "required" methods are
972 /// listed. Similarly, when false only "optional" methods are
973 /// listed. For classes this should always be true.
974 /// - begin, end: The method list to output.
975 ///
976 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000977 llvm::Constant *EmitMethodDescList(const std::string &Name,
978 const char *Section,
979 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000980
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000981 /// GetOrEmitProtocol - Get the protocol object for the given
982 /// declaration, emitting it if necessary. The return value has type
983 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000984 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000985
986 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
987 /// object for the given declaration, emitting it if needed. These
988 /// forward references will be filled in with empty bodies if no
989 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000990 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000991
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000992 /// EmitProtocolExtension - Generate the protocol extension
993 /// structure used to store optional instance and class methods, and
994 /// protocol properties. The return value has type
995 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000996 llvm::Constant *
997 EmitProtocolExtension(const ObjCProtocolDecl *PD,
998 const ConstantVector &OptInstanceMethods,
999 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001000
1001 /// EmitProtocolList - Generate the list of referenced
1002 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001003 llvm::Constant *EmitProtocolList(const std::string &Name,
1004 ObjCProtocolDecl::protocol_iterator begin,
1005 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001006
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001007 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1008 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001009 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001010
Fariborz Jahanianda320092009-01-29 19:24:30 +00001011 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001012 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001013
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001014 virtual llvm::Function *ModuleInitFunction();
1015
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001016 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001017 QualType ResultType,
1018 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001019 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001020 bool IsClassMessage,
1021 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001022
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001023 virtual CodeGen::RValue
1024 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001025 QualType ResultType,
1026 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001027 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001028 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001029 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001030 bool IsClassMessage,
1031 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001032
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001033 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001034 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001035
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001036 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001037
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001038 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001040 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001041
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001042 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001043 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001044
Chris Lattner74391b42009-03-22 21:03:39 +00001045 virtual llvm::Constant *GetPropertyGetFunction();
1046 virtual llvm::Constant *GetPropertySetFunction();
1047 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001048
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001049 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1050 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001051 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1052 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001053 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001054 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001055 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1056 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001057 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1058 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001059 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1060 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001061 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1062 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001063
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001064 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1065 QualType ObjectTy,
1066 llvm::Value *BaseValue,
1067 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001068 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001069 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001070 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001071 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001072};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001073
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001074class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001075private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001076 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001077 llvm::GlobalVariable* ObjCEmptyCacheVar;
1078 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001079
Daniel Dunbar11394522009-04-18 08:51:00 +00001080 /// SuperClassReferences - uniqued super class references.
1081 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1082
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001083 /// MetaClassReferences - uniqued meta class references.
1084 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001085
1086 /// EHTypeReferences - uniqued class ehtype references.
1087 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001088
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001089 /// FinishNonFragileABIModule - Write out global data structures at the end of
1090 /// processing a translation unit.
1091 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001092
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001093 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1094 unsigned InstanceStart,
1095 unsigned InstanceSize,
1096 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001097 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1098 llvm::Constant *IsAGV,
1099 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001100 llvm::Constant *ClassRoGV,
1101 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001102
1103 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1104
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001105 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1106
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001107 /// EmitMethodList - Emit the method list for the given
1108 /// implementation. The return value has type MethodListnfABITy.
1109 llvm::Constant *EmitMethodList(const std::string &Name,
1110 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001111 const ConstantVector &Methods);
1112 /// EmitIvarList - Emit the ivar list for the given
1113 /// implementation. If ForClass is true the list of class ivars
1114 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1115 /// interface ivars will be emitted. The return value has type
1116 /// IvarListnfABIPtrTy.
1117 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001118
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001119 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001120 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001121 unsigned long int offset);
1122
Fariborz Jahanianda320092009-01-29 19:24:30 +00001123 /// GetOrEmitProtocol - Get the protocol object for the given
1124 /// declaration, emitting it if necessary. The return value has type
1125 /// ProtocolPtrTy.
1126 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1127
1128 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1129 /// object for the given declaration, emitting it if needed. These
1130 /// forward references will be filled in with empty bodies if no
1131 /// definition is seen. The return value has type ProtocolPtrTy.
1132 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1133
1134 /// EmitProtocolList - Generate the list of referenced
1135 /// protocols. The return value has type ProtocolListPtrTy.
1136 llvm::Constant *EmitProtocolList(const std::string &Name,
1137 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001138 ObjCProtocolDecl::protocol_iterator end);
1139
1140 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1141 QualType ResultType,
1142 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001143 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001144 QualType Arg0Ty,
1145 bool IsSuper,
1146 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001147
1148 /// GetClassGlobal - Return the global variable for the Objective-C
1149 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001150 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1151
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001152 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001153 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001154 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001155 const ObjCInterfaceDecl *ID);
1156
1157 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1158 /// for the given super class reference.
1159 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1160 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001161
1162 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1163 /// meta-data
1164 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1165 const ObjCInterfaceDecl *ID);
1166
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001167 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1168 /// the given ivar.
1169 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001170 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001171 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001172 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001173
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001174 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1175 /// for the given selector.
1176 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001177
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001178 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001179 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001180 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1181 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001182
1183 const char *getMetaclassSymbolPrefix() const {
1184 return "OBJC_METACLASS_$_";
1185 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001186
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001187 const char *getClassSymbolPrefix() const {
1188 return "OBJC_CLASS_$_";
1189 }
1190
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001191 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001192 uint32_t &InstanceStart,
1193 uint32_t &InstanceSize);
1194
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001195public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001196 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001197 // FIXME. All stubs for now!
1198 virtual llvm::Function *ModuleInitFunction();
1199
1200 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1201 QualType ResultType,
1202 Selector Sel,
1203 llvm::Value *Receiver,
1204 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001205 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001206
1207 virtual CodeGen::RValue
1208 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1209 QualType ResultType,
1210 Selector Sel,
1211 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001212 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001213 llvm::Value *Receiver,
1214 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001215 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001216
1217 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001218 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001219
1220 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001221 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001222
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001223 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001224
1225 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001226 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001227 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001228
Chris Lattner74391b42009-03-22 21:03:39 +00001229 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001230 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001231 }
Chris Lattner74391b42009-03-22 21:03:39 +00001232 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001233 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001234 }
Chris Lattner74391b42009-03-22 21:03:39 +00001235 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001236 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001237 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001238
1239 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001240 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001241 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001242 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001243 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001244 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001245 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001246 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001247 virtual void EmitObjCGlobalAssign(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 EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001250 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001251 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001252 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001253 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1254 QualType ObjectTy,
1255 llvm::Value *BaseValue,
1256 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001257 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001258 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001259 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001260 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001261};
1262
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001263} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001264
1265/* *** Helper Functions *** */
1266
1267/// getConstantGEP() - Help routine to construct simple GEPs.
1268static llvm::Constant *getConstantGEP(llvm::Constant *C,
1269 unsigned idx0,
1270 unsigned idx1) {
1271 llvm::Value *Idxs[] = {
1272 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1273 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1274 };
1275 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1276}
1277
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001278/// hasObjCExceptionAttribute - Return true if this class or any super
1279/// class has the __objc_exception__ attribute.
1280static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001281 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001282 return true;
1283 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1284 return hasObjCExceptionAttribute(Super);
1285 return false;
1286}
1287
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001288/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001289
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001290CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1291 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001292{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001293 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001294 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001295}
1296
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001297/// GetClass - Return a reference to the class for the given interface
1298/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001299llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001300 const ObjCInterfaceDecl *ID) {
1301 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001302}
1303
1304/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001305llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001306 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001307}
1308
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001309/// Generate a constant CFString object.
1310/*
1311 struct __builtin_CFString {
1312 const int *isa; // point to __CFConstantStringClassReference
1313 int flags;
1314 const char *str;
1315 long length;
1316 };
1317*/
1318
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001319llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001320 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001321 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001322}
1323
1324/// Generates a message send where the super is the receiver. This is
1325/// a message send to self with special delivery semantics indicating
1326/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001327CodeGen::RValue
1328CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001329 QualType ResultType,
1330 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001331 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001332 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001333 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001334 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001335 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001336 // Create and init a super structure; this is a (receiver, class)
1337 // pair we will pass to objc_msgSendSuper.
1338 llvm::Value *ObjCSuper =
1339 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1340 llvm::Value *ReceiverAsObject =
1341 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1342 CGF.Builder.CreateStore(ReceiverAsObject,
1343 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001344
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001345 // If this is a class message the metaclass is passed as the target.
1346 llvm::Value *Target;
1347 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001348 if (isCategoryImpl) {
1349 // Message sent to 'super' in a class method defined in a category
1350 // implementation requires an odd treatment.
1351 // If we are in a class method, we must retrieve the
1352 // _metaclass_ for the current class, pointed at by
1353 // the class's "isa" pointer. The following assumes that
1354 // isa" is the first ivar in a class (which it must be).
1355 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1356 Target = CGF.Builder.CreateStructGEP(Target, 0);
1357 Target = CGF.Builder.CreateLoad(Target);
1358 }
1359 else {
1360 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1361 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1362 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1363 Target = Super;
1364 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001365 } else {
1366 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1367 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001368 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1369 // and ObjCTypes types.
1370 const llvm::Type *ClassTy =
1371 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001372 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001373 CGF.Builder.CreateStore(Target,
1374 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1375
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001376 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001377 ObjCSuper, ObjCTypes.SuperPtrCTy,
1378 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001379}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001380
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001381/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001382CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001383 QualType ResultType,
1384 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001385 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001386 bool IsClassMessage,
1387 const CallArgList &CallArgs) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001388 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001389 Receiver, CGF.getContext().getObjCIdType(),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001390 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001391}
1392
1393CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001394 QualType ResultType,
1395 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001396 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001397 QualType Arg0Ty,
1398 bool IsSuper,
1399 const CallArgList &CallArgs) {
1400 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001401 if (!IsSuper)
1402 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001403 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1404 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1405 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001406 CGF.getContext().getObjCSelType()));
1407 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001408
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001409 CodeGenTypes &Types = CGM.getTypes();
1410 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian65257ca2009-04-29 22:47:27 +00001411 // FIXME. vararg flag must be true when this API is used for 64bit code gen.
1412 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001413
1414 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001415 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001416 Fn = ObjCTypes.getSendStretFn(IsSuper);
1417 } else if (ResultType->isFloatingType()) {
1418 // FIXME: Sadly, this is wrong. This actually depends on the
1419 // architecture. This happens to be right for x86-32 though.
1420 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1421 } else {
1422 Fn = ObjCTypes.getSendFn(IsSuper);
1423 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001424 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001425 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001426}
1427
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001428llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001429 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001430 // FIXME: I don't understand why gcc generates this, or where it is
1431 // resolved. Investigate. Its also wasteful to look this up over and
1432 // over.
1433 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1434
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001435 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1436 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001437}
1438
Fariborz Jahanianda320092009-01-29 19:24:30 +00001439void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001440 // FIXME: We shouldn't need this, the protocol decl should contain
1441 // enough information to tell us whether this was a declaration or a
1442 // definition.
1443 DefinedProtocols.insert(PD->getIdentifier());
1444
1445 // If we have generated a forward reference to this protocol, emit
1446 // it now. Otherwise do nothing, the protocol objects are lazily
1447 // emitted.
1448 if (Protocols.count(PD->getIdentifier()))
1449 GetOrEmitProtocol(PD);
1450}
1451
Fariborz Jahanianda320092009-01-29 19:24:30 +00001452llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001453 if (DefinedProtocols.count(PD->getIdentifier()))
1454 return GetOrEmitProtocol(PD);
1455 return GetOrEmitProtocolRef(PD);
1456}
1457
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001458/*
1459 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1460 struct _objc_protocol {
1461 struct _objc_protocol_extension *isa;
1462 char *protocol_name;
1463 struct _objc_protocol_list *protocol_list;
1464 struct _objc__method_prototype_list *instance_methods;
1465 struct _objc__method_prototype_list *class_methods
1466 };
1467
1468 See EmitProtocolExtension().
1469*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001470llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1471 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1472
1473 // Early exit if a defining object has already been generated.
1474 if (Entry && Entry->hasInitializer())
1475 return Entry;
1476
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001477 // FIXME: I don't understand why gcc generates this, or where it is
1478 // resolved. Investigate. Its also wasteful to look this up over and
1479 // over.
1480 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1481
Chris Lattner8ec03f52008-11-24 03:54:41 +00001482 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001483
1484 // Construct method lists.
1485 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1486 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001487 for (ObjCProtocolDecl::instmeth_iterator
1488 i = PD->instmeth_begin(CGM.getContext()),
1489 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001490 ObjCMethodDecl *MD = *i;
1491 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1492 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1493 OptInstanceMethods.push_back(C);
1494 } else {
1495 InstanceMethods.push_back(C);
1496 }
1497 }
1498
Douglas Gregor6ab35242009-04-09 21:40:53 +00001499 for (ObjCProtocolDecl::classmeth_iterator
1500 i = PD->classmeth_begin(CGM.getContext()),
1501 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001502 ObjCMethodDecl *MD = *i;
1503 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1504 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1505 OptClassMethods.push_back(C);
1506 } else {
1507 ClassMethods.push_back(C);
1508 }
1509 }
1510
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001511 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001512 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001513 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001514 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001515 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001516 PD->protocol_begin(),
1517 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001518 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001519 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1520 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001521 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1522 InstanceMethods);
1523 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001524 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1525 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001526 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1527 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001528 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1529 Values);
1530
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001531 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001532 // Already created, fix the linkage and update the initializer.
1533 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001534 Entry->setInitializer(Init);
1535 } else {
1536 Entry =
1537 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1538 llvm::GlobalValue::InternalLinkage,
1539 Init,
1540 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1541 &CGM.getModule());
1542 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001543 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001544 UsedGlobals.push_back(Entry);
1545 // FIXME: Is this necessary? Why only for protocol?
1546 Entry->setAlignment(4);
1547 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001548
1549 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001550}
1551
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001552llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001553 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1554
1555 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001556 // We use the initializer as a marker of whether this is a forward
1557 // reference or not. At module finalization we add the empty
1558 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001559 Entry =
1560 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001561 llvm::GlobalValue::ExternalLinkage,
1562 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001563 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001564 &CGM.getModule());
1565 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001566 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001567 UsedGlobals.push_back(Entry);
1568 // FIXME: Is this necessary? Why only for protocol?
1569 Entry->setAlignment(4);
1570 }
1571
1572 return Entry;
1573}
1574
1575/*
1576 struct _objc_protocol_extension {
1577 uint32_t size;
1578 struct objc_method_description_list *optional_instance_methods;
1579 struct objc_method_description_list *optional_class_methods;
1580 struct objc_property_list *instance_properties;
1581 };
1582*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001583llvm::Constant *
1584CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1585 const ConstantVector &OptInstanceMethods,
1586 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001587 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001588 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001589 std::vector<llvm::Constant*> Values(4);
1590 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001591 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001592 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1593 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001594 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1595 OptInstanceMethods);
1596 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001597 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1598 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001599 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1600 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001601 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1602 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001603 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001604
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001605 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001606 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1607 Values[3]->isNullValue())
1608 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1609
1610 llvm::Constant *Init =
1611 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001612
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001613 // No special section, but goes in llvm.used
1614 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1615 Init,
1616 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001617}
1618
1619/*
1620 struct objc_protocol_list {
1621 struct objc_protocol_list *next;
1622 long count;
1623 Protocol *list[];
1624 };
1625*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001626llvm::Constant *
1627CGObjCMac::EmitProtocolList(const std::string &Name,
1628 ObjCProtocolDecl::protocol_iterator begin,
1629 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001630 std::vector<llvm::Constant*> ProtocolRefs;
1631
Daniel Dunbardbc933702008-08-21 21:57:41 +00001632 for (; begin != end; ++begin)
1633 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001634
1635 // Just return null for empty protocol lists
1636 if (ProtocolRefs.empty())
1637 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1638
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001639 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001640 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1641
1642 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001643 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001644 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1645 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1646 Values[2] =
1647 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1648 ProtocolRefs.size()),
1649 ProtocolRefs);
1650
1651 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1652 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001653 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001654 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001655 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1656}
1657
1658/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001659 struct _objc_property {
1660 const char * const name;
1661 const char * const attributes;
1662 };
1663
1664 struct _objc_property_list {
1665 uint32_t entsize; // sizeof (struct _objc_property)
1666 uint32_t prop_count;
1667 struct _objc_property[prop_count];
1668 };
1669*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001670llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1671 const Decl *Container,
1672 const ObjCContainerDecl *OCD,
1673 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001674 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001675 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1676 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001677 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001678 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001679 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001680 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1681 Prop));
1682 }
1683
1684 // Return null for empty list.
1685 if (Properties.empty())
1686 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1687
1688 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001689 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001690 std::vector<llvm::Constant*> Values(3);
1691 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1692 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1693 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1694 Properties.size());
1695 Values[2] = llvm::ConstantArray::get(AT, Properties);
1696 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1697
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001698 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001699 CreateMetadataVar(Name, Init,
1700 (ObjCABI == 2) ? "__DATA, __objc_const" :
1701 "__OBJC,__property,regular,no_dead_strip",
1702 (ObjCABI == 2) ? 8 : 4,
1703 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001704 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001705}
1706
1707/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001708 struct objc_method_description_list {
1709 int count;
1710 struct objc_method_description list[];
1711 };
1712*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001713llvm::Constant *
1714CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1715 std::vector<llvm::Constant*> Desc(2);
1716 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1717 ObjCTypes.SelectorPtrTy);
1718 Desc[1] = GetMethodVarType(MD);
1719 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1720 Desc);
1721}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001722
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001723llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1724 const char *Section,
1725 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001726 // Return null for empty list.
1727 if (Methods.empty())
1728 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1729
1730 std::vector<llvm::Constant*> Values(2);
1731 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1732 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1733 Methods.size());
1734 Values[1] = llvm::ConstantArray::get(AT, Methods);
1735 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1736
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001737 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001738 return llvm::ConstantExpr::getBitCast(GV,
1739 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001740}
1741
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001742/*
1743 struct _objc_category {
1744 char *category_name;
1745 char *class_name;
1746 struct _objc_method_list *instance_methods;
1747 struct _objc_method_list *class_methods;
1748 struct _objc_protocol_list *protocols;
1749 uint32_t size; // <rdar://4585769>
1750 struct _objc_property_list *instance_properties;
1751 };
1752 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001753void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001754 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001755
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001756 // FIXME: This is poor design, the OCD should have a pointer to the
1757 // category decl. Additionally, note that Category can be null for
1758 // the @implementation w/o an @interface case. Sema should just
1759 // create one for us as it does for @implementation so everyone else
1760 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001761 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001762 const ObjCCategoryDecl *Category =
1763 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001764 std::string ExtName(Interface->getNameAsString() + "_" +
1765 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001766
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001767 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001768 for (ObjCCategoryImplDecl::instmeth_iterator
1769 i = OCD->instmeth_begin(CGM.getContext()),
1770 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001771 // Instance methods should always be defined.
1772 InstanceMethods.push_back(GetMethodConstant(*i));
1773 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001774 for (ObjCCategoryImplDecl::classmeth_iterator
1775 i = OCD->classmeth_begin(CGM.getContext()),
1776 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001777 // Class methods should always be defined.
1778 ClassMethods.push_back(GetMethodConstant(*i));
1779 }
1780
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001781 std::vector<llvm::Constant*> Values(7);
1782 Values[0] = GetClassName(OCD->getIdentifier());
1783 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001784 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001785 Values[2] =
1786 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1787 ExtName,
1788 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001789 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001790 Values[3] =
1791 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001792 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001793 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001794 if (Category) {
1795 Values[4] =
1796 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1797 Category->protocol_begin(),
1798 Category->protocol_end());
1799 } else {
1800 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1801 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001802 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001803
1804 // If there is no category @interface then there can be no properties.
1805 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001806 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001807 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001808 } else {
1809 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1810 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001811
1812 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1813 Values);
1814
1815 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001816 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1817 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001818 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001819 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001820}
1821
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001822// FIXME: Get from somewhere?
1823enum ClassFlags {
1824 eClassFlags_Factory = 0x00001,
1825 eClassFlags_Meta = 0x00002,
1826 // <rdr://5142207>
1827 eClassFlags_HasCXXStructors = 0x02000,
1828 eClassFlags_Hidden = 0x20000,
1829 eClassFlags_ABI2_Hidden = 0x00010,
1830 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1831};
1832
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001833/*
1834 struct _objc_class {
1835 Class isa;
1836 Class super_class;
1837 const char *name;
1838 long version;
1839 long info;
1840 long instance_size;
1841 struct _objc_ivar_list *ivars;
1842 struct _objc_method_list *methods;
1843 struct _objc_cache *cache;
1844 struct _objc_protocol_list *protocols;
1845 // Objective-C 1.0 extensions (<rdr://4585769>)
1846 const char *ivar_layout;
1847 struct _objc_class_ext *ext;
1848 };
1849
1850 See EmitClassExtension();
1851 */
1852void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001853 DefinedSymbols.insert(ID->getIdentifier());
1854
Chris Lattner8ec03f52008-11-24 03:54:41 +00001855 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001856 // FIXME: Gross
1857 ObjCInterfaceDecl *Interface =
1858 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001859 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001860 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001861 Interface->protocol_begin(),
1862 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001863 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001864 unsigned Size =
1865 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001866
1867 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001868 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001869 Flags |= eClassFlags_Hidden;
1870
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001871 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001872 for (ObjCImplementationDecl::instmeth_iterator
1873 i = ID->instmeth_begin(CGM.getContext()),
1874 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001875 // Instance methods should always be defined.
1876 InstanceMethods.push_back(GetMethodConstant(*i));
1877 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001878 for (ObjCImplementationDecl::classmeth_iterator
1879 i = ID->classmeth_begin(CGM.getContext()),
1880 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001881 // Class methods should always be defined.
1882 ClassMethods.push_back(GetMethodConstant(*i));
1883 }
1884
Douglas Gregor653f1b12009-04-23 01:02:12 +00001885 for (ObjCImplementationDecl::propimpl_iterator
1886 i = ID->propimpl_begin(CGM.getContext()),
1887 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001888 ObjCPropertyImplDecl *PID = *i;
1889
1890 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1891 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1892
1893 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1894 if (llvm::Constant *C = GetMethodConstant(MD))
1895 InstanceMethods.push_back(C);
1896 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1897 if (llvm::Constant *C = GetMethodConstant(MD))
1898 InstanceMethods.push_back(C);
1899 }
1900 }
1901
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001902 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00001903 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001904 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001905 // Record a reference to the super class.
1906 LazySymbols.insert(Super->getIdentifier());
1907
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001908 Values[ 1] =
1909 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1910 ObjCTypes.ClassPtrTy);
1911 } else {
1912 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1913 }
1914 Values[ 2] = GetClassName(ID->getIdentifier());
1915 // Version is always 0.
1916 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1917 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1918 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001919 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001920 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001921 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001922 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001923 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001924 // cache is always NULL.
1925 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1926 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001927 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001928 Values[11] = EmitClassExtension(ID);
1929 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1930 Values);
1931
1932 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001933 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1934 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001935 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001936 DefinedClasses.push_back(GV);
1937}
1938
1939llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1940 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001941 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001942 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001943 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001944
Daniel Dunbar04d40782009-04-14 06:00:08 +00001945 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001946 Flags |= eClassFlags_Hidden;
1947
1948 std::vector<llvm::Constant*> Values(12);
1949 // The isa for the metaclass is the root of the hierarchy.
1950 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1951 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1952 Root = Super;
1953 Values[ 0] =
1954 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1955 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001956 // The super class for the metaclass is emitted as the name of the
1957 // super class. The runtime fixes this up to point to the
1958 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001959 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1960 Values[ 1] =
1961 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1962 ObjCTypes.ClassPtrTy);
1963 } else {
1964 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1965 }
1966 Values[ 2] = GetClassName(ID->getIdentifier());
1967 // Version is always 0.
1968 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1969 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1970 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001971 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001972 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001973 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001974 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001975 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001976 // cache is always NULL.
1977 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1978 Values[ 9] = Protocols;
1979 // ivar_layout for metaclass is always NULL.
1980 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1981 // The class extension is always unused for metaclasses.
1982 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1983 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1984 Values);
1985
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001986 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001987 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001988
1989 // Check for a forward reference.
1990 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1991 if (GV) {
1992 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1993 "Forward metaclass reference has incorrect type.");
1994 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1995 GV->setInitializer(Init);
1996 } else {
1997 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1998 llvm::GlobalValue::InternalLinkage,
1999 Init, Name,
2000 &CGM.getModule());
2001 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002002 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002003 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002004 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002005
2006 return GV;
2007}
2008
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002009llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002010 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002011
2012 // FIXME: Should we look these up somewhere other than the
2013 // module. Its a bit silly since we only generate these while
2014 // processing an implementation, so exactly one pointer would work
2015 // if know when we entered/exitted an implementation block.
2016
2017 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002018 // Previously, metaclass with internal linkage may have been defined.
2019 // pass 'true' as 2nd argument so it is returned.
2020 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002021 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2022 "Forward metaclass reference has incorrect type.");
2023 return GV;
2024 } else {
2025 // Generate as an external reference to keep a consistent
2026 // module. This will be patched up when we emit the metaclass.
2027 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2028 llvm::GlobalValue::ExternalLinkage,
2029 0,
2030 Name,
2031 &CGM.getModule());
2032 }
2033}
2034
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002035/*
2036 struct objc_class_ext {
2037 uint32_t size;
2038 const char *weak_ivar_layout;
2039 struct _objc_property_list *properties;
2040 };
2041*/
2042llvm::Constant *
2043CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2044 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002045 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002046
2047 std::vector<llvm::Constant*> Values(3);
2048 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002049 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002050 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002051 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002052
2053 // Return null if no extension bits are used.
2054 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2055 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2056
2057 llvm::Constant *Init =
2058 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002059 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002060 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2061 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002062}
2063
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002064/// getInterfaceDeclForIvar - Get the interface declaration node where
2065/// this ivar is declared in.
2066/// FIXME. Ideally, this info should be in the ivar node. But currently
2067/// it is not and prevailing wisdom is that ASTs should not have more
2068/// info than is absolutely needed, even though this info reflects the
2069/// source language.
2070///
2071static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2072 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002073 const ObjCIvarDecl *IVD,
2074 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002075 if (!OI)
2076 return 0;
2077 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2078 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2079 E = OI->ivar_end(); I != E; ++I)
2080 if ((*I)->getIdentifier() == IVD->getIdentifier())
2081 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002082 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002083 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2084 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002085 ObjCPropertyDecl *PDecl = (*I);
2086 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2087 if (IV->getIdentifier() == IVD->getIdentifier())
2088 return OI;
2089 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002090 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002091}
2092
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002093/*
2094 struct objc_ivar {
2095 char *ivar_name;
2096 char *ivar_type;
2097 int ivar_offset;
2098 };
2099
2100 struct objc_ivar_list {
2101 int ivar_count;
2102 struct objc_ivar list[count];
2103 };
2104 */
2105llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002106 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002107 std::vector<llvm::Constant*> Ivars, Ivar(3);
2108
2109 // When emitting the root class GCC emits ivar entries for the
2110 // actual class structure. It is not clear if we need to follow this
2111 // behavior; for now lets try and get away with not doing it. If so,
2112 // the cleanest solution would be to make up an ObjCInterfaceDecl
2113 // for the class.
2114 if (ForClass)
2115 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002116
2117 ObjCInterfaceDecl *OID =
2118 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002119
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002120 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2121 GetNamedIvarList(OID, OIvars);
2122
2123 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2124 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002125 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2126 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002127 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002128 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002129 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002130 }
2131
2132 // Return null for empty list.
2133 if (Ivars.empty())
2134 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2135
2136 std::vector<llvm::Constant*> Values(2);
2137 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2138 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2139 Ivars.size());
2140 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2141 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2142
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002143 llvm::GlobalVariable *GV;
2144 if (ForClass)
2145 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002146 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2147 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002148 else
2149 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2150 + ID->getNameAsString(),
2151 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002152 4, true);
2153 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002154}
2155
2156/*
2157 struct objc_method {
2158 SEL method_name;
2159 char *method_types;
2160 void *method;
2161 };
2162
2163 struct objc_method_list {
2164 struct objc_method_list *obsolete;
2165 int count;
2166 struct objc_method methods_list[count];
2167 };
2168*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002169
2170/// GetMethodConstant - Return a struct objc_method constant for the
2171/// given method if it has been defined. The result is null if the
2172/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002173llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002174 // FIXME: Use DenseMap::lookup
2175 llvm::Function *Fn = MethodDefinitions[MD];
2176 if (!Fn)
2177 return 0;
2178
2179 std::vector<llvm::Constant*> Method(3);
2180 Method[0] =
2181 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2182 ObjCTypes.SelectorPtrTy);
2183 Method[1] = GetMethodVarType(MD);
2184 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2185 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2186}
2187
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002188llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2189 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002190 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002191 // Return null for empty list.
2192 if (Methods.empty())
2193 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2194
2195 std::vector<llvm::Constant*> Values(3);
2196 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2197 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2198 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2199 Methods.size());
2200 Values[2] = llvm::ConstantArray::get(AT, Methods);
2201 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2202
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002203 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002204 return llvm::ConstantExpr::getBitCast(GV,
2205 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002206}
2207
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002208llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002209 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002210 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002211 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002212
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002213 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002214 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002215 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002216 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002217 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002218 llvm::GlobalValue::InternalLinkage,
2219 Name,
2220 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002221 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002222
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002223 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002224}
2225
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002226llvm::GlobalVariable *
2227CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2228 llvm::Constant *Init,
2229 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002230 unsigned Align,
2231 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002232 const llvm::Type *Ty = Init->getType();
2233 llvm::GlobalVariable *GV =
2234 new llvm::GlobalVariable(Ty, false,
2235 llvm::GlobalValue::InternalLinkage,
2236 Init,
2237 Name,
2238 &CGM.getModule());
2239 if (Section)
2240 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002241 if (Align)
2242 GV->setAlignment(Align);
2243 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002244 UsedGlobals.push_back(GV);
2245 return GV;
2246}
2247
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002248llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002249 // Abuse this interface function as a place to finalize.
2250 FinishModule();
2251
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002252 return NULL;
2253}
2254
Chris Lattner74391b42009-03-22 21:03:39 +00002255llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002256 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002257}
2258
Chris Lattner74391b42009-03-22 21:03:39 +00002259llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002260 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002261}
2262
Chris Lattner74391b42009-03-22 21:03:39 +00002263llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002264 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002265}
2266
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002267/*
2268
2269Objective-C setjmp-longjmp (sjlj) Exception Handling
2270--
2271
2272The basic framework for a @try-catch-finally is as follows:
2273{
2274 objc_exception_data d;
2275 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002276 bool _call_try_exit = true;
2277
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002278 objc_exception_try_enter(&d);
2279 if (!setjmp(d.jmp_buf)) {
2280 ... try body ...
2281 } else {
2282 // exception path
2283 id _caught = objc_exception_extract(&d);
2284
2285 // enter new try scope for handlers
2286 if (!setjmp(d.jmp_buf)) {
2287 ... match exception and execute catch blocks ...
2288
2289 // fell off end, rethrow.
2290 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002291 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002292 } else {
2293 // exception in catch block
2294 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002295 _call_try_exit = false;
2296 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002297 }
2298 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002299 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002300
2301finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002302 if (_call_try_exit)
2303 objc_exception_try_exit(&d);
2304
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002305 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002306 ... dispatch to finally destination ...
2307
2308finally_rethrow:
2309 objc_exception_throw(_rethrow);
2310
2311finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002312}
2313
2314This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002315uses _rethrow to determine if objc_exception_try_exit should be called
2316and if the object should be rethrown. This breaks in the face of
2317throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002318
2319We specialize this framework for a few particular circumstances:
2320
2321 - If there are no catch blocks, then we avoid emitting the second
2322 exception handling context.
2323
2324 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2325 e)) we avoid emitting the code to rethrow an uncaught exception.
2326
2327 - FIXME: If there is no @finally block we can do a few more
2328 simplifications.
2329
2330Rethrows and Jumps-Through-Finally
2331--
2332
2333Support for implicit rethrows and jumping through the finally block is
2334handled by storing the current exception-handling context in
2335ObjCEHStack.
2336
Daniel Dunbar898d5082008-09-30 01:06:03 +00002337In order to implement proper @finally semantics, we support one basic
2338mechanism for jumping through the finally block to an arbitrary
2339destination. Constructs which generate exits from a @try or @catch
2340block use this mechanism to implement the proper semantics by chaining
2341jumps, as necessary.
2342
2343This mechanism works like the one used for indirect goto: we
2344arbitrarily assign an ID to each destination and store the ID for the
2345destination in a variable prior to entering the finally block. At the
2346end of the finally block we simply create a switch to the proper
2347destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002348
2349Code gen for @synchronized(expr) stmt;
2350Effectively generating code for:
2351objc_sync_enter(expr);
2352@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002353*/
2354
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002355void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2356 const Stmt &S) {
2357 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002358 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002359 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002360 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002361 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2362 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2363 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002364
2365 // For @synchronized, call objc_sync_enter(sync.expr). The
2366 // evaluation of the expression must occur before we enter the
2367 // @synchronized. We can safely avoid a temp here because jumps into
2368 // @synchronized are illegal & this will dominate uses.
2369 llvm::Value *SyncArg = 0;
2370 if (!isTry) {
2371 SyncArg =
2372 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2373 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002374 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002375 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002376
2377 // Push an EH context entry, used for handling rethrows and jumps
2378 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002379 CGF.PushCleanupBlock(FinallyBlock);
2380
Anders Carlsson273558f2009-02-07 21:37:21 +00002381 CGF.ObjCEHValueStack.push_back(0);
2382
Daniel Dunbar898d5082008-09-30 01:06:03 +00002383 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002384 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2385 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002386 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2387 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002388 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2389 "_call_try_exit");
2390 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2391
Anders Carlsson80f25672008-09-09 17:59:25 +00002392 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002393 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002394 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2395 "jmpbufarray");
2396 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002397 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002398 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002399
Daniel Dunbar55e87422008-11-11 02:29:29 +00002400 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2401 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002402 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002403 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002404
2405 // Emit the @try block.
2406 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002407 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2408 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002409 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002410
2411 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002412 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002413
2414 // Retrieve the exception object. We may emit multiple blocks but
2415 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002416 llvm::Value *Caught =
2417 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2418 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002419 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002420 if (!isTry)
2421 {
2422 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002423 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002424 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002425 }
2426 else if (const ObjCAtCatchStmt* CatchStmt =
2427 cast<ObjCAtTryStmt>(S).getCatchStmts())
2428 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002429 // Enter a new exception try block (in case a @catch block throws
2430 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002431 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002432
Chris Lattner34b02a12009-04-22 02:26:14 +00002433 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002434 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002435 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002436
Daniel Dunbar55e87422008-11-11 02:29:29 +00002437 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2438 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002439 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002440
2441 CGF.EmitBlock(CatchBlock);
2442
Daniel Dunbar55e40722008-09-27 07:03:52 +00002443 // Handle catch list. As a special case we check if everything is
2444 // matched and avoid generating code for falling off the end if
2445 // so.
2446 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002447 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002448 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002449
Steve Naroff7ba138a2009-03-03 19:52:17 +00002450 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002451 const PointerType *PT = 0;
2452
Anders Carlsson80f25672008-09-09 17:59:25 +00002453 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002454 if (!CatchParam) {
2455 AllMatched = true;
2456 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002457 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002458
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002459 // catch(id e) always matches.
2460 // FIXME: For the time being we also match id<X>; this should
2461 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002462 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002463 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002464 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002465 }
2466
Daniel Dunbar55e40722008-09-27 07:03:52 +00002467 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002468 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002469 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002470 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002471 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002472 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002473
Anders Carlssondde0a942008-09-11 09:15:33 +00002474 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002475 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002476 break;
2477 }
2478
Daniel Dunbar129271a2008-09-27 07:36:24 +00002479 assert(PT && "Unexpected non-pointer type in @catch");
2480 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002481 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002482 assert(ObjCType && "Catch parameter must have Objective-C type!");
2483
2484 // Check if the @catch block matches the exception object.
2485 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2486
Chris Lattner34b02a12009-04-22 02:26:14 +00002487 llvm::Value *Match =
2488 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2489 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002490
Daniel Dunbar55e87422008-11-11 02:29:29 +00002491 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002492
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002493 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002494 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002495
2496 // Emit the @catch block.
2497 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002498 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002499 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002500
2501 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002502 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002503 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002504 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002505
2506 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002507 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002508
2509 CGF.EmitBlock(NextCatchBlock);
2510 }
2511
Daniel Dunbar55e40722008-09-27 07:03:52 +00002512 if (!AllMatched) {
2513 // None of the handlers caught the exception, so store it to be
2514 // rethrown at the end of the @finally block.
2515 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002516 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002517 }
2518
2519 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002520 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002521 CGF.Builder.CreateStore(
2522 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2523 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002524 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002525 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002526 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002527 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002528 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002529 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002530 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002531 }
2532
Daniel Dunbar898d5082008-09-30 01:06:03 +00002533 // Pop the exception-handling stack entry. It is important to do
2534 // this now, because the code in the @finally block is not in this
2535 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002536 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2537
Anders Carlsson273558f2009-02-07 21:37:21 +00002538 CGF.ObjCEHValueStack.pop_back();
2539
Anders Carlsson80f25672008-09-09 17:59:25 +00002540 // Emit the @finally block.
2541 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002542 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2543
2544 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2545
2546 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002547 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002548
2549 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002550 if (isTry) {
2551 if (const ObjCAtFinallyStmt* FinallyStmt =
2552 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2553 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002554 } else {
2555 // Emit objc_sync_exit(expr); as finally's sole statement for
2556 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002557 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002558 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002559
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002560 // Emit the switch block
2561 if (Info.SwitchBlock)
2562 CGF.EmitBlock(Info.SwitchBlock);
2563 if (Info.EndBlock)
2564 CGF.EmitBlock(Info.EndBlock);
2565
Daniel Dunbar898d5082008-09-30 01:06:03 +00002566 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002567 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002568 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002569 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002570
2571 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002572}
2573
2574void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002575 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002576 llvm::Value *ExceptionAsObject;
2577
2578 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2579 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2580 ExceptionAsObject =
2581 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2582 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002583 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002584 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002585 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002586 }
2587
Chris Lattnerbbccd612009-04-22 02:38:11 +00002588 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002589 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002590
2591 // Clear the insertion point to indicate we are in unreachable code.
2592 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002593}
2594
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002595/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002596/// object: objc_read_weak (id *src)
2597///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002598llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002599 llvm::Value *AddrWeakObj)
2600{
Eli Friedman8339b352009-03-07 03:57:15 +00002601 const llvm::Type* DestTy =
2602 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002603 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002604 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002605 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002606 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002607 return read_weak;
2608}
2609
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002610/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2611/// objc_assign_weak (id src, id *dst)
2612///
2613void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2614 llvm::Value *src, llvm::Value *dst)
2615{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002616 const llvm::Type * SrcTy = src->getType();
2617 if (!isa<llvm::PointerType>(SrcTy)) {
2618 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2619 assert(Size <= 8 && "does not support size > 8");
2620 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2621 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002622 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2623 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002624 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2625 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002626 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002627 src, dst, "weakassign");
2628 return;
2629}
2630
Fariborz Jahanian58626502008-11-19 00:59:10 +00002631/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2632/// objc_assign_global (id src, id *dst)
2633///
2634void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2635 llvm::Value *src, llvm::Value *dst)
2636{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002637 const llvm::Type * SrcTy = src->getType();
2638 if (!isa<llvm::PointerType>(SrcTy)) {
2639 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2640 assert(Size <= 8 && "does not support size > 8");
2641 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2642 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002643 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2644 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002645 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2646 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002647 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002648 src, dst, "globalassign");
2649 return;
2650}
2651
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002652/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2653/// objc_assign_ivar (id src, id *dst)
2654///
2655void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2656 llvm::Value *src, llvm::Value *dst)
2657{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002658 const llvm::Type * SrcTy = src->getType();
2659 if (!isa<llvm::PointerType>(SrcTy)) {
2660 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2661 assert(Size <= 8 && "does not support size > 8");
2662 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2663 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002664 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2665 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002666 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2667 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002668 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002669 src, dst, "assignivar");
2670 return;
2671}
2672
Fariborz Jahanian58626502008-11-19 00:59:10 +00002673/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2674/// objc_assign_strongCast (id src, id *dst)
2675///
2676void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2677 llvm::Value *src, llvm::Value *dst)
2678{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002679 const llvm::Type * SrcTy = src->getType();
2680 if (!isa<llvm::PointerType>(SrcTy)) {
2681 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2682 assert(Size <= 8 && "does not support size > 8");
2683 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2684 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002685 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2686 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002687 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2688 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002689 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002690 src, dst, "weakassign");
2691 return;
2692}
2693
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002694/// EmitObjCValueForIvar - Code Gen for ivar reference.
2695///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002696LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2697 QualType ObjectTy,
2698 llvm::Value *BaseValue,
2699 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002700 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002701 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002702 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2703 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002704}
2705
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002706llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002707 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002708 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002709 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002710 return llvm::ConstantInt::get(
2711 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2712 Offset);
2713}
2714
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002715/* *** Private Interface *** */
2716
2717/// EmitImageInfo - Emit the image info marker used to encode some module
2718/// level information.
2719///
2720/// See: <rdr://4810609&4810587&4810587>
2721/// struct IMAGE_INFO {
2722/// unsigned version;
2723/// unsigned flags;
2724/// };
2725enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002726 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2727 // this implies.
2728 eImageInfo_GarbageCollected = (1 << 1),
2729 eImageInfo_GCOnly = (1 << 2),
2730 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2731
2732 // A flag indicating that the module has no instances of an
2733 // @synthesize of a superclass variable. <rdar://problem/6803242>
2734 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002735};
2736
2737void CGObjCMac::EmitImageInfo() {
2738 unsigned version = 0; // Version is unused?
2739 unsigned flags = 0;
2740
2741 // FIXME: Fix and continue?
2742 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2743 flags |= eImageInfo_GarbageCollected;
2744 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2745 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002746
2747 // We never allow @synthesize of a superclass property.
2748 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002749
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002750 // Emitted as int[2];
2751 llvm::Constant *values[2] = {
2752 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2753 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2754 };
2755 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002756
2757 const char *Section;
2758 if (ObjCABI == 1)
2759 Section = "__OBJC, __image_info,regular";
2760 else
2761 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002762 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002763 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2764 llvm::ConstantArray::get(AT, values, 2),
2765 Section,
2766 0,
2767 true);
2768 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002769}
2770
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002771
2772// struct objc_module {
2773// unsigned long version;
2774// unsigned long size;
2775// const char *name;
2776// Symtab symtab;
2777// };
2778
2779// FIXME: Get from somewhere
2780static const int ModuleVersion = 7;
2781
2782void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002783 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002784
2785 std::vector<llvm::Constant*> Values(4);
2786 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2787 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002788 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002789 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002790 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002791 CreateMetadataVar("\01L_OBJC_MODULES",
2792 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2793 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002794 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002795}
2796
2797llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002798 unsigned NumClasses = DefinedClasses.size();
2799 unsigned NumCategories = DefinedCategories.size();
2800
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002801 // Return null if no symbols were defined.
2802 if (!NumClasses && !NumCategories)
2803 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2804
2805 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002806 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2807 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2808 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2809 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2810
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002811 // The runtime expects exactly the list of defined classes followed
2812 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002813 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002814 for (unsigned i=0; i<NumClasses; i++)
2815 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2816 ObjCTypes.Int8PtrTy);
2817 for (unsigned i=0; i<NumCategories; i++)
2818 Symbols[NumClasses + i] =
2819 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2820 ObjCTypes.Int8PtrTy);
2821
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002822 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002823 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002824 NumClasses + NumCategories),
2825 Symbols);
2826
2827 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2828
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002829 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002830 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2831 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002832 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002833 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2834}
2835
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002836llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002837 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002838 LazySymbols.insert(ID->getIdentifier());
2839
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002840 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2841
2842 if (!Entry) {
2843 llvm::Constant *Casted =
2844 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2845 ObjCTypes.ClassPtrTy);
2846 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002847 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2848 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002849 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002850 }
2851
2852 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002853}
2854
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002855llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002856 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2857
2858 if (!Entry) {
2859 llvm::Constant *Casted =
2860 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2861 ObjCTypes.SelectorPtrTy);
2862 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002863 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2864 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002865 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002866 }
2867
2868 return Builder.CreateLoad(Entry, false, "tmp");
2869}
2870
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002871llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002872 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002873
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002874 if (!Entry)
2875 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2876 llvm::ConstantArray::get(Ident->getName()),
2877 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002878 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002879
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002880 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002881}
2882
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002883/// GetIvarLayoutName - Returns a unique constant for the given
2884/// ivar layout bitmap.
2885llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2886 const ObjCCommonTypesHelper &ObjCTypes) {
2887 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2888}
2889
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002890static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2891 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002892 if (FQT.isObjCGCStrong())
2893 return QualType::Strong;
2894
2895 if (FQT.isObjCGCWeak())
2896 return QualType::Weak;
2897
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002898 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002899 return QualType::Strong;
2900
2901 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002902 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002903
2904 return QualType::GCNone;
2905}
2906
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002907void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2908 unsigned int BytePos,
2909 bool ForStrongLayout,
2910 bool &HasUnion) {
2911 const RecordDecl *RD = RT->getDecl();
2912 // FIXME - Use iterator.
2913 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2914 RD->field_end(CGM.getContext()));
2915 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2916 const llvm::StructLayout *RecLayout =
2917 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2918
2919 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2920 ForStrongLayout, HasUnion);
2921}
2922
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002923void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002924 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002925 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002926 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002927 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002928 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002929 bool IsUnion = (RD && RD->isUnion());
2930 uint64_t MaxUnionIvarSize = 0;
2931 uint64_t MaxSkippedUnionIvarSize = 0;
2932 FieldDecl *MaxField = 0;
2933 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002934 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00002935 uint64_t MaxFieldOffset = 0;
2936 uint64_t MaxSkippedFieldOffset = 0;
2937 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002938
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002939 if (RecFields.empty())
2940 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00002941 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2942 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2943
Chris Lattnerf1690852009-03-31 08:48:01 +00002944 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002945 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00002946 uint64_t FieldOffset;
2947 if (RD)
2948 FieldOffset =
2949 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2950 else
2951 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002952
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002953 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002954 if (!Field->getIdentifier() || Field->isBitField()) {
2955 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00002956 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002957 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002958 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002959
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002960 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002961 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002962 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002963 if (FQT->isUnionType())
2964 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002965
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002966 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002967 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002968 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002969 continue;
2970 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002971
2972 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002973 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002974 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002975 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002976 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002977 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002978 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2979 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002980 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002981 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002982 FQT = CArray->getElementType();
2983 }
2984
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002985 assert(!FQT->isUnionType() &&
2986 "layout for array of unions not supported");
2987 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002988 int OldIndex = IvarsInfo.size() - 1;
2989 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002990
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002991 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002992 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002993 ForStrongLayout, HasUnion);
2994
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002995 // Replicate layout information for each array element. Note that
2996 // one element is already done.
2997 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002998 for (int FirstIndex = IvarsInfo.size() - 1,
2999 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003000 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003001 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3002 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3003 IvarsInfo[i].ivar_size));
3004 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3005 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3006 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003007 }
3008 continue;
3009 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003010 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003011 // At this point, we are done with Record/Union and array there of.
3012 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003013 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003014
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003015 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003016 if ((ForStrongLayout && GCAttr == QualType::Strong)
3017 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003018 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003019 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003020 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003021 MaxUnionIvarSize = UnionIvarSize;
3022 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003023 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003024 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003025 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003026 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003027 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003028 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003029 } else if ((ForStrongLayout &&
3030 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3031 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3032 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003033 // FIXME: Why the asymmetry? We divide by word size in bits on
3034 // other side.
3035 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003036 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003037 MaxSkippedUnionIvarSize = UnionIvarSize;
3038 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003039 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003040 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003041 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003042 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003043 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003044 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003045 }
3046 }
3047 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003048
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003049 if (LastFieldBitfield) {
3050 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003051 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3052 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003053 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003054 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003055 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003056 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3057 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003058 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003059 }
3060
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003061 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003062 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003063 MaxUnionIvarSize));
3064 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003065 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003066 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003067}
3068
3069/// BuildIvarLayout - Builds ivar layout bitmap for the class
3070/// implementation for the __strong or __weak case.
3071/// The layout map displays which words in ivar list must be skipped
3072/// and which must be scanned by GC (see below). String is built of bytes.
3073/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3074/// of words to skip and right nibble is count of words to scan. So, each
3075/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3076/// represented by a 0x00 byte which also ends the string.
3077/// 1. when ForStrongLayout is true, following ivars are scanned:
3078/// - id, Class
3079/// - object *
3080/// - __strong anything
3081///
3082/// 2. When ForStrongLayout is false, following ivars are scanned:
3083/// - __weak anything
3084///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003085llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003086 const ObjCImplementationDecl *OMD,
3087 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003088 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003089
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003090 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003091 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3092 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3093 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003094
Chris Lattnerf1690852009-03-31 08:48:01 +00003095 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003096 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003097 CGM.getContext().CollectObjCIvars(OI, RecFields);
Daniel Dunbar37153282009-05-04 04:10:48 +00003098
3099 // Add this implementations synthesized ivars.
3100 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(CGM.getContext()),
3101 E = OI->prop_end(CGM.getContext()); I != E; ++I) {
3102 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
3103 RecFields.push_back(cast<FieldDecl>(IV));
3104 }
3105
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003106 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003107 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003108
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003109 SkipIvars.clear();
3110 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003111
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003112 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003113 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003114 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003115
3116 // Sort on byte position in case we encounterred a union nested in
3117 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003118 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003119 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003120 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003121 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003122
3123 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003124 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003125 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003126 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003127 if (IvarsInfo[0].ivar_bytepos == 0) {
3128 WordsToSkip = 0;
3129 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003130 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003131 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3132 WordsToScan = IvarsInfo[0].ivar_size;
3133 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003134 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003135 unsigned int TailPrevGCObjC =
3136 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003137 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003138 // consecutive 'scanned' object pointers.
3139 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003140 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003141 // Skip over 'gc'able object pointer which lay over each other.
3142 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3143 continue;
3144 // Must skip over 1 or more words. We save current skip/scan values
3145 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003146 SKIP_SCAN SkScan;
3147 SkScan.skip = WordsToSkip;
3148 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003149 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003150
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003151 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003152 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3153 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003154 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003155 WordsToSkip = 0;
3156 WordsToScan = IvarsInfo[i].ivar_size;
3157 }
3158 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003159 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003160 SKIP_SCAN SkScan;
3161 SkScan.skip = WordsToSkip;
3162 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003163 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003164 }
3165
3166 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003167 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003168 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003169 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003170 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3171 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003172 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003173 IvarsInfo[LastIndex].ivar_bytepos +
3174 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003175 BytesSkipped = (LastByteSkipped > LastByteScanned);
3176 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003177 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003178 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003179 SKIP_SCAN SkScan;
3180 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3181 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003182 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003183 }
3184 }
3185 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3186 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003187 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003188 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003189 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3190 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3191 // 0xM0 followed by 0x0N detected.
3192 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3193 for (int j = i+1; j < SkipScan; j++)
3194 SkipScanIvars[j] = SkipScanIvars[j+1];
3195 --SkipScan;
3196 }
3197 }
3198
3199 // Generate the string.
3200 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003201 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003202 unsigned char byte;
3203 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3204 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3205 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3206 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3207
3208 if (skip_small > 0 || skip_big > 0)
3209 BytesSkipped = true;
3210 // first skip big.
3211 for (unsigned int ix = 0; ix < skip_big; ix++)
3212 BitMap += (unsigned char)(0xf0);
3213
3214 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003215 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003216 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003217 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003218 byte |= 0xf;
3219 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003220 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003221 byte |= scan_small;
3222 scan_small = 0;
3223 }
3224 BitMap += byte;
3225 }
3226 // next scan big
3227 for (unsigned int ix = 0; ix < scan_big; ix++)
3228 BitMap += (unsigned char)(0x0f);
3229 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003230 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003231 byte = scan_small;
3232 BitMap += byte;
3233 }
3234 }
3235 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003236 unsigned char zero = 0;
3237 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003238
3239 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3240 printf("\n%s ivar layout for class '%s': ",
3241 ForStrongLayout ? "strong" : "weak",
3242 OMD->getClassInterface()->getNameAsCString());
3243 const unsigned char *s = (unsigned char*)BitMap.c_str();
3244 for (unsigned i = 0; i < BitMap.size(); i++)
3245 if (!(s[i] & 0xf0))
3246 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3247 else
3248 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3249 printf("\n");
3250 }
3251
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003252 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3253 // final layout.
3254 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003255 return llvm::Constant::getNullValue(PtrTy);
3256 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3257 llvm::ConstantArray::get(BitMap.c_str()),
3258 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003259 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003260 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003261}
3262
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003263llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003264 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3265
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003266 // FIXME: Avoid std::string copying.
3267 if (!Entry)
3268 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3269 llvm::ConstantArray::get(Sel.getAsString()),
3270 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003271 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003272
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003273 return getConstantGEP(Entry, 0, 0);
3274}
3275
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003276// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003277llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003278 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3279}
3280
3281// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003282llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003283 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3284}
3285
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003286llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003287 std::string TypeStr;
3288 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3289
3290 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003291
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003292 if (!Entry)
3293 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3294 llvm::ConstantArray::get(TypeStr),
3295 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003296 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003297
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003298 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003299}
3300
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003301llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003302 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003303 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3304 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003305
3306 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3307
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003308 if (!Entry)
3309 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3310 llvm::ConstantArray::get(TypeStr),
3311 "__TEXT,__cstring,cstring_literals",
3312 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003313
3314 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003315}
3316
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003317// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003318llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003319 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3320
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003321 if (!Entry)
3322 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3323 llvm::ConstantArray::get(Ident->getName()),
3324 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003325 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003326
3327 return getConstantGEP(Entry, 0, 0);
3328}
3329
3330// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003331// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003332llvm::Constant *
3333 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3334 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003335 std::string TypeStr;
3336 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003337 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3338}
3339
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003340void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3341 const ObjCContainerDecl *CD,
3342 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003343 NameOut = '\01';
3344 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003345 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003346 assert (CD && "Missing container decl in GetNameForMethod");
3347 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003348 if (const ObjCCategoryImplDecl *CID =
3349 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3350 NameOut += '(';
3351 NameOut += CID->getNameAsString();
3352 NameOut+= ')';
3353 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003354 NameOut += ' ';
3355 NameOut += D->getSelector().getAsString();
3356 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003357}
3358
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003359void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003360 EmitModuleInfo();
3361
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003362 // Emit the dummy bodies for any protocols which were referenced but
3363 // never defined.
3364 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3365 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3366 if (i->second->hasInitializer())
3367 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003368
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003369 std::vector<llvm::Constant*> Values(5);
3370 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3371 Values[1] = GetClassName(i->first);
3372 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3373 Values[3] = Values[4] =
3374 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3375 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3376 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3377 Values));
3378 }
3379
3380 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003381 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003382 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003383 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003384 }
3385
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003386 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003387 llvm::GlobalValue *GV =
3388 new llvm::GlobalVariable(AT, false,
3389 llvm::GlobalValue::AppendingLinkage,
3390 llvm::ConstantArray::get(AT, Used),
3391 "llvm.used",
3392 &CGM.getModule());
3393
3394 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003395
3396 // Add assembler directives to add lazy undefined symbol references
3397 // for classes which are referenced but not defined. This is
3398 // important for correct linker interaction.
3399
3400 // FIXME: Uh, this isn't particularly portable.
3401 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003402
3403 if (!CGM.getModule().getModuleInlineAsm().empty())
3404 s << "\n";
3405
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003406 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3407 e = LazySymbols.end(); i != e; ++i) {
3408 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3409 }
3410 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3411 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003412 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003413 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3414 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003415
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003416 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003417}
3418
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003419CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003420 : CGObjCCommonMac(cgm),
3421 ObjCTypes(cgm)
3422{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003423 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003424 ObjCABI = 2;
3425}
3426
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003427/* *** */
3428
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003429ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3430: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003431{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003432 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3433 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003434
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003435 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003436 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003437 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003438 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003439 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3440
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003441 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003442 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003443 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003444
3445 // FIXME: It would be nice to unify this with the opaque type, so
3446 // that the IR comes out a bit cleaner.
3447 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3448 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003449
3450 // I'm not sure I like this. The implicit coordination is a bit
3451 // gross. We should solve this in a reasonable fashion because this
3452 // is a pretty common task (match some runtime data structure with
3453 // an LLVM data structure).
3454
3455 // FIXME: This is leaked.
3456 // FIXME: Merge with rewriter code?
3457
3458 // struct _objc_super {
3459 // id self;
3460 // Class cls;
3461 // }
3462 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3463 SourceLocation(),
3464 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003465 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3466 Ctx.getObjCIdType(), 0, false));
3467 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3468 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003469 RD->completeDefinition(Ctx);
3470
3471 SuperCTy = Ctx.getTagDeclType(RD);
3472 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3473
3474 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003475 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3476
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003477 // struct _prop_t {
3478 // char *name;
3479 // char *attributes;
3480 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003481 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003482 CGM.getModule().addTypeName("struct._prop_t",
3483 PropertyTy);
3484
3485 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003486 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003487 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003488 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003489 // }
3490 PropertyListTy = llvm::StructType::get(IntTy,
3491 IntTy,
3492 llvm::ArrayType::get(PropertyTy, 0),
3493 NULL);
3494 CGM.getModule().addTypeName("struct._prop_list_t",
3495 PropertyListTy);
3496 // struct _prop_list_t *
3497 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3498
3499 // struct _objc_method {
3500 // SEL _cmd;
3501 // char *method_type;
3502 // char *_imp;
3503 // }
3504 MethodTy = llvm::StructType::get(SelectorPtrTy,
3505 Int8PtrTy,
3506 Int8PtrTy,
3507 NULL);
3508 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003509
3510 // struct _objc_cache *
3511 CacheTy = llvm::OpaqueType::get();
3512 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3513 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003514}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003515
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003516ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3517 : ObjCCommonTypesHelper(cgm)
3518{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003519 // struct _objc_method_description {
3520 // SEL name;
3521 // char *types;
3522 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003523 MethodDescriptionTy =
3524 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003525 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003526 NULL);
3527 CGM.getModule().addTypeName("struct._objc_method_description",
3528 MethodDescriptionTy);
3529
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003530 // struct _objc_method_description_list {
3531 // int count;
3532 // struct _objc_method_description[1];
3533 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003534 MethodDescriptionListTy =
3535 llvm::StructType::get(IntTy,
3536 llvm::ArrayType::get(MethodDescriptionTy, 0),
3537 NULL);
3538 CGM.getModule().addTypeName("struct._objc_method_description_list",
3539 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003540
3541 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003542 MethodDescriptionListPtrTy =
3543 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3544
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003545 // Protocol description structures
3546
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003547 // struct _objc_protocol_extension {
3548 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3549 // struct _objc_method_description_list *optional_instance_methods;
3550 // struct _objc_method_description_list *optional_class_methods;
3551 // struct _objc_property_list *instance_properties;
3552 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003553 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003554 llvm::StructType::get(IntTy,
3555 MethodDescriptionListPtrTy,
3556 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003557 PropertyListPtrTy,
3558 NULL);
3559 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3560 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003561
3562 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003563 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3564
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003565 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003566
3567 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3568 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3569
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003570 const llvm::Type *T =
3571 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3572 LongTy,
3573 llvm::ArrayType::get(ProtocolTyHolder, 0),
3574 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003575 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3576
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003577 // struct _objc_protocol {
3578 // struct _objc_protocol_extension *isa;
3579 // char *protocol_name;
3580 // struct _objc_protocol **_objc_protocol_list;
3581 // struct _objc_method_description_list *instance_methods;
3582 // struct _objc_method_description_list *class_methods;
3583 // }
3584 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003585 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003586 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3587 MethodDescriptionListPtrTy,
3588 MethodDescriptionListPtrTy,
3589 NULL);
3590 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3591
3592 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3593 CGM.getModule().addTypeName("struct._objc_protocol_list",
3594 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003595 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003596 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3597
3598 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003599 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003600 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003601
3602 // Class description structures
3603
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003604 // struct _objc_ivar {
3605 // char *ivar_name;
3606 // char *ivar_type;
3607 // int ivar_offset;
3608 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003609 IvarTy = llvm::StructType::get(Int8PtrTy,
3610 Int8PtrTy,
3611 IntTy,
3612 NULL);
3613 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3614
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003615 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003616 IvarListTy = llvm::OpaqueType::get();
3617 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3618 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3619
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003620 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003621 MethodListTy = llvm::OpaqueType::get();
3622 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3623 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3624
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003625 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003626 ClassExtensionTy =
3627 llvm::StructType::get(IntTy,
3628 Int8PtrTy,
3629 PropertyListPtrTy,
3630 NULL);
3631 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3632 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3633
3634 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3635
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003636 // struct _objc_class {
3637 // Class isa;
3638 // Class super_class;
3639 // char *name;
3640 // long version;
3641 // long info;
3642 // long instance_size;
3643 // struct _objc_ivar_list *ivars;
3644 // struct _objc_method_list *methods;
3645 // struct _objc_cache *cache;
3646 // struct _objc_protocol_list *protocols;
3647 // char *ivar_layout;
3648 // struct _objc_class_ext *ext;
3649 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003650 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3651 llvm::PointerType::getUnqual(ClassTyHolder),
3652 Int8PtrTy,
3653 LongTy,
3654 LongTy,
3655 LongTy,
3656 IvarListPtrTy,
3657 MethodListPtrTy,
3658 CachePtrTy,
3659 ProtocolListPtrTy,
3660 Int8PtrTy,
3661 ClassExtensionPtrTy,
3662 NULL);
3663 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3664
3665 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3666 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3667 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3668
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003669 // struct _objc_category {
3670 // char *category_name;
3671 // char *class_name;
3672 // struct _objc_method_list *instance_method;
3673 // struct _objc_method_list *class_method;
3674 // uint32_t size; // sizeof(struct _objc_category)
3675 // struct _objc_property_list *instance_properties;// category's @property
3676 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003677 CategoryTy = llvm::StructType::get(Int8PtrTy,
3678 Int8PtrTy,
3679 MethodListPtrTy,
3680 MethodListPtrTy,
3681 ProtocolListPtrTy,
3682 IntTy,
3683 PropertyListPtrTy,
3684 NULL);
3685 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3686
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003687 // Global metadata structures
3688
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003689 // struct _objc_symtab {
3690 // long sel_ref_cnt;
3691 // SEL *refs;
3692 // short cls_def_cnt;
3693 // short cat_def_cnt;
3694 // char *defs[cls_def_cnt + cat_def_cnt];
3695 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003696 SymtabTy = llvm::StructType::get(LongTy,
3697 SelectorPtrTy,
3698 ShortTy,
3699 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003700 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003701 NULL);
3702 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3703 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3704
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003705 // struct _objc_module {
3706 // long version;
3707 // long size; // sizeof(struct _objc_module)
3708 // char *name;
3709 // struct _objc_symtab* symtab;
3710 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003711 ModuleTy =
3712 llvm::StructType::get(LongTy,
3713 LongTy,
3714 Int8PtrTy,
3715 SymtabPtrTy,
3716 NULL);
3717 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003718
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003719
Anders Carlsson124526b2008-09-09 10:10:21 +00003720 // FIXME: This is the size of the setjmp buffer and should be
3721 // target specific. 18 is what's used on 32-bit X86.
3722 uint64_t SetJmpBufferSize = 18;
3723
3724 // Exceptions
3725 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003726 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003727
3728 ExceptionDataTy =
3729 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3730 SetJmpBufferSize),
3731 StackPtrTy, NULL);
3732 CGM.getModule().addTypeName("struct._objc_exception_data",
3733 ExceptionDataTy);
3734
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003735}
3736
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003737ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003738: ObjCCommonTypesHelper(cgm)
3739{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003740 // struct _method_list_t {
3741 // uint32_t entsize; // sizeof(struct _objc_method)
3742 // uint32_t method_count;
3743 // struct _objc_method method_list[method_count];
3744 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003745 MethodListnfABITy = llvm::StructType::get(IntTy,
3746 IntTy,
3747 llvm::ArrayType::get(MethodTy, 0),
3748 NULL);
3749 CGM.getModule().addTypeName("struct.__method_list_t",
3750 MethodListnfABITy);
3751 // struct method_list_t *
3752 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003753
3754 // struct _protocol_t {
3755 // id isa; // NULL
3756 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003757 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003758 // const struct method_list_t * const instance_methods;
3759 // const struct method_list_t * const class_methods;
3760 // const struct method_list_t *optionalInstanceMethods;
3761 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003762 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003763 // const uint32_t size; // sizeof(struct _protocol_t)
3764 // const uint32_t flags; // = 0
3765 // }
3766
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003767 // Holder for struct _protocol_list_t *
3768 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3769
3770 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3771 Int8PtrTy,
3772 llvm::PointerType::getUnqual(
3773 ProtocolListTyHolder),
3774 MethodListnfABIPtrTy,
3775 MethodListnfABIPtrTy,
3776 MethodListnfABIPtrTy,
3777 MethodListnfABIPtrTy,
3778 PropertyListPtrTy,
3779 IntTy,
3780 IntTy,
3781 NULL);
3782 CGM.getModule().addTypeName("struct._protocol_t",
3783 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003784
3785 // struct _protocol_t*
3786 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003787
Fariborz Jahanianda320092009-01-29 19:24:30 +00003788 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003789 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003790 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003791 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003792 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3793 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003794 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003795 NULL);
3796 CGM.getModule().addTypeName("struct._objc_protocol_list",
3797 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003798 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3799 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003800
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003801 // struct _objc_protocol_list*
3802 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003803
3804 // struct _ivar_t {
3805 // unsigned long int *offset; // pointer to ivar offset location
3806 // char *name;
3807 // char *type;
3808 // uint32_t alignment;
3809 // uint32_t size;
3810 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003811 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3812 Int8PtrTy,
3813 Int8PtrTy,
3814 IntTy,
3815 IntTy,
3816 NULL);
3817 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3818
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003819 // struct _ivar_list_t {
3820 // uint32 entsize; // sizeof(struct _ivar_t)
3821 // uint32 count;
3822 // struct _iver_t list[count];
3823 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003824 IvarListnfABITy = llvm::StructType::get(IntTy,
3825 IntTy,
3826 llvm::ArrayType::get(
3827 IvarnfABITy, 0),
3828 NULL);
3829 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3830
3831 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003832
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003833 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003834 // uint32_t const flags;
3835 // uint32_t const instanceStart;
3836 // uint32_t const instanceSize;
3837 // uint32_t const reserved; // only when building for 64bit targets
3838 // const uint8_t * const ivarLayout;
3839 // const char *const name;
3840 // const struct _method_list_t * const baseMethods;
3841 // const struct _objc_protocol_list *const baseProtocols;
3842 // const struct _ivar_list_t *const ivars;
3843 // const uint8_t * const weakIvarLayout;
3844 // const struct _prop_list_t * const properties;
3845 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003846
3847 // FIXME. Add 'reserved' field in 64bit abi mode!
3848 ClassRonfABITy = llvm::StructType::get(IntTy,
3849 IntTy,
3850 IntTy,
3851 Int8PtrTy,
3852 Int8PtrTy,
3853 MethodListnfABIPtrTy,
3854 ProtocolListnfABIPtrTy,
3855 IvarListnfABIPtrTy,
3856 Int8PtrTy,
3857 PropertyListPtrTy,
3858 NULL);
3859 CGM.getModule().addTypeName("struct._class_ro_t",
3860 ClassRonfABITy);
3861
3862 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3863 std::vector<const llvm::Type*> Params;
3864 Params.push_back(ObjectPtrTy);
3865 Params.push_back(SelectorPtrTy);
3866 ImpnfABITy = llvm::PointerType::getUnqual(
3867 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3868
3869 // struct _class_t {
3870 // struct _class_t *isa;
3871 // struct _class_t * const superclass;
3872 // void *cache;
3873 // IMP *vtable;
3874 // struct class_ro_t *ro;
3875 // }
3876
3877 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3878 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3879 llvm::PointerType::getUnqual(ClassTyHolder),
3880 CachePtrTy,
3881 llvm::PointerType::getUnqual(ImpnfABITy),
3882 llvm::PointerType::getUnqual(
3883 ClassRonfABITy),
3884 NULL);
3885 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3886
3887 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3888 ClassnfABITy);
3889
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003890 // LLVM for struct _class_t *
3891 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3892
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003893 // struct _category_t {
3894 // const char * const name;
3895 // struct _class_t *const cls;
3896 // const struct _method_list_t * const instance_methods;
3897 // const struct _method_list_t * const class_methods;
3898 // const struct _protocol_list_t * const protocols;
3899 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003900 // }
3901 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003902 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003903 MethodListnfABIPtrTy,
3904 MethodListnfABIPtrTy,
3905 ProtocolListnfABIPtrTy,
3906 PropertyListPtrTy,
3907 NULL);
3908 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003909
3910 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003911 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3912 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003913
3914 // MessageRefTy - LLVM for:
3915 // struct _message_ref_t {
3916 // IMP messenger;
3917 // SEL name;
3918 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003919
3920 // First the clang type for struct _message_ref_t
3921 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3922 SourceLocation(),
3923 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003924 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3925 Ctx.VoidPtrTy, 0, false));
3926 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3927 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003928 RD->completeDefinition(Ctx);
3929
3930 MessageRefCTy = Ctx.getTagDeclType(RD);
3931 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3932 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003933
3934 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3935 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3936
3937 // SuperMessageRefTy - LLVM for:
3938 // struct _super_message_ref_t {
3939 // SUPER_IMP messenger;
3940 // SEL name;
3941 // };
3942 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3943 SelectorPtrTy,
3944 NULL);
3945 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3946
3947 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3948 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3949
Daniel Dunbare588b992009-03-01 04:46:24 +00003950
3951 // struct objc_typeinfo {
3952 // const void** vtable; // objc_ehtype_vtable + 2
3953 // const char* name; // c++ typeinfo string
3954 // Class cls;
3955 // };
3956 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3957 Int8PtrTy,
3958 ClassnfABIPtrTy,
3959 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003960 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003961 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003962}
3963
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003964llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3965 FinishNonFragileABIModule();
3966
3967 return NULL;
3968}
3969
3970void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3971 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003972
3973 // Build list of all implemented classe addresses in array
3974 // L_OBJC_LABEL_CLASS_$.
3975 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3976 // list of 'nonlazy' implementations (defined as those with a +load{}
3977 // method!!).
3978 unsigned NumClasses = DefinedClasses.size();
3979 if (NumClasses) {
3980 std::vector<llvm::Constant*> Symbols(NumClasses);
3981 for (unsigned i=0; i<NumClasses; i++)
3982 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3983 ObjCTypes.Int8PtrTy);
3984 llvm::Constant* Init =
3985 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3986 NumClasses),
3987 Symbols);
3988
3989 llvm::GlobalVariable *GV =
3990 new llvm::GlobalVariable(Init->getType(), false,
3991 llvm::GlobalValue::InternalLinkage,
3992 Init,
3993 "\01L_OBJC_LABEL_CLASS_$",
3994 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003995 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003996 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3997 UsedGlobals.push_back(GV);
3998 }
3999
4000 // Build list of all implemented category addresses in array
4001 // L_OBJC_LABEL_CATEGORY_$.
4002 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4003 // list of 'nonlazy' category implementations (defined as those with a +load{}
4004 // method!!).
4005 unsigned NumCategory = DefinedCategories.size();
4006 if (NumCategory) {
4007 std::vector<llvm::Constant*> Symbols(NumCategory);
4008 for (unsigned i=0; i<NumCategory; i++)
4009 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4010 ObjCTypes.Int8PtrTy);
4011 llvm::Constant* Init =
4012 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4013 NumCategory),
4014 Symbols);
4015
4016 llvm::GlobalVariable *GV =
4017 new llvm::GlobalVariable(Init->getType(), false,
4018 llvm::GlobalValue::InternalLinkage,
4019 Init,
4020 "\01L_OBJC_LABEL_CATEGORY_$",
4021 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004022 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004023 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4024 UsedGlobals.push_back(GV);
4025 }
4026
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004027 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4028 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4029 std::vector<llvm::Constant*> Values(2);
4030 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004031 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004032 // FIXME: Fix and continue?
4033 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4034 flags |= eImageInfo_GarbageCollected;
4035 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4036 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004037 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004038 llvm::Constant* Init = llvm::ConstantArray::get(
4039 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4040 Values);
4041 llvm::GlobalVariable *IMGV =
4042 new llvm::GlobalVariable(Init->getType(), false,
4043 llvm::GlobalValue::InternalLinkage,
4044 Init,
4045 "\01L_OBJC_IMAGE_INFO",
4046 &CGM.getModule());
4047 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004048 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004049 UsedGlobals.push_back(IMGV);
4050
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004051 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004052
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004053 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4054 e = UsedGlobals.end(); i != e; ++i) {
4055 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4056 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004057
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004058 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4059 llvm::GlobalValue *GV =
4060 new llvm::GlobalVariable(AT, false,
4061 llvm::GlobalValue::AppendingLinkage,
4062 llvm::ConstantArray::get(AT, Used),
4063 "llvm.used",
4064 &CGM.getModule());
4065
4066 GV->setSection("llvm.metadata");
4067
4068}
4069
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004070// Metadata flags
4071enum MetaDataDlags {
4072 CLS = 0x0,
4073 CLS_META = 0x1,
4074 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004075 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004076 CLS_EXCEPTION = 0x20
4077};
4078/// BuildClassRoTInitializer - generate meta-data for:
4079/// struct _class_ro_t {
4080/// uint32_t const flags;
4081/// uint32_t const instanceStart;
4082/// uint32_t const instanceSize;
4083/// uint32_t const reserved; // only when building for 64bit targets
4084/// const uint8_t * const ivarLayout;
4085/// const char *const name;
4086/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004087/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004088/// const struct _ivar_list_t *const ivars;
4089/// const uint8_t * const weakIvarLayout;
4090/// const struct _prop_list_t * const properties;
4091/// }
4092///
4093llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4094 unsigned flags,
4095 unsigned InstanceStart,
4096 unsigned InstanceSize,
4097 const ObjCImplementationDecl *ID) {
4098 std::string ClassName = ID->getNameAsString();
4099 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4100 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4101 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4102 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4103 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004104 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4105 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004106 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004107 // const struct _method_list_t * const baseMethods;
4108 std::vector<llvm::Constant*> Methods;
4109 std::string MethodListName("\01l_OBJC_$_");
4110 if (flags & CLS_META) {
4111 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004112 for (ObjCImplementationDecl::classmeth_iterator
4113 i = ID->classmeth_begin(CGM.getContext()),
4114 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004115 // Class methods should always be defined.
4116 Methods.push_back(GetMethodConstant(*i));
4117 }
4118 } else {
4119 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004120 for (ObjCImplementationDecl::instmeth_iterator
4121 i = ID->instmeth_begin(CGM.getContext()),
4122 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004123 // Instance methods should always be defined.
4124 Methods.push_back(GetMethodConstant(*i));
4125 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004126 for (ObjCImplementationDecl::propimpl_iterator
4127 i = ID->propimpl_begin(CGM.getContext()),
4128 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004129 ObjCPropertyImplDecl *PID = *i;
4130
4131 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4132 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4133
4134 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4135 if (llvm::Constant *C = GetMethodConstant(MD))
4136 Methods.push_back(C);
4137 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4138 if (llvm::Constant *C = GetMethodConstant(MD))
4139 Methods.push_back(C);
4140 }
4141 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004142 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004143 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004144 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004145
4146 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4147 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4148 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4149 + OID->getNameAsString(),
4150 OID->protocol_begin(),
4151 OID->protocol_end());
4152
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004153 if (flags & CLS_META)
4154 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4155 else
4156 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004157 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4158 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004159 if (flags & CLS_META)
4160 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4161 else
4162 Values[ 9] =
4163 EmitPropertyList(
4164 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4165 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004166 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4167 Values);
4168 llvm::GlobalVariable *CLASS_RO_GV =
4169 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4170 llvm::GlobalValue::InternalLinkage,
4171 Init,
4172 (flags & CLS_META) ?
4173 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4174 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4175 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004176 CLASS_RO_GV->setAlignment(
4177 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004178 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004179 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004180
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004181}
4182
4183/// BuildClassMetaData - This routine defines that to-level meta-data
4184/// for the given ClassName for:
4185/// struct _class_t {
4186/// struct _class_t *isa;
4187/// struct _class_t * const superclass;
4188/// void *cache;
4189/// IMP *vtable;
4190/// struct class_ro_t *ro;
4191/// }
4192///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004193llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4194 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004195 llvm::Constant *IsAGV,
4196 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004197 llvm::Constant *ClassRoGV,
4198 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004199 std::vector<llvm::Constant*> Values(5);
4200 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004201 Values[1] = SuperClassGV
4202 ? SuperClassGV
4203 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004204 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4205 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4206 Values[4] = ClassRoGV; // &CLASS_RO_GV
4207 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4208 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004209 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4210 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004211 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004212 GV->setAlignment(
4213 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004214 if (HiddenVisibility)
4215 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004216 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004217}
4218
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004219void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004220 uint32_t &InstanceStart,
4221 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004222 const ASTRecordLayout &RL =
4223 CGM.getContext().getASTObjCImplementationLayout(OID);
4224
4225 if (!RL.getFieldCount()) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004226 InstanceStart = InstanceSize = 0;
4227 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004228 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004229
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004230 InstanceStart = RL.getFieldOffset(0) / 8;
4231 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004232}
4233
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004234void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4235 std::string ClassName = ID->getNameAsString();
4236 if (!ObjCEmptyCacheVar) {
4237 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004238 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004239 false,
4240 llvm::GlobalValue::ExternalLinkage,
4241 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004242 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004243 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004244
4245 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004246 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004247 false,
4248 llvm::GlobalValue::ExternalLinkage,
4249 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004250 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004251 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004252 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004253 assert(ID->getClassInterface() &&
4254 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004255 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004256 uint32_t InstanceStart =
4257 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4258 uint32_t InstanceSize = InstanceStart;
4259 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004260 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4261 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004262
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004263 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004264
Daniel Dunbar04d40782009-04-14 06:00:08 +00004265 bool classIsHidden =
4266 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004267 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004268 flags |= OBJC2_CLS_HIDDEN;
4269 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004270 // class is root
4271 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004272 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004273 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +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 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4277 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4278 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004279 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004280 // work on super class metadata symbol.
4281 std::string SuperClassName =
4282 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004283 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004284 }
4285 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4286 InstanceStart,
4287 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004288 std::string TClassName = ObjCMetaClassName + ClassName;
4289 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004290 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4291 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004292
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004293 // Metadata for the class
4294 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004295 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004296 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004297
4298 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4299 flags |= CLS_EXCEPTION;
4300
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004301 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004302 flags |= CLS_ROOT;
4303 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004304 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004305 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004306 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004307 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004308 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004309 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004310 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004311 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004312 InstanceStart,
4313 InstanceSize,
4314 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004315
4316 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004317 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004318 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4319 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004320 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004321
4322 // Force the definition of the EHType if necessary.
4323 if (flags & CLS_EXCEPTION)
4324 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004325}
4326
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004327/// GenerateProtocolRef - This routine is called to generate code for
4328/// a protocol reference expression; as in:
4329/// @code
4330/// @protocol(Proto1);
4331/// @endcode
4332/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4333/// which will hold address of the protocol meta-data.
4334///
4335llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4336 const ObjCProtocolDecl *PD) {
4337
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004338 // This routine is called for @protocol only. So, we must build definition
4339 // of protocol's meta-data (not a reference to it!)
4340 //
4341 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004342 ObjCTypes.ExternalProtocolPtrTy);
4343
4344 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4345 ProtocolName += PD->getNameAsCString();
4346
4347 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4348 if (PTGV)
4349 return Builder.CreateLoad(PTGV, false, "tmp");
4350 PTGV = new llvm::GlobalVariable(
4351 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004352 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004353 Init,
4354 ProtocolName,
4355 &CGM.getModule());
4356 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4357 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4358 UsedGlobals.push_back(PTGV);
4359 return Builder.CreateLoad(PTGV, false, "tmp");
4360}
4361
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004362/// GenerateCategory - Build metadata for a category implementation.
4363/// struct _category_t {
4364/// const char * const name;
4365/// struct _class_t *const cls;
4366/// const struct _method_list_t * const instance_methods;
4367/// const struct _method_list_t * const class_methods;
4368/// const struct _protocol_list_t * const protocols;
4369/// const struct _prop_list_t * const properties;
4370/// }
4371///
4372void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4373{
4374 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004375 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4376 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004377 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004378 std::string ExtClassName(getClassSymbolPrefix() +
4379 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004380
4381 std::vector<llvm::Constant*> Values(6);
4382 Values[0] = GetClassName(OCD->getIdentifier());
4383 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004384 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004385 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004386 std::vector<llvm::Constant*> Methods;
4387 std::string MethodListName(Prefix);
4388 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4389 "_$_" + OCD->getNameAsString();
4390
Douglas Gregor653f1b12009-04-23 01:02:12 +00004391 for (ObjCCategoryImplDecl::instmeth_iterator
4392 i = OCD->instmeth_begin(CGM.getContext()),
4393 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004394 // Instance methods should always be defined.
4395 Methods.push_back(GetMethodConstant(*i));
4396 }
4397
4398 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004399 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004400 Methods);
4401
4402 MethodListName = Prefix;
4403 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4404 OCD->getNameAsString();
4405 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004406 for (ObjCCategoryImplDecl::classmeth_iterator
4407 i = OCD->classmeth_begin(CGM.getContext()),
4408 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004409 // Class methods should always be defined.
4410 Methods.push_back(GetMethodConstant(*i));
4411 }
4412
4413 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004414 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004415 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004416 const ObjCCategoryDecl *Category =
4417 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004418 if (Category) {
4419 std::string ExtName(Interface->getNameAsString() + "_$_" +
4420 OCD->getNameAsString());
4421 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4422 + Interface->getNameAsString() + "_$_"
4423 + Category->getNameAsString(),
4424 Category->protocol_begin(),
4425 Category->protocol_end());
4426 Values[5] =
4427 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4428 OCD, Category, ObjCTypes);
4429 }
4430 else {
4431 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4432 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4433 }
4434
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004435 llvm::Constant *Init =
4436 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4437 Values);
4438 llvm::GlobalVariable *GCATV
4439 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4440 false,
4441 llvm::GlobalValue::InternalLinkage,
4442 Init,
4443 ExtCatName,
4444 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004445 GCATV->setAlignment(
4446 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004447 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004448 UsedGlobals.push_back(GCATV);
4449 DefinedCategories.push_back(GCATV);
4450}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004451
4452/// GetMethodConstant - Return a struct objc_method constant for the
4453/// given method if it has been defined. The result is null if the
4454/// method has not been defined. The return value has type MethodPtrTy.
4455llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4456 const ObjCMethodDecl *MD) {
4457 // FIXME: Use DenseMap::lookup
4458 llvm::Function *Fn = MethodDefinitions[MD];
4459 if (!Fn)
4460 return 0;
4461
4462 std::vector<llvm::Constant*> Method(3);
4463 Method[0] =
4464 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4465 ObjCTypes.SelectorPtrTy);
4466 Method[1] = GetMethodVarType(MD);
4467 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4468 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4469}
4470
4471/// EmitMethodList - Build meta-data for method declarations
4472/// struct _method_list_t {
4473/// uint32_t entsize; // sizeof(struct _objc_method)
4474/// uint32_t method_count;
4475/// struct _objc_method method_list[method_count];
4476/// }
4477///
4478llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4479 const std::string &Name,
4480 const char *Section,
4481 const ConstantVector &Methods) {
4482 // Return null for empty list.
4483 if (Methods.empty())
4484 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4485
4486 std::vector<llvm::Constant*> Values(3);
4487 // sizeof(struct _objc_method)
4488 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4489 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4490 // method_count
4491 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4492 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4493 Methods.size());
4494 Values[2] = llvm::ConstantArray::get(AT, Methods);
4495 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4496
4497 llvm::GlobalVariable *GV =
4498 new llvm::GlobalVariable(Init->getType(), false,
4499 llvm::GlobalValue::InternalLinkage,
4500 Init,
4501 Name,
4502 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004503 GV->setAlignment(
4504 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004505 GV->setSection(Section);
4506 UsedGlobals.push_back(GV);
4507 return llvm::ConstantExpr::getBitCast(GV,
4508 ObjCTypes.MethodListnfABIPtrTy);
4509}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004510
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004511/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4512/// the given ivar.
4513///
4514llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004515 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004516 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004517 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004518 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4519 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004520 llvm::GlobalVariable *IvarOffsetGV =
4521 CGM.getModule().getGlobalVariable(Name);
4522 if (!IvarOffsetGV)
4523 IvarOffsetGV =
4524 new llvm::GlobalVariable(ObjCTypes.LongTy,
4525 false,
4526 llvm::GlobalValue::ExternalLinkage,
4527 0,
4528 Name,
4529 &CGM.getModule());
4530 return IvarOffsetGV;
4531}
4532
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004533llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004534 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004535 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004536 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004537 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4538 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4539 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004540 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004541 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004542
4543 // FIXME: This matches gcc, but shouldn't the visibility be set on
4544 // the use as well (i.e., in ObjCIvarOffsetVariable).
4545 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4546 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4547 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004548 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004549 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004550 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004551 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004552 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004553}
4554
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004555/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004556/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004557/// IvarListnfABIPtrTy.
4558/// struct _ivar_t {
4559/// unsigned long int *offset; // pointer to ivar offset location
4560/// char *name;
4561/// char *type;
4562/// uint32_t alignment;
4563/// uint32_t size;
4564/// }
4565/// struct _ivar_list_t {
4566/// uint32 entsize; // sizeof(struct _ivar_t)
4567/// uint32 count;
4568/// struct _iver_t list[count];
4569/// }
4570///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004571
4572void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4573 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4574 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4575 E = OID->ivar_end(); I != E; ++I) {
4576 // Ignore unnamed bit-fields.
4577 if (!(*I)->getDeclName())
4578 continue;
4579
4580 Res.push_back(*I);
4581 }
4582
4583 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4584 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4585 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4586 Res.push_back(IV);
4587}
4588
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004589llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4590 const ObjCImplementationDecl *ID) {
4591
4592 std::vector<llvm::Constant*> Ivars, Ivar(5);
4593
4594 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4595 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4596
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004597 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004598
Daniel Dunbar91636d62009-04-20 00:33:43 +00004599 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004600 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004601 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004602
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004603 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4604 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004605 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004606 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004607 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4608 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004609 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004610 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004611 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4612 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004613 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004614 Align = llvm::Log2_32(Align);
4615 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004616 // NOTE. Size of a bitfield does not match gcc's, because of the
4617 // way bitfields are treated special in each. But I am told that
4618 // 'size' for bitfield ivars is ignored by the runtime so it does
4619 // not matter. If it matters, there is enough info to get the
4620 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004621 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4622 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4623 }
4624 // Return null for empty list.
4625 if (Ivars.empty())
4626 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4627 std::vector<llvm::Constant*> Values(3);
4628 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4629 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4630 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4631 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4632 Ivars.size());
4633 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4634 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4635 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4636 llvm::GlobalVariable *GV =
4637 new llvm::GlobalVariable(Init->getType(), false,
4638 llvm::GlobalValue::InternalLinkage,
4639 Init,
4640 Prefix + OID->getNameAsString(),
4641 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004642 GV->setAlignment(
4643 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004644 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004645
4646 UsedGlobals.push_back(GV);
4647 return llvm::ConstantExpr::getBitCast(GV,
4648 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004649}
4650
4651llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4652 const ObjCProtocolDecl *PD) {
4653 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4654
4655 if (!Entry) {
4656 // We use the initializer as a marker of whether this is a forward
4657 // reference or not. At module finalization we add the empty
4658 // contents for protocols which were referenced but never defined.
4659 Entry =
4660 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4661 llvm::GlobalValue::ExternalLinkage,
4662 0,
4663 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4664 &CGM.getModule());
4665 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4666 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004667 }
4668
4669 return Entry;
4670}
4671
4672/// GetOrEmitProtocol - Generate the protocol meta-data:
4673/// @code
4674/// struct _protocol_t {
4675/// id isa; // NULL
4676/// const char * const protocol_name;
4677/// const struct _protocol_list_t * protocol_list; // super protocols
4678/// const struct method_list_t * const instance_methods;
4679/// const struct method_list_t * const class_methods;
4680/// const struct method_list_t *optionalInstanceMethods;
4681/// const struct method_list_t *optionalClassMethods;
4682/// const struct _prop_list_t * properties;
4683/// const uint32_t size; // sizeof(struct _protocol_t)
4684/// const uint32_t flags; // = 0
4685/// }
4686/// @endcode
4687///
4688
4689llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4690 const ObjCProtocolDecl *PD) {
4691 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4692
4693 // Early exit if a defining object has already been generated.
4694 if (Entry && Entry->hasInitializer())
4695 return Entry;
4696
4697 const char *ProtocolName = PD->getNameAsCString();
4698
4699 // Construct method lists.
4700 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4701 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004702 for (ObjCProtocolDecl::instmeth_iterator
4703 i = PD->instmeth_begin(CGM.getContext()),
4704 e = PD->instmeth_end(CGM.getContext());
4705 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004706 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004707 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004708 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4709 OptInstanceMethods.push_back(C);
4710 } else {
4711 InstanceMethods.push_back(C);
4712 }
4713 }
4714
Douglas Gregor6ab35242009-04-09 21:40:53 +00004715 for (ObjCProtocolDecl::classmeth_iterator
4716 i = PD->classmeth_begin(CGM.getContext()),
4717 e = PD->classmeth_end(CGM.getContext());
4718 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004719 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004720 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004721 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4722 OptClassMethods.push_back(C);
4723 } else {
4724 ClassMethods.push_back(C);
4725 }
4726 }
4727
4728 std::vector<llvm::Constant*> Values(10);
4729 // isa is NULL
4730 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4731 Values[1] = GetClassName(PD->getIdentifier());
4732 Values[2] = EmitProtocolList(
4733 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4734 PD->protocol_begin(),
4735 PD->protocol_end());
4736
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004737 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004738 + PD->getNameAsString(),
4739 "__DATA, __objc_const",
4740 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004741 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004742 + PD->getNameAsString(),
4743 "__DATA, __objc_const",
4744 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004745 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004746 + PD->getNameAsString(),
4747 "__DATA, __objc_const",
4748 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004749 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750 + PD->getNameAsString(),
4751 "__DATA, __objc_const",
4752 OptClassMethods);
4753 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4754 0, PD, ObjCTypes);
4755 uint32_t Size =
4756 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4757 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4758 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4759 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4760 Values);
4761
4762 if (Entry) {
4763 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004764 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004765 Entry->setInitializer(Init);
4766 } else {
4767 Entry =
4768 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004769 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004770 Init,
4771 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4772 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004773 Entry->setAlignment(
4774 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004775 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004776 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004777 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4778
4779 // Use this protocol meta-data to build protocol list table in section
4780 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004781 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004782 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004783 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004784 Entry,
4785 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4786 +ProtocolName,
4787 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004788 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004789 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004790 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004791 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4792 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 return Entry;
4794}
4795
4796/// EmitProtocolList - Generate protocol list meta-data:
4797/// @code
4798/// struct _protocol_list_t {
4799/// long protocol_count; // Note, this is 32/64 bit
4800/// struct _protocol_t[protocol_count];
4801/// }
4802/// @endcode
4803///
4804llvm::Constant *
4805CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4806 ObjCProtocolDecl::protocol_iterator begin,
4807 ObjCProtocolDecl::protocol_iterator end) {
4808 std::vector<llvm::Constant*> ProtocolRefs;
4809
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004811 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4813
Daniel Dunbar948e2582009-02-15 07:36:20 +00004814 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4816 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004817 return llvm::ConstantExpr::getBitCast(GV,
4818 ObjCTypes.ProtocolListnfABIPtrTy);
4819
4820 for (; begin != end; ++begin)
4821 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4822
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 // This list is null terminated.
4824 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004825 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004826
4827 std::vector<llvm::Constant*> Values(2);
4828 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4829 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004830 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004831 ProtocolRefs.size()),
4832 ProtocolRefs);
4833
4834 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4835 GV = new llvm::GlobalVariable(Init->getType(), false,
4836 llvm::GlobalValue::InternalLinkage,
4837 Init,
4838 Name,
4839 &CGM.getModule());
4840 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004841 GV->setAlignment(
4842 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004844 return llvm::ConstantExpr::getBitCast(GV,
4845 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846}
4847
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004848/// GetMethodDescriptionConstant - This routine build following meta-data:
4849/// struct _objc_method {
4850/// SEL _cmd;
4851/// char *method_type;
4852/// char *_imp;
4853/// }
4854
4855llvm::Constant *
4856CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4857 std::vector<llvm::Constant*> Desc(3);
4858 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4859 ObjCTypes.SelectorPtrTy);
4860 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004861 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004862 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4863 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4864}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004865
4866/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4867/// This code gen. amounts to generating code for:
4868/// @code
4869/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4870/// @encode
4871///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004872LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004873 CodeGen::CodeGenFunction &CGF,
4874 QualType ObjectTy,
4875 llvm::Value *BaseValue,
4876 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004877 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004878 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004879 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4880 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004881}
4882
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004883llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4884 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004885 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004886 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004887 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4888 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004889}
4890
Fariborz Jahanian46551122009-02-04 00:22:57 +00004891CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4892 CodeGen::CodeGenFunction &CGF,
4893 QualType ResultType,
4894 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004895 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004896 QualType Arg0Ty,
4897 bool IsSuper,
4898 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004899 // FIXME. Even though IsSuper is passes. This function doese not
4900 // handle calls to 'super' receivers.
4901 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004902 llvm::Value *Arg0 = Receiver;
4903 if (!IsSuper)
4904 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004905
4906 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004907 // FIXME. This is too much work to get the ABI-specific result type
4908 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004909 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4910 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004911 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004912 std::string Name("\01l_");
4913 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004914#if 0
4915 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004916 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004917 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004918 // FIXME. Is there a better way of getting these names.
4919 // They are available in RuntimeFunctions vector pair.
4920 Name += "objc_msgSendId_stret_fixup";
4921 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004922 else
4923#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004924 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004925 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004926 Name += "objc_msgSendSuper2_stret_fixup";
4927 }
4928 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004929 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004930 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004931 Name += "objc_msgSend_stret_fixup";
4932 }
4933 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00004934 else if (!IsSuper && ResultType->isFloatingType()) {
4935 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
4936 BuiltinType::Kind k = BT->getKind();
4937 if (k == BuiltinType::LongDouble) {
4938 Fn = ObjCTypes.getMessageSendFpretFixupFn();
4939 Name += "objc_msgSend_fpret_fixup";
4940 }
4941 else {
4942 Fn = ObjCTypes.getMessageSendFixupFn();
4943 Name += "objc_msgSend_fixup";
4944 }
4945 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004946 }
4947 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004948#if 0
4949// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004951 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952 Name += "objc_msgSendId_fixup";
4953 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004954 else
4955#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004956 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004957 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004958 Name += "objc_msgSendSuper2_fixup";
4959 }
4960 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004961 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004962 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004963 Name += "objc_msgSend_fixup";
4964 }
4965 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004966 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004967 Name += '_';
4968 std::string SelName(Sel.getAsString());
4969 // Replace all ':' in selector name with '_' ouch!
4970 for(unsigned i = 0; i < SelName.size(); i++)
4971 if (SelName[i] == ':')
4972 SelName[i] = '_';
4973 Name += SelName;
4974 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4975 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00004976 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977 std::vector<llvm::Constant*> Values(2);
4978 Values[0] = Fn;
4979 Values[1] = GetMethodVarName(Sel);
4980 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4981 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004982 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004983 Init,
4984 Name,
4985 &CGM.getModule());
4986 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00004987 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004989 }
4990 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004991
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 CallArgList ActualArgs;
4993 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4994 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4995 ObjCTypes.MessageRefCPtrTy));
4996 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004997 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4998 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4999 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005000 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005001 Callee = CGF.Builder.CreateBitCast(Callee,
5002 llvm::PointerType::getUnqual(FTy));
5003 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005004}
5005
5006/// Generate code for a message send expression in the nonfragile abi.
5007CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5008 CodeGen::CodeGenFunction &CGF,
5009 QualType ResultType,
5010 Selector Sel,
5011 llvm::Value *Receiver,
5012 bool IsClassMessage,
5013 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005014 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005015 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005016 false, CallArgs);
5017}
5018
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005019llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005020CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005021 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5022
Daniel Dunbardfff2302009-03-02 05:18:14 +00005023 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005024 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5025 llvm::GlobalValue::ExternalLinkage,
5026 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005027 }
5028
5029 return GV;
5030}
5031
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005032llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005033 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005034 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5035
5036 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005037 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005038 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005039 Entry =
5040 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5041 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005042 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005043 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005044 &CGM.getModule());
5045 Entry->setAlignment(
5046 CGM.getTargetData().getPrefTypeAlignment(
5047 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005048 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5049 UsedGlobals.push_back(Entry);
5050 }
5051
5052 return Builder.CreateLoad(Entry, false, "tmp");
5053}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005054
Daniel Dunbar11394522009-04-18 08:51:00 +00005055llvm::Value *
5056CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5057 const ObjCInterfaceDecl *ID) {
5058 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5059
5060 if (!Entry) {
5061 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5062 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5063 Entry =
5064 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5065 llvm::GlobalValue::InternalLinkage,
5066 ClassGV,
5067 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5068 &CGM.getModule());
5069 Entry->setAlignment(
5070 CGM.getTargetData().getPrefTypeAlignment(
5071 ObjCTypes.ClassnfABIPtrTy));
5072 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005073 UsedGlobals.push_back(Entry);
5074 }
5075
5076 return Builder.CreateLoad(Entry, false, "tmp");
5077}
5078
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005079/// EmitMetaClassRef - Return a Value * of the address of _class_t
5080/// meta-data
5081///
5082llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5083 const ObjCInterfaceDecl *ID) {
5084 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5085 if (Entry)
5086 return Builder.CreateLoad(Entry, false, "tmp");
5087
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005088 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005089 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005090 Entry =
5091 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5092 llvm::GlobalValue::InternalLinkage,
5093 MetaClassGV,
5094 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5095 &CGM.getModule());
5096 Entry->setAlignment(
5097 CGM.getTargetData().getPrefTypeAlignment(
5098 ObjCTypes.ClassnfABIPtrTy));
5099
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005100 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005101 UsedGlobals.push_back(Entry);
5102
5103 return Builder.CreateLoad(Entry, false, "tmp");
5104}
5105
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005106/// GetClass - Return a reference to the class for the given interface
5107/// decl.
5108llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5109 const ObjCInterfaceDecl *ID) {
5110 return EmitClassRef(Builder, ID);
5111}
5112
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005113/// Generates a message send where the super is the receiver. This is
5114/// a message send to self with special delivery semantics indicating
5115/// which class's method should be called.
5116CodeGen::RValue
5117CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5118 QualType ResultType,
5119 Selector Sel,
5120 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005121 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005122 llvm::Value *Receiver,
5123 bool IsClassMessage,
5124 const CodeGen::CallArgList &CallArgs) {
5125 // ...
5126 // Create and init a super structure; this is a (receiver, class)
5127 // pair we will pass to objc_msgSendSuper.
5128 llvm::Value *ObjCSuper =
5129 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5130
5131 llvm::Value *ReceiverAsObject =
5132 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5133 CGF.Builder.CreateStore(ReceiverAsObject,
5134 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5135
5136 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005137 llvm::Value *Target;
5138 if (IsClassMessage) {
5139 if (isCategoryImpl) {
5140 // Message sent to "super' in a class method defined in
5141 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005142 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005143 Target = CGF.Builder.CreateStructGEP(Target, 0);
5144 Target = CGF.Builder.CreateLoad(Target);
5145 }
5146 else
5147 Target = EmitMetaClassRef(CGF.Builder, Class);
5148 }
5149 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005150 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005151
5152 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5153 // and ObjCTypes types.
5154 const llvm::Type *ClassTy =
5155 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5156 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5157 CGF.Builder.CreateStore(Target,
5158 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5159
5160 return EmitMessageSend(CGF, ResultType, Sel,
5161 ObjCSuper, ObjCTypes.SuperPtrCTy,
5162 true, CallArgs);
5163}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005164
5165llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5166 Selector Sel) {
5167 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5168
5169 if (!Entry) {
5170 llvm::Constant *Casted =
5171 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5172 ObjCTypes.SelectorPtrTy);
5173 Entry =
5174 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5175 llvm::GlobalValue::InternalLinkage,
5176 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5177 &CGM.getModule());
5178 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5179 UsedGlobals.push_back(Entry);
5180 }
5181
5182 return Builder.CreateLoad(Entry, false, "tmp");
5183}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005184/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5185/// objc_assign_ivar (id src, id *dst)
5186///
5187void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5188 llvm::Value *src, llvm::Value *dst)
5189{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005190 const llvm::Type * SrcTy = src->getType();
5191 if (!isa<llvm::PointerType>(SrcTy)) {
5192 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5193 assert(Size <= 8 && "does not support size > 8");
5194 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5195 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005196 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5197 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005198 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5199 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005200 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005201 src, dst, "assignivar");
5202 return;
5203}
5204
5205/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5206/// objc_assign_strongCast (id src, id *dst)
5207///
5208void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5209 CodeGen::CodeGenFunction &CGF,
5210 llvm::Value *src, llvm::Value *dst)
5211{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005212 const llvm::Type * SrcTy = src->getType();
5213 if (!isa<llvm::PointerType>(SrcTy)) {
5214 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5215 assert(Size <= 8 && "does not support size > 8");
5216 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5217 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005218 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5219 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005220 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5221 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005222 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005223 src, dst, "weakassign");
5224 return;
5225}
5226
5227/// EmitObjCWeakRead - Code gen for loading value of a __weak
5228/// object: objc_read_weak (id *src)
5229///
5230llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5231 CodeGen::CodeGenFunction &CGF,
5232 llvm::Value *AddrWeakObj)
5233{
Eli Friedman8339b352009-03-07 03:57:15 +00005234 const llvm::Type* DestTy =
5235 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005236 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005237 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005238 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005239 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005240 return read_weak;
5241}
5242
5243/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5244/// objc_assign_weak (id src, id *dst)
5245///
5246void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5247 llvm::Value *src, llvm::Value *dst)
5248{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005249 const llvm::Type * SrcTy = src->getType();
5250 if (!isa<llvm::PointerType>(SrcTy)) {
5251 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5252 assert(Size <= 8 && "does not support size > 8");
5253 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5254 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005255 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5256 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005257 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5258 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005259 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005260 src, dst, "weakassign");
5261 return;
5262}
5263
5264/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5265/// objc_assign_global (id src, id *dst)
5266///
5267void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5268 llvm::Value *src, llvm::Value *dst)
5269{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005270 const llvm::Type * SrcTy = src->getType();
5271 if (!isa<llvm::PointerType>(SrcTy)) {
5272 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5273 assert(Size <= 8 && "does not support size > 8");
5274 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5275 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005276 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5277 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005278 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5279 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005280 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005281 src, dst, "globalassign");
5282 return;
5283}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005284
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005285void
5286CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5287 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005288 bool isTry = isa<ObjCAtTryStmt>(S);
5289 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5290 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005291 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005292 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005293 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005294 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5295
5296 // For @synchronized, call objc_sync_enter(sync.expr). The
5297 // evaluation of the expression must occur before we enter the
5298 // @synchronized. We can safely avoid a temp here because jumps into
5299 // @synchronized are illegal & this will dominate uses.
5300 llvm::Value *SyncArg = 0;
5301 if (!isTry) {
5302 SyncArg =
5303 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5304 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005305 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005306 }
5307
5308 // Push an EH context entry, used for handling rethrows and jumps
5309 // through finally.
5310 CGF.PushCleanupBlock(FinallyBlock);
5311
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005312 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005313
5314 CGF.EmitBlock(TryBlock);
5315 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5316 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5317 CGF.EmitBranchThroughCleanup(FinallyEnd);
5318
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005319 // Emit the exception handler.
5320
5321 CGF.EmitBlock(TryHandler);
5322
5323 llvm::Value *llvm_eh_exception =
5324 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5325 llvm::Value *llvm_eh_selector_i64 =
5326 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5327 llvm::Value *llvm_eh_typeid_for_i64 =
5328 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5329 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5330 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5331
5332 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5333 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005334 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005335
5336 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005337 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005338 bool HasCatchAll = false;
5339 if (isTry) {
5340 if (const ObjCAtCatchStmt* CatchStmt =
5341 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5342 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005343 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005344 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005345
5346 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005347 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005348 // Use i8* null here to signal this is a catch all, not a cleanup.
5349 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5350 SelectorArgs.push_back(Null);
5351 HasCatchAll = true;
5352 break;
5353 }
5354
Daniel Dunbarede8de92009-03-06 00:01:21 +00005355 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5356 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005357 llvm::Value *IDEHType =
5358 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5359 if (!IDEHType)
5360 IDEHType =
5361 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5362 llvm::GlobalValue::ExternalLinkage,
5363 0, "OBJC_EHTYPE_id", &CGM.getModule());
5364 SelectorArgs.push_back(IDEHType);
5365 HasCatchAll = true;
5366 break;
5367 }
5368
5369 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005370 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005371 assert(PT && "Invalid @catch type.");
5372 const ObjCInterfaceType *IT =
5373 PT->getPointeeType()->getAsObjCInterfaceType();
5374 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005375 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005376 SelectorArgs.push_back(EHType);
5377 }
5378 }
5379 }
5380
5381 // We use a cleanup unless there was already a catch all.
5382 if (!HasCatchAll) {
5383 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005384 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005385 }
5386
5387 llvm::Value *Selector =
5388 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5389 SelectorArgs.begin(), SelectorArgs.end(),
5390 "selector");
5391 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005392 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005393 const Stmt *CatchBody = Handlers[i].second;
5394
5395 llvm::BasicBlock *Next = 0;
5396
5397 // The last handler always matches.
5398 if (i + 1 != e) {
5399 assert(CatchParam && "Only last handler can be a catch all.");
5400
5401 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5402 Next = CGF.createBasicBlock("catch.next");
5403 llvm::Value *Id =
5404 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5405 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5406 ObjCTypes.Int8PtrTy));
5407 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5408 Match, Next);
5409
5410 CGF.EmitBlock(Match);
5411 }
5412
5413 if (CatchBody) {
5414 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5415 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5416
5417 // Cleanups must call objc_end_catch.
5418 //
5419 // FIXME: It seems incorrect for objc_begin_catch to be inside
5420 // this context, but this matches gcc.
5421 CGF.PushCleanupBlock(MatchEnd);
5422 CGF.setInvokeDest(MatchHandler);
5423
5424 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005425 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005426
5427 // Bind the catch parameter if it exists.
5428 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005429 ExcObject =
5430 CGF.Builder.CreateBitCast(ExcObject,
5431 CGF.ConvertType(CatchParam->getType()));
5432 // CatchParam is a ParmVarDecl because of the grammar
5433 // construction used to handle this, but for codegen purposes
5434 // we treat this as a local decl.
5435 CGF.EmitLocalBlockVarDecl(*CatchParam);
5436 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005437 }
5438
5439 CGF.ObjCEHValueStack.push_back(ExcObject);
5440 CGF.EmitStmt(CatchBody);
5441 CGF.ObjCEHValueStack.pop_back();
5442
5443 CGF.EmitBranchThroughCleanup(FinallyEnd);
5444
5445 CGF.EmitBlock(MatchHandler);
5446
5447 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5448 // We are required to emit this call to satisfy LLVM, even
5449 // though we don't use the result.
5450 llvm::SmallVector<llvm::Value*, 8> Args;
5451 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005452 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005453 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5454 0));
5455 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5456 CGF.Builder.CreateStore(Exc, RethrowPtr);
5457 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5458
5459 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5460
5461 CGF.EmitBlock(MatchEnd);
5462
5463 // Unfortunately, we also have to generate another EH frame here
5464 // in case this throws.
5465 llvm::BasicBlock *MatchEndHandler =
5466 CGF.createBasicBlock("match.end.handler");
5467 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005468 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005469 Cont, MatchEndHandler,
5470 Args.begin(), Args.begin());
5471
5472 CGF.EmitBlock(Cont);
5473 if (Info.SwitchBlock)
5474 CGF.EmitBlock(Info.SwitchBlock);
5475 if (Info.EndBlock)
5476 CGF.EmitBlock(Info.EndBlock);
5477
5478 CGF.EmitBlock(MatchEndHandler);
5479 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5480 // We are required to emit this call to satisfy LLVM, even
5481 // though we don't use the result.
5482 Args.clear();
5483 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005484 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005485 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5486 0));
5487 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5488 CGF.Builder.CreateStore(Exc, RethrowPtr);
5489 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5490
5491 if (Next)
5492 CGF.EmitBlock(Next);
5493 } else {
5494 assert(!Next && "catchup should be last handler.");
5495
5496 CGF.Builder.CreateStore(Exc, RethrowPtr);
5497 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5498 }
5499 }
5500
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005501 // Pop the cleanup entry, the @finally is outside this cleanup
5502 // scope.
5503 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5504 CGF.setInvokeDest(PrevLandingPad);
5505
5506 CGF.EmitBlock(FinallyBlock);
5507
5508 if (isTry) {
5509 if (const ObjCAtFinallyStmt* FinallyStmt =
5510 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5511 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5512 } else {
5513 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5514 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005515 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005516 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005517
5518 if (Info.SwitchBlock)
5519 CGF.EmitBlock(Info.SwitchBlock);
5520 if (Info.EndBlock)
5521 CGF.EmitBlock(Info.EndBlock);
5522
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005523 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005524 CGF.EmitBranch(FinallyEnd);
5525
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005526 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005527 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005528 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005529 CGF.Builder.CreateUnreachable();
5530
5531 CGF.EmitBlock(FinallyEnd);
5532}
5533
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005534/// EmitThrowStmt - Generate code for a throw statement.
5535void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5536 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005537 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005538 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005539 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005540 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005541 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5542 "Unexpected rethrow outside @catch block.");
5543 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005544 }
5545
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005546 llvm::Value *ExceptionAsObject =
5547 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5548 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5549 if (InvokeDest) {
5550 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005551 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005552 Cont, InvokeDest,
5553 &ExceptionAsObject, &ExceptionAsObject + 1);
5554 CGF.EmitBlock(Cont);
5555 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005556 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005557 CGF.Builder.CreateUnreachable();
5558
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005559 // Clear the insertion point to indicate we are in unreachable code.
5560 CGF.Builder.ClearInsertionPoint();
5561}
Daniel Dunbare588b992009-03-01 04:46:24 +00005562
5563llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005564CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5565 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005566 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005567
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005568 // If we don't need a definition, return the entry if found or check
5569 // if we use an external reference.
5570 if (!ForDefinition) {
5571 if (Entry)
5572 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005573
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005574 // If this type (or a super class) has the __objc_exception__
5575 // attribute, emit an external reference.
5576 if (hasObjCExceptionAttribute(ID))
5577 return Entry =
5578 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5579 llvm::GlobalValue::ExternalLinkage,
5580 0,
5581 (std::string("OBJC_EHTYPE_$_") +
5582 ID->getIdentifier()->getName()),
5583 &CGM.getModule());
5584 }
5585
5586 // Otherwise we need to either make a new entry or fill in the
5587 // initializer.
5588 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005589 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005590 std::string VTableName = "objc_ehtype_vtable";
5591 llvm::GlobalVariable *VTableGV =
5592 CGM.getModule().getGlobalVariable(VTableName);
5593 if (!VTableGV)
5594 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5595 llvm::GlobalValue::ExternalLinkage,
5596 0, VTableName, &CGM.getModule());
5597
5598 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5599
5600 std::vector<llvm::Constant*> Values(3);
5601 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5602 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005603 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005604 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5605
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005606 if (Entry) {
5607 Entry->setInitializer(Init);
5608 } else {
5609 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5610 llvm::GlobalValue::WeakAnyLinkage,
5611 Init,
5612 (std::string("OBJC_EHTYPE_$_") +
5613 ID->getIdentifier()->getName()),
5614 &CGM.getModule());
5615 }
5616
Daniel Dunbar04d40782009-04-14 06:00:08 +00005617 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005618 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005619 Entry->setAlignment(8);
5620
5621 if (ForDefinition) {
5622 Entry->setSection("__DATA,__objc_const");
5623 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5624 } else {
5625 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5626 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005627
5628 return Entry;
5629}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005630
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005631/* *** */
5632
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005633CodeGen::CGObjCRuntime *
5634CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005635 return new CGObjCMac(CGM);
5636}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005637
5638CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005639CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005640 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005641}