blob: 13864d7265e2d3a104b7afd3812f6e5d4aefb394 [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 Dunbar2bebbf02009-05-03 10:46:44 +000038static const llvm::StructType *
39GetConcreteClassStruct(CodeGen::CodeGenModule &CGM,
40 const ObjCInterfaceDecl *OID) {
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000041 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar412f59b2009-04-22 10:28:39 +000042 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
43 return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000044}
45
Daniel Dunbar532d4da2009-05-03 13:15:50 +000046/// FindIvarInterface - Find the interface containing the ivar.
Daniel Dunbara2435782009-04-22 12:00:04 +000047///
Daniel Dunbar532d4da2009-05-03 13:15:50 +000048/// FIXME: We shouldn't need to do this, the containing context should
49/// be fixed.
50static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
51 const ObjCInterfaceDecl *OID,
52 const ObjCIvarDecl *OIVD,
53 unsigned &Index) {
54 const ObjCInterfaceDecl *Super = OID->getSuperClass();
Daniel Dunbara80a0f62009-04-22 17:43:55 +000055
Daniel Dunbar532d4da2009-05-03 13:15:50 +000056 // FIXME: The index here is closely tied to how
57 // ASTContext::getObjCLayout is implemented. This should be fixed to
58 // get the information from the layout directly.
59 Index = 0;
60 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(),
61 IVE = OID->ivar_end(); IVI != IVE; ++IVI, ++Index)
62 if (OIVD == *IVI)
63 return OID;
64
65 // Also look in synthesized ivars.
66 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(Context),
67 E = OID->prop_end(Context); I != E; ++I) {
68 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) {
69 if (OIVD == Ivar)
70 return OID;
71 ++Index;
72 }
Daniel Dunbara80a0f62009-04-22 17:43:55 +000073 }
74
Daniel Dunbar532d4da2009-05-03 13:15:50 +000075 // Otherwise check in the super class.
76 if (Super)
77 return FindIvarInterface(Context, Super, OIVD, Index);
78
79 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000080}
81
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000082static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
83 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000084 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000085 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000086 unsigned Index;
87 const ObjCInterfaceDecl *Container =
88 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
89 assert(Container && "Unable to find ivar container");
90
91 // If we know have an implementation (and the ivar is in it) then
92 // look up in the implementation layout.
93 const ASTRecordLayout *RL;
94 if (ID && ID->getClassInterface() == Container)
95 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
96 else
97 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
98 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000099}
100
101uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
102 const ObjCInterfaceDecl *OID,
103 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000104 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
105}
106
107uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
108 const ObjCImplementationDecl *OID,
109 const ObjCIvarDecl *Ivar) {
110 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +0000111}
112
113LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
114 const ObjCInterfaceDecl *OID,
115 llvm::Value *BaseValue,
116 const ObjCIvarDecl *Ivar,
117 unsigned CVRQualifiers,
118 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000119 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000120 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000121 QualType IvarTy = Ivar->getType();
122 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000123 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000124 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000125 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000126
127 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000128 // We need to compute the bit offset for the bit-field, the offset
129 // is to the byte. Note, there is a subtle invariant here: we can
130 // only call this routine on non-sythesized ivars but we may be
131 // called for synthesized ivars. However, a synthesized ivar can
132 // never be a bit-field so this is safe.
133 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
134
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000135 uint64_t BitFieldSize =
136 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
137 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000138 IvarTy->isSignedIntegerType(),
139 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000140 }
141
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000142 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
143 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000144 LValue::SetObjCIvar(LV, true);
145 return LV;
146}
147
148///
149
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000150namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000151
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000152 typedef std::vector<llvm::Constant*> ConstantVector;
153
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000154 // FIXME: We should find a nicer way to make the labels for
155 // metadata, string concatenation is lame.
156
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000157class ObjCCommonTypesHelper {
158protected:
159 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000160
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000161public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000162 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000163 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000164
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000165 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
166 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000167
168 /// PtrObjectPtrTy - LLVM type for id *
169 const llvm::Type *PtrObjectPtrTy;
170
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000171 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000172 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000173 /// ProtocolPtrTy - LLVM type for external protocol handles
174 /// (typeof(Protocol))
175 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000176
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000177 // SuperCTy - clang type for struct objc_super.
178 QualType SuperCTy;
179 // SuperPtrCTy - clang type for struct objc_super *.
180 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000181
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000182 /// SuperTy - LLVM type for struct objc_super.
183 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000184 /// SuperPtrTy - LLVM type for struct objc_super *.
185 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000186
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000187 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
188 /// in GCC parlance).
189 const llvm::StructType *PropertyTy;
190
191 /// PropertyListTy - LLVM type for struct objc_property_list
192 /// (_prop_list_t in GCC parlance).
193 const llvm::StructType *PropertyListTy;
194 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
195 const llvm::Type *PropertyListPtrTy;
196
197 // MethodTy - LLVM type for struct objc_method.
198 const llvm::StructType *MethodTy;
199
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000200 /// CacheTy - LLVM type for struct objc_cache.
201 const llvm::Type *CacheTy;
202 /// CachePtrTy - LLVM type for struct objc_cache *.
203 const llvm::Type *CachePtrTy;
204
Chris Lattner72db6c32009-04-22 02:44:54 +0000205 llvm::Constant *getGetPropertyFn() {
206 CodeGen::CodeGenTypes &Types = CGM.getTypes();
207 ASTContext &Ctx = CGM.getContext();
208 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
209 llvm::SmallVector<QualType,16> Params;
210 QualType IdType = Ctx.getObjCIdType();
211 QualType SelType = Ctx.getObjCSelType();
212 Params.push_back(IdType);
213 Params.push_back(SelType);
214 Params.push_back(Ctx.LongTy);
215 Params.push_back(Ctx.BoolTy);
216 const llvm::FunctionType *FTy =
217 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
218 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
219 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000220
Chris Lattner72db6c32009-04-22 02:44:54 +0000221 llvm::Constant *getSetPropertyFn() {
222 CodeGen::CodeGenTypes &Types = CGM.getTypes();
223 ASTContext &Ctx = CGM.getContext();
224 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
225 llvm::SmallVector<QualType,16> Params;
226 QualType IdType = Ctx.getObjCIdType();
227 QualType SelType = Ctx.getObjCSelType();
228 Params.push_back(IdType);
229 Params.push_back(SelType);
230 Params.push_back(Ctx.LongTy);
231 Params.push_back(IdType);
232 Params.push_back(Ctx.BoolTy);
233 Params.push_back(Ctx.BoolTy);
234 const llvm::FunctionType *FTy =
235 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
236 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
237 }
238
239 llvm::Constant *getEnumerationMutationFn() {
240 // void objc_enumerationMutation (id)
241 std::vector<const llvm::Type*> Args;
242 Args.push_back(ObjectPtrTy);
243 llvm::FunctionType *FTy =
244 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
245 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
246 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000247
248 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000249 llvm::Constant *getGcReadWeakFn() {
250 // id objc_read_weak (id *)
251 std::vector<const llvm::Type*> Args;
252 Args.push_back(ObjectPtrTy->getPointerTo());
253 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
254 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
255 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000256
257 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000258 llvm::Constant *getGcAssignWeakFn() {
259 // id objc_assign_weak (id, id *)
260 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
261 Args.push_back(ObjectPtrTy->getPointerTo());
262 llvm::FunctionType *FTy =
263 llvm::FunctionType::get(ObjectPtrTy, Args, false);
264 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
265 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000266
267 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000268 llvm::Constant *getGcAssignGlobalFn() {
269 // id objc_assign_global(id, id *)
270 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
271 Args.push_back(ObjectPtrTy->getPointerTo());
272 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
273 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
274 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000275
276 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000277 llvm::Constant *getGcAssignIvarFn() {
278 // id objc_assign_ivar(id, id *)
279 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
280 Args.push_back(ObjectPtrTy->getPointerTo());
281 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
282 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
283 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000284
285 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000286 llvm::Constant *getGcAssignStrongCastFn() {
287 // id objc_assign_global(id, id *)
288 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
289 Args.push_back(ObjectPtrTy->getPointerTo());
290 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
291 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
292 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000293
294 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000295 llvm::Constant *getExceptionThrowFn() {
296 // void objc_exception_throw(id)
297 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
298 llvm::FunctionType *FTy =
299 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
300 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
301 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000302
Daniel Dunbar1c566672009-02-24 01:43:46 +0000303 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000304 llvm::Constant *getSyncEnterFn() {
305 // void objc_sync_enter (id)
306 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
307 llvm::FunctionType *FTy =
308 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
309 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
310 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000311
312 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000313 llvm::Constant *getSyncExitFn() {
314 // void objc_sync_exit (id)
315 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
316 llvm::FunctionType *FTy =
317 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
318 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
319 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000320
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000321 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
322 ~ObjCCommonTypesHelper(){}
323};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000324
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000325/// ObjCTypesHelper - Helper class that encapsulates lazy
326/// construction of varies types used during ObjC generation.
327class ObjCTypesHelper : public ObjCCommonTypesHelper {
328private:
329
Chris Lattner4176b0c2009-04-22 02:32:31 +0000330 llvm::Constant *getMessageSendFn() {
331 // id objc_msgSend (id, SEL, ...)
332 std::vector<const llvm::Type*> Params;
333 Params.push_back(ObjectPtrTy);
334 Params.push_back(SelectorPtrTy);
335 return
336 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
337 Params, true),
338 "objc_msgSend");
339 }
340
341 llvm::Constant *getMessageSendStretFn() {
342 // id objc_msgSend_stret (id, SEL, ...)
343 std::vector<const llvm::Type*> Params;
344 Params.push_back(ObjectPtrTy);
345 Params.push_back(SelectorPtrTy);
346 return
347 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
348 Params, true),
349 "objc_msgSend_stret");
350
351 }
352
353 llvm::Constant *getMessageSendFpretFn() {
354 // FIXME: This should be long double on x86_64?
355 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
356 std::vector<const llvm::Type*> Params;
357 Params.push_back(ObjectPtrTy);
358 Params.push_back(SelectorPtrTy);
359 return
360 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
361 Params,
362 true),
363 "objc_msgSend_fpret");
364
365 }
366
367 llvm::Constant *getMessageSendSuperFn() {
368 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
369 std::vector<const llvm::Type*> Params;
370 Params.push_back(SuperPtrTy);
371 Params.push_back(SelectorPtrTy);
372 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
373 Params, true),
374 "objc_msgSendSuper");
375 }
376 llvm::Constant *getMessageSendSuperStretFn() {
377 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
378 // SEL op, ...)
379 std::vector<const llvm::Type*> Params;
380 Params.push_back(Int8PtrTy);
381 Params.push_back(SuperPtrTy);
382 Params.push_back(SelectorPtrTy);
383 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
384 Params, true),
385 "objc_msgSendSuper_stret");
386 }
387
388 llvm::Constant *getMessageSendSuperFpretFn() {
389 // There is no objc_msgSendSuper_fpret? How can that work?
390 return getMessageSendSuperFn();
391 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000392
393public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000394 /// SymtabTy - LLVM type for struct objc_symtab.
395 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000396 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
397 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000398 /// ModuleTy - LLVM type for struct objc_module.
399 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000400
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000401 /// ProtocolTy - LLVM type for struct objc_protocol.
402 const llvm::StructType *ProtocolTy;
403 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
404 const llvm::Type *ProtocolPtrTy;
405 /// ProtocolExtensionTy - LLVM type for struct
406 /// objc_protocol_extension.
407 const llvm::StructType *ProtocolExtensionTy;
408 /// ProtocolExtensionTy - LLVM type for struct
409 /// objc_protocol_extension *.
410 const llvm::Type *ProtocolExtensionPtrTy;
411 /// MethodDescriptionTy - LLVM type for struct
412 /// objc_method_description.
413 const llvm::StructType *MethodDescriptionTy;
414 /// MethodDescriptionListTy - LLVM type for struct
415 /// objc_method_description_list.
416 const llvm::StructType *MethodDescriptionListTy;
417 /// MethodDescriptionListPtrTy - LLVM type for struct
418 /// objc_method_description_list *.
419 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000420 /// ProtocolListTy - LLVM type for struct objc_property_list.
421 const llvm::Type *ProtocolListTy;
422 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
423 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000424 /// CategoryTy - LLVM type for struct objc_category.
425 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000426 /// ClassTy - LLVM type for struct objc_class.
427 const llvm::StructType *ClassTy;
428 /// ClassPtrTy - LLVM type for struct objc_class *.
429 const llvm::Type *ClassPtrTy;
430 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
431 const llvm::StructType *ClassExtensionTy;
432 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
433 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000434 // IvarTy - LLVM type for struct objc_ivar.
435 const llvm::StructType *IvarTy;
436 /// IvarListTy - LLVM type for struct objc_ivar_list.
437 const llvm::Type *IvarListTy;
438 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
439 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000440 /// MethodListTy - LLVM type for struct objc_method_list.
441 const llvm::Type *MethodListTy;
442 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
443 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000444
445 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
446 const llvm::Type *ExceptionDataTy;
447
Anders Carlsson124526b2008-09-09 10:10:21 +0000448 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000449 llvm::Constant *getExceptionTryEnterFn() {
450 std::vector<const llvm::Type*> Params;
451 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
452 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
453 Params, false),
454 "objc_exception_try_enter");
455 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000456
457 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000458 llvm::Constant *getExceptionTryExitFn() {
459 std::vector<const llvm::Type*> Params;
460 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
461 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
462 Params, false),
463 "objc_exception_try_exit");
464 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000465
466 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000467 llvm::Constant *getExceptionExtractFn() {
468 std::vector<const llvm::Type*> Params;
469 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
470 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
471 Params, false),
472 "objc_exception_extract");
473
474 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000475
476 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000477 llvm::Constant *getExceptionMatchFn() {
478 std::vector<const llvm::Type*> Params;
479 Params.push_back(ClassPtrTy);
480 Params.push_back(ObjectPtrTy);
481 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
482 Params, false),
483 "objc_exception_match");
484
485 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000486
487 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000488 llvm::Constant *getSetJmpFn() {
489 std::vector<const llvm::Type*> Params;
490 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
491 return
492 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
493 Params, false),
494 "_setjmp");
495
496 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000497
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000498public:
499 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000500 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000501
502
Chris Lattner74391b42009-03-22 21:03:39 +0000503 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000504 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000505 }
506
Chris Lattner74391b42009-03-22 21:03:39 +0000507 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000508 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000509 }
510
Chris Lattner74391b42009-03-22 21:03:39 +0000511 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000512 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000513 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000514};
515
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000516/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000517/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000518class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000519public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000520
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000521 // MethodListnfABITy - LLVM for struct _method_list_t
522 const llvm::StructType *MethodListnfABITy;
523
524 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
525 const llvm::Type *MethodListnfABIPtrTy;
526
527 // ProtocolnfABITy = LLVM for struct _protocol_t
528 const llvm::StructType *ProtocolnfABITy;
529
Daniel Dunbar948e2582009-02-15 07:36:20 +0000530 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
531 const llvm::Type *ProtocolnfABIPtrTy;
532
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000533 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
534 const llvm::StructType *ProtocolListnfABITy;
535
536 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
537 const llvm::Type *ProtocolListnfABIPtrTy;
538
539 // ClassnfABITy - LLVM for struct _class_t
540 const llvm::StructType *ClassnfABITy;
541
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000542 // ClassnfABIPtrTy - LLVM for struct _class_t*
543 const llvm::Type *ClassnfABIPtrTy;
544
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000545 // IvarnfABITy - LLVM for struct _ivar_t
546 const llvm::StructType *IvarnfABITy;
547
548 // IvarListnfABITy - LLVM for struct _ivar_list_t
549 const llvm::StructType *IvarListnfABITy;
550
551 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
552 const llvm::Type *IvarListnfABIPtrTy;
553
554 // ClassRonfABITy - LLVM for struct _class_ro_t
555 const llvm::StructType *ClassRonfABITy;
556
557 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
558 const llvm::Type *ImpnfABITy;
559
560 // CategorynfABITy - LLVM for struct _category_t
561 const llvm::StructType *CategorynfABITy;
562
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000563 // New types for nonfragile abi messaging.
564
565 // MessageRefTy - LLVM for:
566 // struct _message_ref_t {
567 // IMP messenger;
568 // SEL name;
569 // };
570 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000571 // MessageRefCTy - clang type for struct _message_ref_t
572 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000573
574 // MessageRefPtrTy - LLVM for struct _message_ref_t*
575 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000576 // MessageRefCPtrTy - clang type for struct _message_ref_t*
577 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000578
Fariborz Jahanianef163782009-02-05 01:13:09 +0000579 // MessengerTy - Type of the messenger (shown as IMP above)
580 const llvm::FunctionType *MessengerTy;
581
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000582 // SuperMessageRefTy - LLVM for:
583 // struct _super_message_ref_t {
584 // SUPER_IMP messenger;
585 // SEL name;
586 // };
587 const llvm::StructType *SuperMessageRefTy;
588
589 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
590 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000591
Chris Lattner1c02f862009-04-22 02:53:24 +0000592 llvm::Constant *getMessageSendFixupFn() {
593 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
594 std::vector<const llvm::Type*> Params;
595 Params.push_back(ObjectPtrTy);
596 Params.push_back(MessageRefPtrTy);
597 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
598 Params, true),
599 "objc_msgSend_fixup");
600 }
601
602 llvm::Constant *getMessageSendFpretFixupFn() {
603 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
604 std::vector<const llvm::Type*> Params;
605 Params.push_back(ObjectPtrTy);
606 Params.push_back(MessageRefPtrTy);
607 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
608 Params, true),
609 "objc_msgSend_fpret_fixup");
610 }
611
612 llvm::Constant *getMessageSendStretFixupFn() {
613 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
614 std::vector<const llvm::Type*> Params;
615 Params.push_back(ObjectPtrTy);
616 Params.push_back(MessageRefPtrTy);
617 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
618 Params, true),
619 "objc_msgSend_stret_fixup");
620 }
621
622 llvm::Constant *getMessageSendIdFixupFn() {
623 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
624 std::vector<const llvm::Type*> Params;
625 Params.push_back(ObjectPtrTy);
626 Params.push_back(MessageRefPtrTy);
627 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
628 Params, true),
629 "objc_msgSendId_fixup");
630 }
631
632 llvm::Constant *getMessageSendIdStretFixupFn() {
633 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
634 std::vector<const llvm::Type*> Params;
635 Params.push_back(ObjectPtrTy);
636 Params.push_back(MessageRefPtrTy);
637 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
638 Params, true),
639 "objc_msgSendId_stret_fixup");
640 }
641 llvm::Constant *getMessageSendSuper2FixupFn() {
642 // id objc_msgSendSuper2_fixup (struct objc_super *,
643 // struct _super_message_ref_t*, ...)
644 std::vector<const llvm::Type*> Params;
645 Params.push_back(SuperPtrTy);
646 Params.push_back(SuperMessageRefPtrTy);
647 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
648 Params, true),
649 "objc_msgSendSuper2_fixup");
650 }
651
652 llvm::Constant *getMessageSendSuper2StretFixupFn() {
653 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
654 // struct _super_message_ref_t*, ...)
655 std::vector<const llvm::Type*> Params;
656 Params.push_back(SuperPtrTy);
657 Params.push_back(SuperMessageRefPtrTy);
658 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
659 Params, true),
660 "objc_msgSendSuper2_stret_fixup");
661 }
662
663
664
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000665 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
666 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000667 llvm::Value *getEHPersonalityPtr() {
668 llvm::Constant *Personality =
669 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
670 std::vector<const llvm::Type*>(),
671 true),
672 "__objc_personality_v0");
673 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
674 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000675
Chris Lattner8a569112009-04-22 02:15:23 +0000676 llvm::Constant *getUnwindResumeOrRethrowFn() {
677 std::vector<const llvm::Type*> Params;
678 Params.push_back(Int8PtrTy);
679 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
680 Params, false),
681 "_Unwind_Resume_or_Rethrow");
682 }
683
684 llvm::Constant *getObjCEndCatchFn() {
685 std::vector<const llvm::Type*> Params;
686 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
687 Params, false),
688 "objc_end_catch");
689
690 }
691
692 llvm::Constant *getObjCBeginCatchFn() {
693 std::vector<const llvm::Type*> Params;
694 Params.push_back(Int8PtrTy);
695 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
696 Params, false),
697 "objc_begin_catch");
698 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000699
700 const llvm::StructType *EHTypeTy;
701 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000702
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000703 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
704 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000705};
706
707class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000708public:
709 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000710 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000711 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000712 unsigned ivar_bytepos;
713 unsigned ivar_size;
714 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
715 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000716
717 // Allow sorting based on byte pos.
718 bool operator<(const GC_IVAR &b) const {
719 return ivar_bytepos < b.ivar_bytepos;
720 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000721 };
722
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000723 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000724 public:
725 unsigned skip;
726 unsigned scan;
727 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
728 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000729 };
730
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000731protected:
732 CodeGen::CodeGenModule &CGM;
733 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000734 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000735
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000736 // gc ivar layout bitmap calculation helper caches.
737 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
738 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000739
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000740 /// LazySymbols - Symbols to generate a lazy reference for. See
741 /// DefinedSymbols and FinishModule().
742 std::set<IdentifierInfo*> LazySymbols;
743
744 /// DefinedSymbols - External symbols which are defined by this
745 /// module. The symbols in this list and LazySymbols are used to add
746 /// special linker symbols which ensure that Objective-C modules are
747 /// linked properly.
748 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000749
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000750 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000751 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000752
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000753 /// MethodVarNames - uniqued method variable names.
754 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000755
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000756 /// MethodVarTypes - uniqued method type signatures. We have to use
757 /// a StringMap here because have no other unique reference.
758 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000759
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000760 /// MethodDefinitions - map of methods which have been defined in
761 /// this translation unit.
762 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000763
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000764 /// PropertyNames - uniqued method variable names.
765 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000766
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000767 /// ClassReferences - uniqued class references.
768 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000769
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000770 /// SelectorReferences - uniqued selector references.
771 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000772
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000773 /// Protocols - Protocols for which an objc_protocol structure has
774 /// been emitted. Forward declarations are handled by creating an
775 /// empty structure whose initializer is filled in when/if defined.
776 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000777
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000778 /// DefinedProtocols - Protocols which have actually been
779 /// defined. We should not need this, see FIXME in GenerateProtocol.
780 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000781
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000782 /// DefinedClasses - List of defined classes.
783 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000784
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000785 /// DefinedCategories - List of defined categories.
786 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000787
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000788 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000789 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000790 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000791
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000792 /// GetNameForMethod - Return a name for the given method.
793 /// \param[out] NameOut - The return value.
794 void GetNameForMethod(const ObjCMethodDecl *OMD,
795 const ObjCContainerDecl *CD,
796 std::string &NameOut);
797
798 /// GetMethodVarName - Return a unique constant for the given
799 /// selector's name. The return value has type char *.
800 llvm::Constant *GetMethodVarName(Selector Sel);
801 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
802 llvm::Constant *GetMethodVarName(const std::string &Name);
803
804 /// GetMethodVarType - Return a unique constant for the given
805 /// selector's name. The return value has type char *.
806
807 // FIXME: This is a horrible name.
808 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000809 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000810
811 /// GetPropertyName - Return a unique constant for the given
812 /// name. The return value has type char *.
813 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
814
815 // FIXME: This can be dropped once string functions are unified.
816 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
817 const Decl *Container);
818
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000819 /// GetClassName - Return a unique constant for the given selector's
820 /// name. The return value has type char *.
821 llvm::Constant *GetClassName(IdentifierInfo *Ident);
822
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000823 /// BuildIvarLayout - Builds ivar layout bitmap for the class
824 /// implementation for the __strong or __weak case.
825 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000826 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
827 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000828
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000829 void BuildAggrIvarRecordLayout(const RecordType *RT,
830 unsigned int BytePos, bool ForStrongLayout,
831 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000832 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
833 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000834 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000835 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000836 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000837 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000838
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000839 /// GetIvarLayoutName - Returns a unique constant for the given
840 /// ivar layout bitmap.
841 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
842 const ObjCCommonTypesHelper &ObjCTypes);
843
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000844 /// EmitPropertyList - Emit the given property list. The return
845 /// value has type PropertyListPtrTy.
846 llvm::Constant *EmitPropertyList(const std::string &Name,
847 const Decl *Container,
848 const ObjCContainerDecl *OCD,
849 const ObjCCommonTypesHelper &ObjCTypes);
850
Fariborz Jahanianda320092009-01-29 19:24:30 +0000851 /// GetProtocolRef - Return a reference to the internal protocol
852 /// description, creating an empty one if it has not been
853 /// defined. The return value has type ProtocolPtrTy.
854 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000855
Chris Lattnercd0ee142009-03-31 08:33:16 +0000856 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000857 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
858 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000859 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000860
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000861 /// CreateMetadataVar - Create a global variable with internal
862 /// linkage for use by the Objective-C runtime.
863 ///
864 /// This is a convenience wrapper which not only creates the
865 /// variable, but also sets the section and alignment and adds the
866 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000867 ///
868 /// \param Name - The variable name.
869 /// \param Init - The variable initializer; this is also used to
870 /// define the type of the variable.
871 /// \param Section - The section the variable should go into, or 0.
872 /// \param Align - The alignment for the variable, or 0.
873 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000874 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000875 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
876 llvm::Constant *Init,
877 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000878 unsigned Align,
879 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000880
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000881 /// GetNamedIvarList - Return the list of ivars in the interface
882 /// itself (not including super classes and not including unnamed
883 /// bitfields).
884 ///
885 /// For the non-fragile ABI, this also includes synthesized property
886 /// ivars.
887 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
888 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
889
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000890public:
891 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
892 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000893
Steve Naroff33fdb732009-03-31 16:53:37 +0000894 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000895
896 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
897 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000898
899 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
900
901 /// GetOrEmitProtocol - Get the protocol object for the given
902 /// declaration, emitting it if necessary. The return value has type
903 /// ProtocolPtrTy.
904 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
905
906 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
907 /// object for the given declaration, emitting it if needed. These
908 /// forward references will be filled in with empty bodies if no
909 /// definition is seen. The return value has type ProtocolPtrTy.
910 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000911};
912
913class CGObjCMac : public CGObjCCommonMac {
914private:
915 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000916 /// EmitImageInfo - Emit the image info marker used to encode some module
917 /// level information.
918 void EmitImageInfo();
919
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000920 /// EmitModuleInfo - Another marker encoding module level
921 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000922 void EmitModuleInfo();
923
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000924 /// EmitModuleSymols - Emit module symbols, the list of defined
925 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000926 llvm::Constant *EmitModuleSymbols();
927
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000928 /// FinishModule - Write out global data structures at the end of
929 /// processing a translation unit.
930 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000931
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000932 /// EmitClassExtension - Generate the class extension structure used
933 /// to store the weak ivar layout and properties. The return value
934 /// has type ClassExtensionPtrTy.
935 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
936
937 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
938 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000939 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000940 const ObjCInterfaceDecl *ID);
941
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000942 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000943 QualType ResultType,
944 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000945 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000946 QualType Arg0Ty,
947 bool IsSuper,
948 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000949
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000950 /// EmitIvarList - Emit the ivar list for the given
951 /// implementation. If ForClass is true the list of class ivars
952 /// (i.e. metaclass ivars) is emitted, otherwise the list of
953 /// interface ivars will be emitted. The return value has type
954 /// IvarListPtrTy.
955 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000956 bool ForClass);
957
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000958 /// EmitMetaClass - Emit a forward reference to the class structure
959 /// for the metaclass of the given interface. The return value has
960 /// type ClassPtrTy.
961 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
962
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000963 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000964 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000965 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
966 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000967 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000968
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000969 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000970
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000971 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000972
973 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000974 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000975 llvm::Constant *EmitMethodList(const std::string &Name,
976 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000977 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000978
979 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000980 /// method declarations.
981 /// - TypeName: The name for the type containing the methods.
982 /// - IsProtocol: True iff these methods are for a protocol.
983 /// - ClassMethds: True iff these are class methods.
984 /// - Required: When true, only "required" methods are
985 /// listed. Similarly, when false only "optional" methods are
986 /// listed. For classes this should always be true.
987 /// - begin, end: The method list to output.
988 ///
989 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000990 llvm::Constant *EmitMethodDescList(const std::string &Name,
991 const char *Section,
992 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000993
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000994 /// GetOrEmitProtocol - Get the protocol object for the given
995 /// declaration, emitting it if necessary. The return value has type
996 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000997 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000998
999 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1000 /// object for the given declaration, emitting it if needed. These
1001 /// forward references will be filled in with empty bodies if no
1002 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001003 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001004
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001005 /// EmitProtocolExtension - Generate the protocol extension
1006 /// structure used to store optional instance and class methods, and
1007 /// protocol properties. The return value has type
1008 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001009 llvm::Constant *
1010 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1011 const ConstantVector &OptInstanceMethods,
1012 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001013
1014 /// EmitProtocolList - Generate the list of referenced
1015 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001016 llvm::Constant *EmitProtocolList(const std::string &Name,
1017 ObjCProtocolDecl::protocol_iterator begin,
1018 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001019
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001020 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1021 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001022 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001023
Fariborz Jahanianda320092009-01-29 19:24:30 +00001024 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001025 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001026
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001027 virtual llvm::Function *ModuleInitFunction();
1028
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001029 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001030 QualType ResultType,
1031 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001032 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001033 bool IsClassMessage,
1034 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001035
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001036 virtual CodeGen::RValue
1037 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001038 QualType ResultType,
1039 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001040 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001041 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001042 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001043 bool IsClassMessage,
1044 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001045
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001046 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001047 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001048
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001049 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001050
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001051 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001052
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001053 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001054
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001055 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001056 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001057
Chris Lattner74391b42009-03-22 21:03:39 +00001058 virtual llvm::Constant *GetPropertyGetFunction();
1059 virtual llvm::Constant *GetPropertySetFunction();
1060 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001061
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001062 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1063 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001064 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1065 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001066 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001067 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001068 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1069 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001070 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1071 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001072 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1073 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001074 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1075 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001076
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001077 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1078 QualType ObjectTy,
1079 llvm::Value *BaseValue,
1080 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001081 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001082 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001083 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001084 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001085};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001086
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001087class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001088private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001089 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001090 llvm::GlobalVariable* ObjCEmptyCacheVar;
1091 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001092
Daniel Dunbar11394522009-04-18 08:51:00 +00001093 /// SuperClassReferences - uniqued super class references.
1094 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1095
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001096 /// MetaClassReferences - uniqued meta class references.
1097 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001098
1099 /// EHTypeReferences - uniqued class ehtype references.
1100 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001101
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001102 /// FinishNonFragileABIModule - Write out global data structures at the end of
1103 /// processing a translation unit.
1104 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001105
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001106 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1107 unsigned InstanceStart,
1108 unsigned InstanceSize,
1109 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001110 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1111 llvm::Constant *IsAGV,
1112 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001113 llvm::Constant *ClassRoGV,
1114 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001115
1116 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1117
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001118 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1119
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001120 /// EmitMethodList - Emit the method list for the given
1121 /// implementation. The return value has type MethodListnfABITy.
1122 llvm::Constant *EmitMethodList(const std::string &Name,
1123 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001124 const ConstantVector &Methods);
1125 /// EmitIvarList - Emit the ivar list for the given
1126 /// implementation. If ForClass is true the list of class ivars
1127 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1128 /// interface ivars will be emitted. The return value has type
1129 /// IvarListnfABIPtrTy.
1130 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001131
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001132 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001133 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001134 unsigned long int offset);
1135
Fariborz Jahanianda320092009-01-29 19:24:30 +00001136 /// GetOrEmitProtocol - Get the protocol object for the given
1137 /// declaration, emitting it if necessary. The return value has type
1138 /// ProtocolPtrTy.
1139 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1140
1141 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1142 /// object for the given declaration, emitting it if needed. These
1143 /// forward references will be filled in with empty bodies if no
1144 /// definition is seen. The return value has type ProtocolPtrTy.
1145 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1146
1147 /// EmitProtocolList - Generate the list of referenced
1148 /// protocols. The return value has type ProtocolListPtrTy.
1149 llvm::Constant *EmitProtocolList(const std::string &Name,
1150 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001151 ObjCProtocolDecl::protocol_iterator end);
1152
1153 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1154 QualType ResultType,
1155 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001156 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001157 QualType Arg0Ty,
1158 bool IsSuper,
1159 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001160
1161 /// GetClassGlobal - Return the global variable for the Objective-C
1162 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001163 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1164
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001165 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001166 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001167 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001168 const ObjCInterfaceDecl *ID);
1169
1170 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1171 /// for the given super class reference.
1172 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1173 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001174
1175 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1176 /// meta-data
1177 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1178 const ObjCInterfaceDecl *ID);
1179
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001180 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1181 /// the given ivar.
1182 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001183 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001184 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001185 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001186
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001187 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1188 /// for the given selector.
1189 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001190
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001191 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001192 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001193 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1194 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001195
1196 const char *getMetaclassSymbolPrefix() const {
1197 return "OBJC_METACLASS_$_";
1198 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001199
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001200 const char *getClassSymbolPrefix() const {
1201 return "OBJC_CLASS_$_";
1202 }
1203
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001204 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001205 uint32_t &InstanceStart,
1206 uint32_t &InstanceSize);
1207
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001208public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001209 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001210 // FIXME. All stubs for now!
1211 virtual llvm::Function *ModuleInitFunction();
1212
1213 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1214 QualType ResultType,
1215 Selector Sel,
1216 llvm::Value *Receiver,
1217 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001218 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001219
1220 virtual CodeGen::RValue
1221 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1222 QualType ResultType,
1223 Selector Sel,
1224 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001225 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001226 llvm::Value *Receiver,
1227 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001228 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001229
1230 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001231 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001232
1233 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001234 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001235
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001236 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001237
1238 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001239 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001240 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001241
Chris Lattner74391b42009-03-22 21:03:39 +00001242 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001243 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001244 }
Chris Lattner74391b42009-03-22 21:03:39 +00001245 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001246 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001247 }
Chris Lattner74391b42009-03-22 21:03:39 +00001248 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001249 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001250 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001251
1252 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001253 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001254 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001255 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001256 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001257 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001258 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001259 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001260 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001261 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001262 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001263 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001264 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001265 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001266 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1267 QualType ObjectTy,
1268 llvm::Value *BaseValue,
1269 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001270 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001271 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001272 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001273 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001274};
1275
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001276} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001277
1278/* *** Helper Functions *** */
1279
1280/// getConstantGEP() - Help routine to construct simple GEPs.
1281static llvm::Constant *getConstantGEP(llvm::Constant *C,
1282 unsigned idx0,
1283 unsigned idx1) {
1284 llvm::Value *Idxs[] = {
1285 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1286 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1287 };
1288 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1289}
1290
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001291/// hasObjCExceptionAttribute - Return true if this class or any super
1292/// class has the __objc_exception__ attribute.
1293static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001294 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001295 return true;
1296 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1297 return hasObjCExceptionAttribute(Super);
1298 return false;
1299}
1300
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001301/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001302
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001303CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1304 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001305{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001306 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001307 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001308}
1309
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001310/// GetClass - Return a reference to the class for the given interface
1311/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001312llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001313 const ObjCInterfaceDecl *ID) {
1314 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001315}
1316
1317/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001318llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001319 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001320}
1321
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001322/// Generate a constant CFString object.
1323/*
1324 struct __builtin_CFString {
1325 const int *isa; // point to __CFConstantStringClassReference
1326 int flags;
1327 const char *str;
1328 long length;
1329 };
1330*/
1331
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001332llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001333 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001334 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001335}
1336
1337/// Generates a message send where the super is the receiver. This is
1338/// a message send to self with special delivery semantics indicating
1339/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001340CodeGen::RValue
1341CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001342 QualType ResultType,
1343 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001344 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001345 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001346 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001347 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001348 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001349 // Create and init a super structure; this is a (receiver, class)
1350 // pair we will pass to objc_msgSendSuper.
1351 llvm::Value *ObjCSuper =
1352 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1353 llvm::Value *ReceiverAsObject =
1354 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1355 CGF.Builder.CreateStore(ReceiverAsObject,
1356 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001357
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001358 // If this is a class message the metaclass is passed as the target.
1359 llvm::Value *Target;
1360 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001361 if (isCategoryImpl) {
1362 // Message sent to 'super' in a class method defined in a category
1363 // implementation requires an odd treatment.
1364 // If we are in a class method, we must retrieve the
1365 // _metaclass_ for the current class, pointed at by
1366 // the class's "isa" pointer. The following assumes that
1367 // isa" is the first ivar in a class (which it must be).
1368 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1369 Target = CGF.Builder.CreateStructGEP(Target, 0);
1370 Target = CGF.Builder.CreateLoad(Target);
1371 }
1372 else {
1373 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1374 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1375 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1376 Target = Super;
1377 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001378 } else {
1379 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1380 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001381 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1382 // and ObjCTypes types.
1383 const llvm::Type *ClassTy =
1384 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001385 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001386 CGF.Builder.CreateStore(Target,
1387 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1388
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001389 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001390 ObjCSuper, ObjCTypes.SuperPtrCTy,
1391 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001392}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001393
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001394/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001395CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001396 QualType ResultType,
1397 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001398 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001399 bool IsClassMessage,
1400 const CallArgList &CallArgs) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001401 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001402 Receiver, CGF.getContext().getObjCIdType(),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001403 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001404}
1405
1406CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001407 QualType ResultType,
1408 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001409 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001410 QualType Arg0Ty,
1411 bool IsSuper,
1412 const CallArgList &CallArgs) {
1413 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001414 if (!IsSuper)
1415 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001416 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1417 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1418 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001419 CGF.getContext().getObjCSelType()));
1420 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001421
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001422 CodeGenTypes &Types = CGM.getTypes();
1423 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian65257ca2009-04-29 22:47:27 +00001424 // FIXME. vararg flag must be true when this API is used for 64bit code gen.
1425 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001426
1427 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001428 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001429 Fn = ObjCTypes.getSendStretFn(IsSuper);
1430 } else if (ResultType->isFloatingType()) {
1431 // FIXME: Sadly, this is wrong. This actually depends on the
1432 // architecture. This happens to be right for x86-32 though.
1433 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1434 } else {
1435 Fn = ObjCTypes.getSendFn(IsSuper);
1436 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001437 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001438 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001439}
1440
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001441llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001442 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001443 // FIXME: I don't understand why gcc generates this, or where it is
1444 // resolved. Investigate. Its also wasteful to look this up over and
1445 // over.
1446 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1447
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001448 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1449 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001450}
1451
Fariborz Jahanianda320092009-01-29 19:24:30 +00001452void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001453 // FIXME: We shouldn't need this, the protocol decl should contain
1454 // enough information to tell us whether this was a declaration or a
1455 // definition.
1456 DefinedProtocols.insert(PD->getIdentifier());
1457
1458 // If we have generated a forward reference to this protocol, emit
1459 // it now. Otherwise do nothing, the protocol objects are lazily
1460 // emitted.
1461 if (Protocols.count(PD->getIdentifier()))
1462 GetOrEmitProtocol(PD);
1463}
1464
Fariborz Jahanianda320092009-01-29 19:24:30 +00001465llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001466 if (DefinedProtocols.count(PD->getIdentifier()))
1467 return GetOrEmitProtocol(PD);
1468 return GetOrEmitProtocolRef(PD);
1469}
1470
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001471/*
1472 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1473 struct _objc_protocol {
1474 struct _objc_protocol_extension *isa;
1475 char *protocol_name;
1476 struct _objc_protocol_list *protocol_list;
1477 struct _objc__method_prototype_list *instance_methods;
1478 struct _objc__method_prototype_list *class_methods
1479 };
1480
1481 See EmitProtocolExtension().
1482*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001483llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1484 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1485
1486 // Early exit if a defining object has already been generated.
1487 if (Entry && Entry->hasInitializer())
1488 return Entry;
1489
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001490 // FIXME: I don't understand why gcc generates this, or where it is
1491 // resolved. Investigate. Its also wasteful to look this up over and
1492 // over.
1493 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1494
Chris Lattner8ec03f52008-11-24 03:54:41 +00001495 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001496
1497 // Construct method lists.
1498 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1499 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001500 for (ObjCProtocolDecl::instmeth_iterator
1501 i = PD->instmeth_begin(CGM.getContext()),
1502 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001503 ObjCMethodDecl *MD = *i;
1504 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1505 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1506 OptInstanceMethods.push_back(C);
1507 } else {
1508 InstanceMethods.push_back(C);
1509 }
1510 }
1511
Douglas Gregor6ab35242009-04-09 21:40:53 +00001512 for (ObjCProtocolDecl::classmeth_iterator
1513 i = PD->classmeth_begin(CGM.getContext()),
1514 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001515 ObjCMethodDecl *MD = *i;
1516 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1517 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1518 OptClassMethods.push_back(C);
1519 } else {
1520 ClassMethods.push_back(C);
1521 }
1522 }
1523
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001524 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001525 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001526 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001527 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001528 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001529 PD->protocol_begin(),
1530 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001531 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001532 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1533 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001534 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1535 InstanceMethods);
1536 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001537 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1538 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001539 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1540 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001541 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1542 Values);
1543
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001544 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001545 // Already created, fix the linkage and update the initializer.
1546 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001547 Entry->setInitializer(Init);
1548 } else {
1549 Entry =
1550 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1551 llvm::GlobalValue::InternalLinkage,
1552 Init,
1553 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1554 &CGM.getModule());
1555 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001556 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001557 UsedGlobals.push_back(Entry);
1558 // FIXME: Is this necessary? Why only for protocol?
1559 Entry->setAlignment(4);
1560 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001561
1562 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001563}
1564
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001565llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001566 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1567
1568 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001569 // We use the initializer as a marker of whether this is a forward
1570 // reference or not. At module finalization we add the empty
1571 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001572 Entry =
1573 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001574 llvm::GlobalValue::ExternalLinkage,
1575 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001576 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001577 &CGM.getModule());
1578 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001579 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001580 UsedGlobals.push_back(Entry);
1581 // FIXME: Is this necessary? Why only for protocol?
1582 Entry->setAlignment(4);
1583 }
1584
1585 return Entry;
1586}
1587
1588/*
1589 struct _objc_protocol_extension {
1590 uint32_t size;
1591 struct objc_method_description_list *optional_instance_methods;
1592 struct objc_method_description_list *optional_class_methods;
1593 struct objc_property_list *instance_properties;
1594 };
1595*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001596llvm::Constant *
1597CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1598 const ConstantVector &OptInstanceMethods,
1599 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001600 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001601 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001602 std::vector<llvm::Constant*> Values(4);
1603 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001604 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001605 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1606 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001607 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1608 OptInstanceMethods);
1609 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001610 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1611 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001612 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1613 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001614 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1615 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001616 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001617
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001618 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001619 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1620 Values[3]->isNullValue())
1621 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1622
1623 llvm::Constant *Init =
1624 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001625
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001626 // No special section, but goes in llvm.used
1627 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1628 Init,
1629 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001630}
1631
1632/*
1633 struct objc_protocol_list {
1634 struct objc_protocol_list *next;
1635 long count;
1636 Protocol *list[];
1637 };
1638*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001639llvm::Constant *
1640CGObjCMac::EmitProtocolList(const std::string &Name,
1641 ObjCProtocolDecl::protocol_iterator begin,
1642 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001643 std::vector<llvm::Constant*> ProtocolRefs;
1644
Daniel Dunbardbc933702008-08-21 21:57:41 +00001645 for (; begin != end; ++begin)
1646 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001647
1648 // Just return null for empty protocol lists
1649 if (ProtocolRefs.empty())
1650 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1651
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001652 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001653 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1654
1655 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001656 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001657 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1658 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1659 Values[2] =
1660 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1661 ProtocolRefs.size()),
1662 ProtocolRefs);
1663
1664 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1665 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001666 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001667 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001668 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1669}
1670
1671/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001672 struct _objc_property {
1673 const char * const name;
1674 const char * const attributes;
1675 };
1676
1677 struct _objc_property_list {
1678 uint32_t entsize; // sizeof (struct _objc_property)
1679 uint32_t prop_count;
1680 struct _objc_property[prop_count];
1681 };
1682*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001683llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1684 const Decl *Container,
1685 const ObjCContainerDecl *OCD,
1686 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001687 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001688 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1689 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001690 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001691 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001692 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001693 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1694 Prop));
1695 }
1696
1697 // Return null for empty list.
1698 if (Properties.empty())
1699 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1700
1701 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001702 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001703 std::vector<llvm::Constant*> Values(3);
1704 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1705 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1706 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1707 Properties.size());
1708 Values[2] = llvm::ConstantArray::get(AT, Properties);
1709 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1710
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001711 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001712 CreateMetadataVar(Name, Init,
1713 (ObjCABI == 2) ? "__DATA, __objc_const" :
1714 "__OBJC,__property,regular,no_dead_strip",
1715 (ObjCABI == 2) ? 8 : 4,
1716 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001717 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001718}
1719
1720/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001721 struct objc_method_description_list {
1722 int count;
1723 struct objc_method_description list[];
1724 };
1725*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001726llvm::Constant *
1727CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1728 std::vector<llvm::Constant*> Desc(2);
1729 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1730 ObjCTypes.SelectorPtrTy);
1731 Desc[1] = GetMethodVarType(MD);
1732 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1733 Desc);
1734}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001735
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001736llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1737 const char *Section,
1738 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001739 // Return null for empty list.
1740 if (Methods.empty())
1741 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1742
1743 std::vector<llvm::Constant*> Values(2);
1744 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1745 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1746 Methods.size());
1747 Values[1] = llvm::ConstantArray::get(AT, Methods);
1748 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1749
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001750 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001751 return llvm::ConstantExpr::getBitCast(GV,
1752 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001753}
1754
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001755/*
1756 struct _objc_category {
1757 char *category_name;
1758 char *class_name;
1759 struct _objc_method_list *instance_methods;
1760 struct _objc_method_list *class_methods;
1761 struct _objc_protocol_list *protocols;
1762 uint32_t size; // <rdar://4585769>
1763 struct _objc_property_list *instance_properties;
1764 };
1765 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001766void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001767 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001768
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001769 // FIXME: This is poor design, the OCD should have a pointer to the
1770 // category decl. Additionally, note that Category can be null for
1771 // the @implementation w/o an @interface case. Sema should just
1772 // create one for us as it does for @implementation so everyone else
1773 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001774 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001775 const ObjCCategoryDecl *Category =
1776 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001777 std::string ExtName(Interface->getNameAsString() + "_" +
1778 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001779
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001780 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001781 for (ObjCCategoryImplDecl::instmeth_iterator
1782 i = OCD->instmeth_begin(CGM.getContext()),
1783 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001784 // Instance methods should always be defined.
1785 InstanceMethods.push_back(GetMethodConstant(*i));
1786 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001787 for (ObjCCategoryImplDecl::classmeth_iterator
1788 i = OCD->classmeth_begin(CGM.getContext()),
1789 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001790 // Class methods should always be defined.
1791 ClassMethods.push_back(GetMethodConstant(*i));
1792 }
1793
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001794 std::vector<llvm::Constant*> Values(7);
1795 Values[0] = GetClassName(OCD->getIdentifier());
1796 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001797 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001798 Values[2] =
1799 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1800 ExtName,
1801 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001802 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001803 Values[3] =
1804 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001805 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001806 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001807 if (Category) {
1808 Values[4] =
1809 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1810 Category->protocol_begin(),
1811 Category->protocol_end());
1812 } else {
1813 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1814 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001815 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001816
1817 // If there is no category @interface then there can be no properties.
1818 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001819 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001820 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001821 } else {
1822 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1823 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001824
1825 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1826 Values);
1827
1828 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001829 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1830 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001831 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001832 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001833}
1834
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001835// FIXME: Get from somewhere?
1836enum ClassFlags {
1837 eClassFlags_Factory = 0x00001,
1838 eClassFlags_Meta = 0x00002,
1839 // <rdr://5142207>
1840 eClassFlags_HasCXXStructors = 0x02000,
1841 eClassFlags_Hidden = 0x20000,
1842 eClassFlags_ABI2_Hidden = 0x00010,
1843 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1844};
1845
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001846/*
1847 struct _objc_class {
1848 Class isa;
1849 Class super_class;
1850 const char *name;
1851 long version;
1852 long info;
1853 long instance_size;
1854 struct _objc_ivar_list *ivars;
1855 struct _objc_method_list *methods;
1856 struct _objc_cache *cache;
1857 struct _objc_protocol_list *protocols;
1858 // Objective-C 1.0 extensions (<rdr://4585769>)
1859 const char *ivar_layout;
1860 struct _objc_class_ext *ext;
1861 };
1862
1863 See EmitClassExtension();
1864 */
1865void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001866 DefinedSymbols.insert(ID->getIdentifier());
1867
Chris Lattner8ec03f52008-11-24 03:54:41 +00001868 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001869 // FIXME: Gross
1870 ObjCInterfaceDecl *Interface =
1871 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001872 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001873 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001874 Interface->protocol_begin(),
1875 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001876 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001877 unsigned Size =
1878 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001879
1880 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001881 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001882 Flags |= eClassFlags_Hidden;
1883
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001884 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001885 for (ObjCImplementationDecl::instmeth_iterator
1886 i = ID->instmeth_begin(CGM.getContext()),
1887 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001888 // Instance methods should always be defined.
1889 InstanceMethods.push_back(GetMethodConstant(*i));
1890 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001891 for (ObjCImplementationDecl::classmeth_iterator
1892 i = ID->classmeth_begin(CGM.getContext()),
1893 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001894 // Class methods should always be defined.
1895 ClassMethods.push_back(GetMethodConstant(*i));
1896 }
1897
Douglas Gregor653f1b12009-04-23 01:02:12 +00001898 for (ObjCImplementationDecl::propimpl_iterator
1899 i = ID->propimpl_begin(CGM.getContext()),
1900 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001901 ObjCPropertyImplDecl *PID = *i;
1902
1903 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1904 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1905
1906 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1907 if (llvm::Constant *C = GetMethodConstant(MD))
1908 InstanceMethods.push_back(C);
1909 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1910 if (llvm::Constant *C = GetMethodConstant(MD))
1911 InstanceMethods.push_back(C);
1912 }
1913 }
1914
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001915 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00001916 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001917 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001918 // Record a reference to the super class.
1919 LazySymbols.insert(Super->getIdentifier());
1920
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001921 Values[ 1] =
1922 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1923 ObjCTypes.ClassPtrTy);
1924 } else {
1925 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1926 }
1927 Values[ 2] = GetClassName(ID->getIdentifier());
1928 // Version is always 0.
1929 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1930 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1931 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001932 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001933 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001934 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001935 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001936 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001937 // cache is always NULL.
1938 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1939 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001940 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001941 Values[11] = EmitClassExtension(ID);
1942 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1943 Values);
1944
1945 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001946 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1947 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001948 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001949 DefinedClasses.push_back(GV);
1950}
1951
1952llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1953 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001954 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001955 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001956 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001957
Daniel Dunbar04d40782009-04-14 06:00:08 +00001958 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001959 Flags |= eClassFlags_Hidden;
1960
1961 std::vector<llvm::Constant*> Values(12);
1962 // The isa for the metaclass is the root of the hierarchy.
1963 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1964 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1965 Root = Super;
1966 Values[ 0] =
1967 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1968 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001969 // The super class for the metaclass is emitted as the name of the
1970 // super class. The runtime fixes this up to point to the
1971 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001972 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1973 Values[ 1] =
1974 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1975 ObjCTypes.ClassPtrTy);
1976 } else {
1977 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1978 }
1979 Values[ 2] = GetClassName(ID->getIdentifier());
1980 // Version is always 0.
1981 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1982 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1983 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001984 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001985 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001986 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001987 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001988 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001989 // cache is always NULL.
1990 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1991 Values[ 9] = Protocols;
1992 // ivar_layout for metaclass is always NULL.
1993 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1994 // The class extension is always unused for metaclasses.
1995 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1996 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1997 Values);
1998
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001999 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002000 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002001
2002 // Check for a forward reference.
2003 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2004 if (GV) {
2005 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2006 "Forward metaclass reference has incorrect type.");
2007 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2008 GV->setInitializer(Init);
2009 } else {
2010 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2011 llvm::GlobalValue::InternalLinkage,
2012 Init, Name,
2013 &CGM.getModule());
2014 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002015 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002016 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002017 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002018
2019 return GV;
2020}
2021
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002022llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002023 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002024
2025 // FIXME: Should we look these up somewhere other than the
2026 // module. Its a bit silly since we only generate these while
2027 // processing an implementation, so exactly one pointer would work
2028 // if know when we entered/exitted an implementation block.
2029
2030 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002031 // Previously, metaclass with internal linkage may have been defined.
2032 // pass 'true' as 2nd argument so it is returned.
2033 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002034 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2035 "Forward metaclass reference has incorrect type.");
2036 return GV;
2037 } else {
2038 // Generate as an external reference to keep a consistent
2039 // module. This will be patched up when we emit the metaclass.
2040 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2041 llvm::GlobalValue::ExternalLinkage,
2042 0,
2043 Name,
2044 &CGM.getModule());
2045 }
2046}
2047
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002048/*
2049 struct objc_class_ext {
2050 uint32_t size;
2051 const char *weak_ivar_layout;
2052 struct _objc_property_list *properties;
2053 };
2054*/
2055llvm::Constant *
2056CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2057 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002058 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002059
2060 std::vector<llvm::Constant*> Values(3);
2061 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002062 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002063 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002064 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002065
2066 // Return null if no extension bits are used.
2067 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2068 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2069
2070 llvm::Constant *Init =
2071 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002072 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002073 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2074 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002075}
2076
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002077/// getInterfaceDeclForIvar - Get the interface declaration node where
2078/// this ivar is declared in.
2079/// FIXME. Ideally, this info should be in the ivar node. But currently
2080/// it is not and prevailing wisdom is that ASTs should not have more
2081/// info than is absolutely needed, even though this info reflects the
2082/// source language.
2083///
2084static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2085 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002086 const ObjCIvarDecl *IVD,
2087 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002088 if (!OI)
2089 return 0;
2090 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2091 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2092 E = OI->ivar_end(); I != E; ++I)
2093 if ((*I)->getIdentifier() == IVD->getIdentifier())
2094 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002095 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002096 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2097 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002098 ObjCPropertyDecl *PDecl = (*I);
2099 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2100 if (IV->getIdentifier() == IVD->getIdentifier())
2101 return OI;
2102 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002103 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002104}
2105
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002106/*
2107 struct objc_ivar {
2108 char *ivar_name;
2109 char *ivar_type;
2110 int ivar_offset;
2111 };
2112
2113 struct objc_ivar_list {
2114 int ivar_count;
2115 struct objc_ivar list[count];
2116 };
2117 */
2118llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002119 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002120 std::vector<llvm::Constant*> Ivars, Ivar(3);
2121
2122 // When emitting the root class GCC emits ivar entries for the
2123 // actual class structure. It is not clear if we need to follow this
2124 // behavior; for now lets try and get away with not doing it. If so,
2125 // the cleanest solution would be to make up an ObjCInterfaceDecl
2126 // for the class.
2127 if (ForClass)
2128 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002129
2130 ObjCInterfaceDecl *OID =
2131 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002132
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002133 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2134 GetNamedIvarList(OID, OIvars);
2135
2136 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2137 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002138 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2139 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002140 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002141 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002142 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002143 }
2144
2145 // Return null for empty list.
2146 if (Ivars.empty())
2147 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2148
2149 std::vector<llvm::Constant*> Values(2);
2150 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2151 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2152 Ivars.size());
2153 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2154 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2155
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002156 llvm::GlobalVariable *GV;
2157 if (ForClass)
2158 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002159 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2160 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002161 else
2162 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2163 + ID->getNameAsString(),
2164 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002165 4, true);
2166 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002167}
2168
2169/*
2170 struct objc_method {
2171 SEL method_name;
2172 char *method_types;
2173 void *method;
2174 };
2175
2176 struct objc_method_list {
2177 struct objc_method_list *obsolete;
2178 int count;
2179 struct objc_method methods_list[count];
2180 };
2181*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002182
2183/// GetMethodConstant - Return a struct objc_method constant for the
2184/// given method if it has been defined. The result is null if the
2185/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002186llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002187 // FIXME: Use DenseMap::lookup
2188 llvm::Function *Fn = MethodDefinitions[MD];
2189 if (!Fn)
2190 return 0;
2191
2192 std::vector<llvm::Constant*> Method(3);
2193 Method[0] =
2194 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2195 ObjCTypes.SelectorPtrTy);
2196 Method[1] = GetMethodVarType(MD);
2197 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2198 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2199}
2200
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002201llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2202 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002203 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002204 // Return null for empty list.
2205 if (Methods.empty())
2206 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2207
2208 std::vector<llvm::Constant*> Values(3);
2209 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2210 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2211 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2212 Methods.size());
2213 Values[2] = llvm::ConstantArray::get(AT, Methods);
2214 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2215
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002216 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002217 return llvm::ConstantExpr::getBitCast(GV,
2218 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002219}
2220
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002221llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002222 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002223 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002224 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002225
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002226 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002227 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002228 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002229 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002230 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002231 llvm::GlobalValue::InternalLinkage,
2232 Name,
2233 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002234 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002235
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002236 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002237}
2238
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002239/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002240uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2241 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002242 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002243 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002244 if (!OI)
2245 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002246 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002247}
2248
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002249llvm::GlobalVariable *
2250CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2251 llvm::Constant *Init,
2252 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002253 unsigned Align,
2254 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002255 const llvm::Type *Ty = Init->getType();
2256 llvm::GlobalVariable *GV =
2257 new llvm::GlobalVariable(Ty, false,
2258 llvm::GlobalValue::InternalLinkage,
2259 Init,
2260 Name,
2261 &CGM.getModule());
2262 if (Section)
2263 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002264 if (Align)
2265 GV->setAlignment(Align);
2266 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002267 UsedGlobals.push_back(GV);
2268 return GV;
2269}
2270
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002271llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002272 // Abuse this interface function as a place to finalize.
2273 FinishModule();
2274
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002275 return NULL;
2276}
2277
Chris Lattner74391b42009-03-22 21:03:39 +00002278llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002279 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002280}
2281
Chris Lattner74391b42009-03-22 21:03:39 +00002282llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002283 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002284}
2285
Chris Lattner74391b42009-03-22 21:03:39 +00002286llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002287 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002288}
2289
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002290/*
2291
2292Objective-C setjmp-longjmp (sjlj) Exception Handling
2293--
2294
2295The basic framework for a @try-catch-finally is as follows:
2296{
2297 objc_exception_data d;
2298 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002299 bool _call_try_exit = true;
2300
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002301 objc_exception_try_enter(&d);
2302 if (!setjmp(d.jmp_buf)) {
2303 ... try body ...
2304 } else {
2305 // exception path
2306 id _caught = objc_exception_extract(&d);
2307
2308 // enter new try scope for handlers
2309 if (!setjmp(d.jmp_buf)) {
2310 ... match exception and execute catch blocks ...
2311
2312 // fell off end, rethrow.
2313 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002314 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002315 } else {
2316 // exception in catch block
2317 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002318 _call_try_exit = false;
2319 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002320 }
2321 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002322 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002323
2324finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002325 if (_call_try_exit)
2326 objc_exception_try_exit(&d);
2327
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002328 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002329 ... dispatch to finally destination ...
2330
2331finally_rethrow:
2332 objc_exception_throw(_rethrow);
2333
2334finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002335}
2336
2337This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002338uses _rethrow to determine if objc_exception_try_exit should be called
2339and if the object should be rethrown. This breaks in the face of
2340throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002341
2342We specialize this framework for a few particular circumstances:
2343
2344 - If there are no catch blocks, then we avoid emitting the second
2345 exception handling context.
2346
2347 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2348 e)) we avoid emitting the code to rethrow an uncaught exception.
2349
2350 - FIXME: If there is no @finally block we can do a few more
2351 simplifications.
2352
2353Rethrows and Jumps-Through-Finally
2354--
2355
2356Support for implicit rethrows and jumping through the finally block is
2357handled by storing the current exception-handling context in
2358ObjCEHStack.
2359
Daniel Dunbar898d5082008-09-30 01:06:03 +00002360In order to implement proper @finally semantics, we support one basic
2361mechanism for jumping through the finally block to an arbitrary
2362destination. Constructs which generate exits from a @try or @catch
2363block use this mechanism to implement the proper semantics by chaining
2364jumps, as necessary.
2365
2366This mechanism works like the one used for indirect goto: we
2367arbitrarily assign an ID to each destination and store the ID for the
2368destination in a variable prior to entering the finally block. At the
2369end of the finally block we simply create a switch to the proper
2370destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002371
2372Code gen for @synchronized(expr) stmt;
2373Effectively generating code for:
2374objc_sync_enter(expr);
2375@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002376*/
2377
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002378void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2379 const Stmt &S) {
2380 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002381 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002382 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002383 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002384 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2385 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2386 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002387
2388 // For @synchronized, call objc_sync_enter(sync.expr). The
2389 // evaluation of the expression must occur before we enter the
2390 // @synchronized. We can safely avoid a temp here because jumps into
2391 // @synchronized are illegal & this will dominate uses.
2392 llvm::Value *SyncArg = 0;
2393 if (!isTry) {
2394 SyncArg =
2395 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2396 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002397 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002398 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002399
2400 // Push an EH context entry, used for handling rethrows and jumps
2401 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002402 CGF.PushCleanupBlock(FinallyBlock);
2403
Anders Carlsson273558f2009-02-07 21:37:21 +00002404 CGF.ObjCEHValueStack.push_back(0);
2405
Daniel Dunbar898d5082008-09-30 01:06:03 +00002406 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002407 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2408 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002409 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2410 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002411 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2412 "_call_try_exit");
2413 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2414
Anders Carlsson80f25672008-09-09 17:59:25 +00002415 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002416 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002417 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2418 "jmpbufarray");
2419 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002420 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002421 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002422
Daniel Dunbar55e87422008-11-11 02:29:29 +00002423 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2424 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002425 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002426 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002427
2428 // Emit the @try block.
2429 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002430 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2431 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002432 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002433
2434 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002435 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002436
2437 // Retrieve the exception object. We may emit multiple blocks but
2438 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002439 llvm::Value *Caught =
2440 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2441 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002442 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002443 if (!isTry)
2444 {
2445 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002446 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002447 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002448 }
2449 else if (const ObjCAtCatchStmt* CatchStmt =
2450 cast<ObjCAtTryStmt>(S).getCatchStmts())
2451 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002452 // Enter a new exception try block (in case a @catch block throws
2453 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002454 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002455
Chris Lattner34b02a12009-04-22 02:26:14 +00002456 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002457 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002458 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002459
Daniel Dunbar55e87422008-11-11 02:29:29 +00002460 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2461 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002462 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002463
2464 CGF.EmitBlock(CatchBlock);
2465
Daniel Dunbar55e40722008-09-27 07:03:52 +00002466 // Handle catch list. As a special case we check if everything is
2467 // matched and avoid generating code for falling off the end if
2468 // so.
2469 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002470 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002471 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002472
Steve Naroff7ba138a2009-03-03 19:52:17 +00002473 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002474 const PointerType *PT = 0;
2475
Anders Carlsson80f25672008-09-09 17:59:25 +00002476 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002477 if (!CatchParam) {
2478 AllMatched = true;
2479 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002480 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002481
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002482 // catch(id e) always matches.
2483 // FIXME: For the time being we also match id<X>; this should
2484 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002485 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002486 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002487 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002488 }
2489
Daniel Dunbar55e40722008-09-27 07:03:52 +00002490 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002491 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002492 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002493 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002494 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002495 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002496
Anders Carlssondde0a942008-09-11 09:15:33 +00002497 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002498 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002499 break;
2500 }
2501
Daniel Dunbar129271a2008-09-27 07:36:24 +00002502 assert(PT && "Unexpected non-pointer type in @catch");
2503 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002504 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002505 assert(ObjCType && "Catch parameter must have Objective-C type!");
2506
2507 // Check if the @catch block matches the exception object.
2508 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2509
Chris Lattner34b02a12009-04-22 02:26:14 +00002510 llvm::Value *Match =
2511 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2512 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002513
Daniel Dunbar55e87422008-11-11 02:29:29 +00002514 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002515
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002516 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002517 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002518
2519 // Emit the @catch block.
2520 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002521 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002522 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002523
2524 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002525 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002526 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002527 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002528
2529 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002530 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002531
2532 CGF.EmitBlock(NextCatchBlock);
2533 }
2534
Daniel Dunbar55e40722008-09-27 07:03:52 +00002535 if (!AllMatched) {
2536 // None of the handlers caught the exception, so store it to be
2537 // rethrown at the end of the @finally block.
2538 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002539 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002540 }
2541
2542 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002543 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002544 CGF.Builder.CreateStore(
2545 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2546 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002547 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002548 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002549 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002550 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002551 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002552 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002553 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002554 }
2555
Daniel Dunbar898d5082008-09-30 01:06:03 +00002556 // Pop the exception-handling stack entry. It is important to do
2557 // this now, because the code in the @finally block is not in this
2558 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002559 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2560
Anders Carlsson273558f2009-02-07 21:37:21 +00002561 CGF.ObjCEHValueStack.pop_back();
2562
Anders Carlsson80f25672008-09-09 17:59:25 +00002563 // Emit the @finally block.
2564 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002565 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2566
2567 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2568
2569 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002570 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002571
2572 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002573 if (isTry) {
2574 if (const ObjCAtFinallyStmt* FinallyStmt =
2575 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2576 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002577 } else {
2578 // Emit objc_sync_exit(expr); as finally's sole statement for
2579 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002580 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002581 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002582
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002583 // Emit the switch block
2584 if (Info.SwitchBlock)
2585 CGF.EmitBlock(Info.SwitchBlock);
2586 if (Info.EndBlock)
2587 CGF.EmitBlock(Info.EndBlock);
2588
Daniel Dunbar898d5082008-09-30 01:06:03 +00002589 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002590 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002591 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002592 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002593
2594 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002595}
2596
2597void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002598 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002599 llvm::Value *ExceptionAsObject;
2600
2601 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2602 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2603 ExceptionAsObject =
2604 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2605 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002606 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002607 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002608 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002609 }
2610
Chris Lattnerbbccd612009-04-22 02:38:11 +00002611 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002612 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002613
2614 // Clear the insertion point to indicate we are in unreachable code.
2615 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002616}
2617
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002618/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002619/// object: objc_read_weak (id *src)
2620///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002621llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002622 llvm::Value *AddrWeakObj)
2623{
Eli Friedman8339b352009-03-07 03:57:15 +00002624 const llvm::Type* DestTy =
2625 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002626 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002627 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002628 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002629 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002630 return read_weak;
2631}
2632
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002633/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2634/// objc_assign_weak (id src, id *dst)
2635///
2636void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2637 llvm::Value *src, llvm::Value *dst)
2638{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002639 const llvm::Type * SrcTy = src->getType();
2640 if (!isa<llvm::PointerType>(SrcTy)) {
2641 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2642 assert(Size <= 8 && "does not support size > 8");
2643 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2644 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002645 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2646 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002647 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2648 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002649 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002650 src, dst, "weakassign");
2651 return;
2652}
2653
Fariborz Jahanian58626502008-11-19 00:59:10 +00002654/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2655/// objc_assign_global (id src, id *dst)
2656///
2657void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2658 llvm::Value *src, llvm::Value *dst)
2659{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002660 const llvm::Type * SrcTy = src->getType();
2661 if (!isa<llvm::PointerType>(SrcTy)) {
2662 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2663 assert(Size <= 8 && "does not support size > 8");
2664 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2665 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002666 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2667 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002668 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2669 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002670 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002671 src, dst, "globalassign");
2672 return;
2673}
2674
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002675/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2676/// objc_assign_ivar (id src, id *dst)
2677///
2678void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2679 llvm::Value *src, llvm::Value *dst)
2680{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002681 const llvm::Type * SrcTy = src->getType();
2682 if (!isa<llvm::PointerType>(SrcTy)) {
2683 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2684 assert(Size <= 8 && "does not support size > 8");
2685 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2686 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002687 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2688 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002689 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2690 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002691 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002692 src, dst, "assignivar");
2693 return;
2694}
2695
Fariborz Jahanian58626502008-11-19 00:59:10 +00002696/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2697/// objc_assign_strongCast (id src, id *dst)
2698///
2699void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2700 llvm::Value *src, llvm::Value *dst)
2701{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002702 const llvm::Type * SrcTy = src->getType();
2703 if (!isa<llvm::PointerType>(SrcTy)) {
2704 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2705 assert(Size <= 8 && "does not support size > 8");
2706 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2707 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002708 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2709 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002710 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2711 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002712 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002713 src, dst, "weakassign");
2714 return;
2715}
2716
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002717/// EmitObjCValueForIvar - Code Gen for ivar reference.
2718///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002719LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2720 QualType ObjectTy,
2721 llvm::Value *BaseValue,
2722 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002723 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002724 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002725 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2726 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002727}
2728
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002729llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002730 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002731 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002732 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002733 return llvm::ConstantInt::get(
2734 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2735 Offset);
2736}
2737
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002738/* *** Private Interface *** */
2739
2740/// EmitImageInfo - Emit the image info marker used to encode some module
2741/// level information.
2742///
2743/// See: <rdr://4810609&4810587&4810587>
2744/// struct IMAGE_INFO {
2745/// unsigned version;
2746/// unsigned flags;
2747/// };
2748enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002749 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2750 // this implies.
2751 eImageInfo_GarbageCollected = (1 << 1),
2752 eImageInfo_GCOnly = (1 << 2),
2753 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2754
2755 // A flag indicating that the module has no instances of an
2756 // @synthesize of a superclass variable. <rdar://problem/6803242>
2757 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002758};
2759
2760void CGObjCMac::EmitImageInfo() {
2761 unsigned version = 0; // Version is unused?
2762 unsigned flags = 0;
2763
2764 // FIXME: Fix and continue?
2765 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2766 flags |= eImageInfo_GarbageCollected;
2767 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2768 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002769
2770 // We never allow @synthesize of a superclass property.
2771 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002772
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002773 // Emitted as int[2];
2774 llvm::Constant *values[2] = {
2775 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2776 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2777 };
2778 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002779
2780 const char *Section;
2781 if (ObjCABI == 1)
2782 Section = "__OBJC, __image_info,regular";
2783 else
2784 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002785 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002786 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2787 llvm::ConstantArray::get(AT, values, 2),
2788 Section,
2789 0,
2790 true);
2791 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002792}
2793
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002794
2795// struct objc_module {
2796// unsigned long version;
2797// unsigned long size;
2798// const char *name;
2799// Symtab symtab;
2800// };
2801
2802// FIXME: Get from somewhere
2803static const int ModuleVersion = 7;
2804
2805void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002806 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002807
2808 std::vector<llvm::Constant*> Values(4);
2809 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2810 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002811 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002812 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002813 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002814 CreateMetadataVar("\01L_OBJC_MODULES",
2815 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2816 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002817 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002818}
2819
2820llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002821 unsigned NumClasses = DefinedClasses.size();
2822 unsigned NumCategories = DefinedCategories.size();
2823
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002824 // Return null if no symbols were defined.
2825 if (!NumClasses && !NumCategories)
2826 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2827
2828 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002829 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2830 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2831 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2832 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2833
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002834 // The runtime expects exactly the list of defined classes followed
2835 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002836 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002837 for (unsigned i=0; i<NumClasses; i++)
2838 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2839 ObjCTypes.Int8PtrTy);
2840 for (unsigned i=0; i<NumCategories; i++)
2841 Symbols[NumClasses + i] =
2842 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2843 ObjCTypes.Int8PtrTy);
2844
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002845 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002846 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002847 NumClasses + NumCategories),
2848 Symbols);
2849
2850 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2851
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002852 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002853 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2854 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002855 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002856 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2857}
2858
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002859llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002860 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002861 LazySymbols.insert(ID->getIdentifier());
2862
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002863 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2864
2865 if (!Entry) {
2866 llvm::Constant *Casted =
2867 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2868 ObjCTypes.ClassPtrTy);
2869 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002870 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2871 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002872 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002873 }
2874
2875 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002876}
2877
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002878llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002879 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2880
2881 if (!Entry) {
2882 llvm::Constant *Casted =
2883 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2884 ObjCTypes.SelectorPtrTy);
2885 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002886 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2887 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002888 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002889 }
2890
2891 return Builder.CreateLoad(Entry, false, "tmp");
2892}
2893
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002894llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002895 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002896
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002897 if (!Entry)
2898 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2899 llvm::ConstantArray::get(Ident->getName()),
2900 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002901 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002902
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002903 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002904}
2905
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002906/// GetIvarLayoutName - Returns a unique constant for the given
2907/// ivar layout bitmap.
2908llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2909 const ObjCCommonTypesHelper &ObjCTypes) {
2910 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2911}
2912
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002913static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2914 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002915 if (FQT.isObjCGCStrong())
2916 return QualType::Strong;
2917
2918 if (FQT.isObjCGCWeak())
2919 return QualType::Weak;
2920
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002921 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002922 return QualType::Strong;
2923
2924 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002925 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002926
2927 return QualType::GCNone;
2928}
2929
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002930void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2931 unsigned int BytePos,
2932 bool ForStrongLayout,
2933 bool &HasUnion) {
2934 const RecordDecl *RD = RT->getDecl();
2935 // FIXME - Use iterator.
2936 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2937 RD->field_end(CGM.getContext()));
2938 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2939 const llvm::StructLayout *RecLayout =
2940 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2941
2942 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2943 ForStrongLayout, HasUnion);
2944}
2945
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002946void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2947 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002948 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002949 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002950 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002951 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002952 bool IsUnion = (RD && RD->isUnion());
2953 uint64_t MaxUnionIvarSize = 0;
2954 uint64_t MaxSkippedUnionIvarSize = 0;
2955 FieldDecl *MaxField = 0;
2956 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002957 FieldDecl *LastFieldBitfield = 0;
2958
Chris Lattnerf1690852009-03-31 08:48:01 +00002959 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002960 if (RecFields.empty())
2961 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002962 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002963 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002964 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2965 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2966
Chris Lattnerf1690852009-03-31 08:48:01 +00002967 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002968 FieldDecl *Field = RecFields[i];
2969 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002970 if (!Field->getIdentifier() || Field->isBitField()) {
2971 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002972 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002973 }
2974 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002975 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002976 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002977 if (FQT->isUnionType())
2978 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002979
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002980 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
2981 BytePos + GetFieldBaseOffset(OI, Layout, Field),
2982 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002983 continue;
2984 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002985
2986 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002987 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002988 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002989 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002990 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002991 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002992 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2993 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002994 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002995 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002996 FQT = CArray->getElementType();
2997 }
2998
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002999 assert(!FQT->isUnionType() &&
3000 "layout for array of unions not supported");
3001 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003002 int OldIndex = IvarsInfo.size() - 1;
3003 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003004
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003005 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003006 BuildAggrIvarRecordLayout(RT,
3007 BytePos + GetFieldBaseOffset(OI, Layout,
3008 Field),
3009 ForStrongLayout, HasUnion);
3010
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003011 // Replicate layout information for each array element. Note that
3012 // one element is already done.
3013 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003014 for (int FirstIndex = IvarsInfo.size() - 1,
3015 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003016 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003017 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3018 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3019 IvarsInfo[i].ivar_size));
3020 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3021 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3022 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003023 }
3024 continue;
3025 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003026 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003027 // At this point, we are done with Record/Union and array there of.
3028 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003029 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003030
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003031 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003032 if ((ForStrongLayout && GCAttr == QualType::Strong)
3033 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003034 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003035 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003036 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003037 MaxUnionIvarSize = UnionIvarSize;
3038 MaxField = Field;
3039 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003040 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003041 IvarsInfo.push_back(GC_IVAR(BytePos + GetFieldBaseOffset(OI, Layout,
3042 Field),
3043 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003044 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003045 } else if ((ForStrongLayout &&
3046 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3047 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3048 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003049 // FIXME: Why the asymmetry? We divide by word size in bits on
3050 // other side.
3051 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003052 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003053 MaxSkippedUnionIvarSize = UnionIvarSize;
3054 MaxSkippedField = Field;
3055 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003056 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003057 // FIXME: Why the asymmetry, we divide by byte size in bits here?
3058 SkipIvars.push_back(GC_IVAR(BytePos + GetFieldBaseOffset(OI, Layout,
3059 Field),
3060 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003061 }
3062 }
3063 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003064
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003065 if (LastFieldBitfield) {
3066 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003067 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3068 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003069 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003070 GC_IVAR skivar;
3071 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3072 LastFieldBitfield);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003073 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3074 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003075 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003076 }
3077
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003078 if (MaxField)
3079 IvarsInfo.push_back(GC_IVAR(BytePos + GetFieldBaseOffset(OI, Layout,
3080 MaxField),
3081 MaxUnionIvarSize));
3082 if (MaxSkippedField)
3083 SkipIvars.push_back(GC_IVAR(BytePos + GetFieldBaseOffset(OI, Layout,
3084 MaxSkippedField),
3085 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003086}
3087
3088/// BuildIvarLayout - Builds ivar layout bitmap for the class
3089/// implementation for the __strong or __weak case.
3090/// The layout map displays which words in ivar list must be skipped
3091/// and which must be scanned by GC (see below). String is built of bytes.
3092/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3093/// of words to skip and right nibble is count of words to scan. So, each
3094/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3095/// represented by a 0x00 byte which also ends the string.
3096/// 1. when ForStrongLayout is true, following ivars are scanned:
3097/// - id, Class
3098/// - object *
3099/// - __strong anything
3100///
3101/// 2. When ForStrongLayout is false, following ivars are scanned:
3102/// - __weak anything
3103///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003104llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003105 const ObjCImplementationDecl *OMD,
3106 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003107 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003108
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003109 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003110 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3111 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3112 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003113
Chris Lattnerf1690852009-03-31 08:48:01 +00003114 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003115 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003116 CGM.getContext().CollectObjCIvars(OI, RecFields);
3117 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003118 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003119
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003120 SkipIvars.clear();
3121 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003122
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00003123 const llvm::StructLayout *Layout =
3124 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003125 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, hasUnion);
3126 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003127 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003128
3129 // Sort on byte position in case we encounterred a union nested in
3130 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003131 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003132 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003133 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003134 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003135
3136 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003137 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003138 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003139 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003140 if (IvarsInfo[0].ivar_bytepos == 0) {
3141 WordsToSkip = 0;
3142 WordsToScan = IvarsInfo[0].ivar_size;
3143 }
3144 else {
3145 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3146 WordsToScan = IvarsInfo[0].ivar_size;
3147 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003148 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003149 {
3150 unsigned int TailPrevGCObjC =
3151 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3152 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3153 {
3154 // consecutive 'scanned' object pointers.
3155 WordsToScan += IvarsInfo[i].ivar_size;
3156 }
3157 else
3158 {
3159 // Skip over 'gc'able object pointer which lay over each other.
3160 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3161 continue;
3162 // Must skip over 1 or more words. We save current skip/scan values
3163 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003164 SKIP_SCAN SkScan;
3165 SkScan.skip = WordsToSkip;
3166 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003167 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003168
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003169 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003170 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3171 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003172 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003173 WordsToSkip = 0;
3174 WordsToScan = IvarsInfo[i].ivar_size;
3175 }
3176 }
3177 if (WordsToScan > 0)
3178 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003179 SKIP_SCAN SkScan;
3180 SkScan.skip = WordsToSkip;
3181 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003182 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003183 }
3184
3185 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003186 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003187 {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003188 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003189 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003190 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3191 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003192 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003193 IvarsInfo[LastIndex].ivar_bytepos +
3194 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003195 BytesSkipped = (LastByteSkipped > LastByteScanned);
3196 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3197 if (BytesSkipped)
3198 {
3199 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003200 SKIP_SCAN SkScan;
3201 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3202 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003203 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003204 }
3205 }
3206 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3207 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003208 int SkipScan = SkipScanIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003209 for (int i = 0; i <= SkipScan; i++)
3210 {
3211 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3212 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3213 // 0xM0 followed by 0x0N detected.
3214 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3215 for (int j = i+1; j < SkipScan; j++)
3216 SkipScanIvars[j] = SkipScanIvars[j+1];
3217 --SkipScan;
3218 }
3219 }
3220
3221 // Generate the string.
3222 std::string BitMap;
3223 for (int i = 0; i <= SkipScan; i++)
3224 {
3225 unsigned char byte;
3226 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3227 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3228 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3229 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3230
3231 if (skip_small > 0 || skip_big > 0)
3232 BytesSkipped = true;
3233 // first skip big.
3234 for (unsigned int ix = 0; ix < skip_big; ix++)
3235 BitMap += (unsigned char)(0xf0);
3236
3237 // next (skip small, scan)
3238 if (skip_small)
3239 {
3240 byte = skip_small << 4;
3241 if (scan_big > 0)
3242 {
3243 byte |= 0xf;
3244 --scan_big;
3245 }
3246 else if (scan_small)
3247 {
3248 byte |= scan_small;
3249 scan_small = 0;
3250 }
3251 BitMap += byte;
3252 }
3253 // next scan big
3254 for (unsigned int ix = 0; ix < scan_big; ix++)
3255 BitMap += (unsigned char)(0x0f);
3256 // last scan small
3257 if (scan_small)
3258 {
3259 byte = scan_small;
3260 BitMap += byte;
3261 }
3262 }
3263 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003264 unsigned char zero = 0;
3265 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003266
3267 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3268 printf("\n%s ivar layout for class '%s': ",
3269 ForStrongLayout ? "strong" : "weak",
3270 OMD->getClassInterface()->getNameAsCString());
3271 const unsigned char *s = (unsigned char*)BitMap.c_str();
3272 for (unsigned i = 0; i < BitMap.size(); i++)
3273 if (!(s[i] & 0xf0))
3274 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3275 else
3276 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3277 printf("\n");
3278 }
3279
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003280 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3281 // final layout.
3282 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003283 return llvm::Constant::getNullValue(PtrTy);
3284 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3285 llvm::ConstantArray::get(BitMap.c_str()),
3286 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003287 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003288 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003289}
3290
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003291llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003292 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3293
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003294 // FIXME: Avoid std::string copying.
3295 if (!Entry)
3296 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3297 llvm::ConstantArray::get(Sel.getAsString()),
3298 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003299 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003300
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003301 return getConstantGEP(Entry, 0, 0);
3302}
3303
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003304// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003305llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003306 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3307}
3308
3309// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003310llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003311 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3312}
3313
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003314llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003315 std::string TypeStr;
3316 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3317
3318 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003319
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003320 if (!Entry)
3321 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3322 llvm::ConstantArray::get(TypeStr),
3323 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003324 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003325
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003326 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003327}
3328
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003329llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003330 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003331 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3332 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003333
3334 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3335
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003336 if (!Entry)
3337 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3338 llvm::ConstantArray::get(TypeStr),
3339 "__TEXT,__cstring,cstring_literals",
3340 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003341
3342 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003343}
3344
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003345// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003346llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003347 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3348
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003349 if (!Entry)
3350 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3351 llvm::ConstantArray::get(Ident->getName()),
3352 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003353 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003354
3355 return getConstantGEP(Entry, 0, 0);
3356}
3357
3358// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003359// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003360llvm::Constant *
3361 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3362 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003363 std::string TypeStr;
3364 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003365 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3366}
3367
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003368void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3369 const ObjCContainerDecl *CD,
3370 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003371 NameOut = '\01';
3372 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003373 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003374 assert (CD && "Missing container decl in GetNameForMethod");
3375 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003376 if (const ObjCCategoryImplDecl *CID =
3377 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3378 NameOut += '(';
3379 NameOut += CID->getNameAsString();
3380 NameOut+= ')';
3381 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003382 NameOut += ' ';
3383 NameOut += D->getSelector().getAsString();
3384 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003385}
3386
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003387void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003388 EmitModuleInfo();
3389
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003390 // Emit the dummy bodies for any protocols which were referenced but
3391 // never defined.
3392 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3393 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3394 if (i->second->hasInitializer())
3395 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003396
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003397 std::vector<llvm::Constant*> Values(5);
3398 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3399 Values[1] = GetClassName(i->first);
3400 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3401 Values[3] = Values[4] =
3402 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3403 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3404 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3405 Values));
3406 }
3407
3408 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003409 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003410 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003411 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003412 }
3413
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003414 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003415 llvm::GlobalValue *GV =
3416 new llvm::GlobalVariable(AT, false,
3417 llvm::GlobalValue::AppendingLinkage,
3418 llvm::ConstantArray::get(AT, Used),
3419 "llvm.used",
3420 &CGM.getModule());
3421
3422 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003423
3424 // Add assembler directives to add lazy undefined symbol references
3425 // for classes which are referenced but not defined. This is
3426 // important for correct linker interaction.
3427
3428 // FIXME: Uh, this isn't particularly portable.
3429 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003430
3431 if (!CGM.getModule().getModuleInlineAsm().empty())
3432 s << "\n";
3433
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003434 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3435 e = LazySymbols.end(); i != e; ++i) {
3436 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3437 }
3438 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3439 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003440 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003441 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3442 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003443
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003444 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003445}
3446
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003447CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003448 : CGObjCCommonMac(cgm),
3449 ObjCTypes(cgm)
3450{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003451 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003452 ObjCABI = 2;
3453}
3454
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003455/* *** */
3456
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003457ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3458: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003459{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003460 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3461 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003462
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003463 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003464 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003465 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003466 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003467 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3468
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003469 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003470 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003471 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003472
3473 // FIXME: It would be nice to unify this with the opaque type, so
3474 // that the IR comes out a bit cleaner.
3475 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3476 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003477
3478 // I'm not sure I like this. The implicit coordination is a bit
3479 // gross. We should solve this in a reasonable fashion because this
3480 // is a pretty common task (match some runtime data structure with
3481 // an LLVM data structure).
3482
3483 // FIXME: This is leaked.
3484 // FIXME: Merge with rewriter code?
3485
3486 // struct _objc_super {
3487 // id self;
3488 // Class cls;
3489 // }
3490 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3491 SourceLocation(),
3492 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003493 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3494 Ctx.getObjCIdType(), 0, false));
3495 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3496 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003497 RD->completeDefinition(Ctx);
3498
3499 SuperCTy = Ctx.getTagDeclType(RD);
3500 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3501
3502 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003503 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3504
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003505 // struct _prop_t {
3506 // char *name;
3507 // char *attributes;
3508 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003509 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003510 CGM.getModule().addTypeName("struct._prop_t",
3511 PropertyTy);
3512
3513 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003514 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003515 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003516 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003517 // }
3518 PropertyListTy = llvm::StructType::get(IntTy,
3519 IntTy,
3520 llvm::ArrayType::get(PropertyTy, 0),
3521 NULL);
3522 CGM.getModule().addTypeName("struct._prop_list_t",
3523 PropertyListTy);
3524 // struct _prop_list_t *
3525 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3526
3527 // struct _objc_method {
3528 // SEL _cmd;
3529 // char *method_type;
3530 // char *_imp;
3531 // }
3532 MethodTy = llvm::StructType::get(SelectorPtrTy,
3533 Int8PtrTy,
3534 Int8PtrTy,
3535 NULL);
3536 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003537
3538 // struct _objc_cache *
3539 CacheTy = llvm::OpaqueType::get();
3540 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3541 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003542}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003543
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003544ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3545 : ObjCCommonTypesHelper(cgm)
3546{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003547 // struct _objc_method_description {
3548 // SEL name;
3549 // char *types;
3550 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003551 MethodDescriptionTy =
3552 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003553 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003554 NULL);
3555 CGM.getModule().addTypeName("struct._objc_method_description",
3556 MethodDescriptionTy);
3557
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003558 // struct _objc_method_description_list {
3559 // int count;
3560 // struct _objc_method_description[1];
3561 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003562 MethodDescriptionListTy =
3563 llvm::StructType::get(IntTy,
3564 llvm::ArrayType::get(MethodDescriptionTy, 0),
3565 NULL);
3566 CGM.getModule().addTypeName("struct._objc_method_description_list",
3567 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003568
3569 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003570 MethodDescriptionListPtrTy =
3571 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3572
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003573 // Protocol description structures
3574
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003575 // struct _objc_protocol_extension {
3576 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3577 // struct _objc_method_description_list *optional_instance_methods;
3578 // struct _objc_method_description_list *optional_class_methods;
3579 // struct _objc_property_list *instance_properties;
3580 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003581 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003582 llvm::StructType::get(IntTy,
3583 MethodDescriptionListPtrTy,
3584 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003585 PropertyListPtrTy,
3586 NULL);
3587 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3588 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003589
3590 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003591 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3592
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003593 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003594
3595 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3596 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3597
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003598 const llvm::Type *T =
3599 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3600 LongTy,
3601 llvm::ArrayType::get(ProtocolTyHolder, 0),
3602 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003603 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3604
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003605 // struct _objc_protocol {
3606 // struct _objc_protocol_extension *isa;
3607 // char *protocol_name;
3608 // struct _objc_protocol **_objc_protocol_list;
3609 // struct _objc_method_description_list *instance_methods;
3610 // struct _objc_method_description_list *class_methods;
3611 // }
3612 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003613 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003614 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3615 MethodDescriptionListPtrTy,
3616 MethodDescriptionListPtrTy,
3617 NULL);
3618 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3619
3620 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3621 CGM.getModule().addTypeName("struct._objc_protocol_list",
3622 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003623 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003624 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3625
3626 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003627 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003628 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003629
3630 // Class description structures
3631
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003632 // struct _objc_ivar {
3633 // char *ivar_name;
3634 // char *ivar_type;
3635 // int ivar_offset;
3636 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003637 IvarTy = llvm::StructType::get(Int8PtrTy,
3638 Int8PtrTy,
3639 IntTy,
3640 NULL);
3641 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3642
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003643 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003644 IvarListTy = llvm::OpaqueType::get();
3645 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3646 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3647
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003648 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003649 MethodListTy = llvm::OpaqueType::get();
3650 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3651 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3652
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003653 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003654 ClassExtensionTy =
3655 llvm::StructType::get(IntTy,
3656 Int8PtrTy,
3657 PropertyListPtrTy,
3658 NULL);
3659 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3660 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3661
3662 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3663
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003664 // struct _objc_class {
3665 // Class isa;
3666 // Class super_class;
3667 // char *name;
3668 // long version;
3669 // long info;
3670 // long instance_size;
3671 // struct _objc_ivar_list *ivars;
3672 // struct _objc_method_list *methods;
3673 // struct _objc_cache *cache;
3674 // struct _objc_protocol_list *protocols;
3675 // char *ivar_layout;
3676 // struct _objc_class_ext *ext;
3677 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003678 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3679 llvm::PointerType::getUnqual(ClassTyHolder),
3680 Int8PtrTy,
3681 LongTy,
3682 LongTy,
3683 LongTy,
3684 IvarListPtrTy,
3685 MethodListPtrTy,
3686 CachePtrTy,
3687 ProtocolListPtrTy,
3688 Int8PtrTy,
3689 ClassExtensionPtrTy,
3690 NULL);
3691 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3692
3693 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3694 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3695 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3696
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003697 // struct _objc_category {
3698 // char *category_name;
3699 // char *class_name;
3700 // struct _objc_method_list *instance_method;
3701 // struct _objc_method_list *class_method;
3702 // uint32_t size; // sizeof(struct _objc_category)
3703 // struct _objc_property_list *instance_properties;// category's @property
3704 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003705 CategoryTy = llvm::StructType::get(Int8PtrTy,
3706 Int8PtrTy,
3707 MethodListPtrTy,
3708 MethodListPtrTy,
3709 ProtocolListPtrTy,
3710 IntTy,
3711 PropertyListPtrTy,
3712 NULL);
3713 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3714
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003715 // Global metadata structures
3716
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003717 // struct _objc_symtab {
3718 // long sel_ref_cnt;
3719 // SEL *refs;
3720 // short cls_def_cnt;
3721 // short cat_def_cnt;
3722 // char *defs[cls_def_cnt + cat_def_cnt];
3723 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003724 SymtabTy = llvm::StructType::get(LongTy,
3725 SelectorPtrTy,
3726 ShortTy,
3727 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003728 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003729 NULL);
3730 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3731 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3732
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003733 // struct _objc_module {
3734 // long version;
3735 // long size; // sizeof(struct _objc_module)
3736 // char *name;
3737 // struct _objc_symtab* symtab;
3738 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003739 ModuleTy =
3740 llvm::StructType::get(LongTy,
3741 LongTy,
3742 Int8PtrTy,
3743 SymtabPtrTy,
3744 NULL);
3745 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003746
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003747
Anders Carlsson124526b2008-09-09 10:10:21 +00003748 // FIXME: This is the size of the setjmp buffer and should be
3749 // target specific. 18 is what's used on 32-bit X86.
3750 uint64_t SetJmpBufferSize = 18;
3751
3752 // Exceptions
3753 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003754 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003755
3756 ExceptionDataTy =
3757 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3758 SetJmpBufferSize),
3759 StackPtrTy, NULL);
3760 CGM.getModule().addTypeName("struct._objc_exception_data",
3761 ExceptionDataTy);
3762
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003763}
3764
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003765ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003766: ObjCCommonTypesHelper(cgm)
3767{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003768 // struct _method_list_t {
3769 // uint32_t entsize; // sizeof(struct _objc_method)
3770 // uint32_t method_count;
3771 // struct _objc_method method_list[method_count];
3772 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003773 MethodListnfABITy = llvm::StructType::get(IntTy,
3774 IntTy,
3775 llvm::ArrayType::get(MethodTy, 0),
3776 NULL);
3777 CGM.getModule().addTypeName("struct.__method_list_t",
3778 MethodListnfABITy);
3779 // struct method_list_t *
3780 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003781
3782 // struct _protocol_t {
3783 // id isa; // NULL
3784 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003785 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003786 // const struct method_list_t * const instance_methods;
3787 // const struct method_list_t * const class_methods;
3788 // const struct method_list_t *optionalInstanceMethods;
3789 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003790 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003791 // const uint32_t size; // sizeof(struct _protocol_t)
3792 // const uint32_t flags; // = 0
3793 // }
3794
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003795 // Holder for struct _protocol_list_t *
3796 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3797
3798 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3799 Int8PtrTy,
3800 llvm::PointerType::getUnqual(
3801 ProtocolListTyHolder),
3802 MethodListnfABIPtrTy,
3803 MethodListnfABIPtrTy,
3804 MethodListnfABIPtrTy,
3805 MethodListnfABIPtrTy,
3806 PropertyListPtrTy,
3807 IntTy,
3808 IntTy,
3809 NULL);
3810 CGM.getModule().addTypeName("struct._protocol_t",
3811 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003812
3813 // struct _protocol_t*
3814 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003815
Fariborz Jahanianda320092009-01-29 19:24:30 +00003816 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003817 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003818 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003819 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003820 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3821 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003822 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003823 NULL);
3824 CGM.getModule().addTypeName("struct._objc_protocol_list",
3825 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003826 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3827 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003828
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003829 // struct _objc_protocol_list*
3830 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003831
3832 // struct _ivar_t {
3833 // unsigned long int *offset; // pointer to ivar offset location
3834 // char *name;
3835 // char *type;
3836 // uint32_t alignment;
3837 // uint32_t size;
3838 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003839 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3840 Int8PtrTy,
3841 Int8PtrTy,
3842 IntTy,
3843 IntTy,
3844 NULL);
3845 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3846
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003847 // struct _ivar_list_t {
3848 // uint32 entsize; // sizeof(struct _ivar_t)
3849 // uint32 count;
3850 // struct _iver_t list[count];
3851 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003852 IvarListnfABITy = llvm::StructType::get(IntTy,
3853 IntTy,
3854 llvm::ArrayType::get(
3855 IvarnfABITy, 0),
3856 NULL);
3857 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3858
3859 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003860
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003861 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003862 // uint32_t const flags;
3863 // uint32_t const instanceStart;
3864 // uint32_t const instanceSize;
3865 // uint32_t const reserved; // only when building for 64bit targets
3866 // const uint8_t * const ivarLayout;
3867 // const char *const name;
3868 // const struct _method_list_t * const baseMethods;
3869 // const struct _objc_protocol_list *const baseProtocols;
3870 // const struct _ivar_list_t *const ivars;
3871 // const uint8_t * const weakIvarLayout;
3872 // const struct _prop_list_t * const properties;
3873 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003874
3875 // FIXME. Add 'reserved' field in 64bit abi mode!
3876 ClassRonfABITy = llvm::StructType::get(IntTy,
3877 IntTy,
3878 IntTy,
3879 Int8PtrTy,
3880 Int8PtrTy,
3881 MethodListnfABIPtrTy,
3882 ProtocolListnfABIPtrTy,
3883 IvarListnfABIPtrTy,
3884 Int8PtrTy,
3885 PropertyListPtrTy,
3886 NULL);
3887 CGM.getModule().addTypeName("struct._class_ro_t",
3888 ClassRonfABITy);
3889
3890 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3891 std::vector<const llvm::Type*> Params;
3892 Params.push_back(ObjectPtrTy);
3893 Params.push_back(SelectorPtrTy);
3894 ImpnfABITy = llvm::PointerType::getUnqual(
3895 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3896
3897 // struct _class_t {
3898 // struct _class_t *isa;
3899 // struct _class_t * const superclass;
3900 // void *cache;
3901 // IMP *vtable;
3902 // struct class_ro_t *ro;
3903 // }
3904
3905 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3906 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3907 llvm::PointerType::getUnqual(ClassTyHolder),
3908 CachePtrTy,
3909 llvm::PointerType::getUnqual(ImpnfABITy),
3910 llvm::PointerType::getUnqual(
3911 ClassRonfABITy),
3912 NULL);
3913 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3914
3915 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3916 ClassnfABITy);
3917
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003918 // LLVM for struct _class_t *
3919 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3920
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003921 // struct _category_t {
3922 // const char * const name;
3923 // struct _class_t *const cls;
3924 // const struct _method_list_t * const instance_methods;
3925 // const struct _method_list_t * const class_methods;
3926 // const struct _protocol_list_t * const protocols;
3927 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003928 // }
3929 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003930 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003931 MethodListnfABIPtrTy,
3932 MethodListnfABIPtrTy,
3933 ProtocolListnfABIPtrTy,
3934 PropertyListPtrTy,
3935 NULL);
3936 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003937
3938 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003939 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3940 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003941
3942 // MessageRefTy - LLVM for:
3943 // struct _message_ref_t {
3944 // IMP messenger;
3945 // SEL name;
3946 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003947
3948 // First the clang type for struct _message_ref_t
3949 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3950 SourceLocation(),
3951 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003952 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3953 Ctx.VoidPtrTy, 0, false));
3954 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3955 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003956 RD->completeDefinition(Ctx);
3957
3958 MessageRefCTy = Ctx.getTagDeclType(RD);
3959 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3960 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003961
3962 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3963 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3964
3965 // SuperMessageRefTy - LLVM for:
3966 // struct _super_message_ref_t {
3967 // SUPER_IMP messenger;
3968 // SEL name;
3969 // };
3970 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3971 SelectorPtrTy,
3972 NULL);
3973 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3974
3975 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3976 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3977
Daniel Dunbare588b992009-03-01 04:46:24 +00003978
3979 // struct objc_typeinfo {
3980 // const void** vtable; // objc_ehtype_vtable + 2
3981 // const char* name; // c++ typeinfo string
3982 // Class cls;
3983 // };
3984 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3985 Int8PtrTy,
3986 ClassnfABIPtrTy,
3987 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003988 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003989 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003990}
3991
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003992llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3993 FinishNonFragileABIModule();
3994
3995 return NULL;
3996}
3997
3998void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3999 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004000
4001 // Build list of all implemented classe addresses in array
4002 // L_OBJC_LABEL_CLASS_$.
4003 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4004 // list of 'nonlazy' implementations (defined as those with a +load{}
4005 // method!!).
4006 unsigned NumClasses = DefinedClasses.size();
4007 if (NumClasses) {
4008 std::vector<llvm::Constant*> Symbols(NumClasses);
4009 for (unsigned i=0; i<NumClasses; i++)
4010 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4011 ObjCTypes.Int8PtrTy);
4012 llvm::Constant* Init =
4013 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4014 NumClasses),
4015 Symbols);
4016
4017 llvm::GlobalVariable *GV =
4018 new llvm::GlobalVariable(Init->getType(), false,
4019 llvm::GlobalValue::InternalLinkage,
4020 Init,
4021 "\01L_OBJC_LABEL_CLASS_$",
4022 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004023 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004024 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4025 UsedGlobals.push_back(GV);
4026 }
4027
4028 // Build list of all implemented category addresses in array
4029 // L_OBJC_LABEL_CATEGORY_$.
4030 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4031 // list of 'nonlazy' category implementations (defined as those with a +load{}
4032 // method!!).
4033 unsigned NumCategory = DefinedCategories.size();
4034 if (NumCategory) {
4035 std::vector<llvm::Constant*> Symbols(NumCategory);
4036 for (unsigned i=0; i<NumCategory; i++)
4037 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4038 ObjCTypes.Int8PtrTy);
4039 llvm::Constant* Init =
4040 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4041 NumCategory),
4042 Symbols);
4043
4044 llvm::GlobalVariable *GV =
4045 new llvm::GlobalVariable(Init->getType(), false,
4046 llvm::GlobalValue::InternalLinkage,
4047 Init,
4048 "\01L_OBJC_LABEL_CATEGORY_$",
4049 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004050 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004051 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4052 UsedGlobals.push_back(GV);
4053 }
4054
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004055 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4056 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4057 std::vector<llvm::Constant*> Values(2);
4058 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004059 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004060 // FIXME: Fix and continue?
4061 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4062 flags |= eImageInfo_GarbageCollected;
4063 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4064 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004065 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004066 llvm::Constant* Init = llvm::ConstantArray::get(
4067 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4068 Values);
4069 llvm::GlobalVariable *IMGV =
4070 new llvm::GlobalVariable(Init->getType(), false,
4071 llvm::GlobalValue::InternalLinkage,
4072 Init,
4073 "\01L_OBJC_IMAGE_INFO",
4074 &CGM.getModule());
4075 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004076 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004077 UsedGlobals.push_back(IMGV);
4078
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004079 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004080
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004081 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4082 e = UsedGlobals.end(); i != e; ++i) {
4083 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4084 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004085
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004086 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4087 llvm::GlobalValue *GV =
4088 new llvm::GlobalVariable(AT, false,
4089 llvm::GlobalValue::AppendingLinkage,
4090 llvm::ConstantArray::get(AT, Used),
4091 "llvm.used",
4092 &CGM.getModule());
4093
4094 GV->setSection("llvm.metadata");
4095
4096}
4097
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004098// Metadata flags
4099enum MetaDataDlags {
4100 CLS = 0x0,
4101 CLS_META = 0x1,
4102 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004103 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004104 CLS_EXCEPTION = 0x20
4105};
4106/// BuildClassRoTInitializer - generate meta-data for:
4107/// struct _class_ro_t {
4108/// uint32_t const flags;
4109/// uint32_t const instanceStart;
4110/// uint32_t const instanceSize;
4111/// uint32_t const reserved; // only when building for 64bit targets
4112/// const uint8_t * const ivarLayout;
4113/// const char *const name;
4114/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004115/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004116/// const struct _ivar_list_t *const ivars;
4117/// const uint8_t * const weakIvarLayout;
4118/// const struct _prop_list_t * const properties;
4119/// }
4120///
4121llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4122 unsigned flags,
4123 unsigned InstanceStart,
4124 unsigned InstanceSize,
4125 const ObjCImplementationDecl *ID) {
4126 std::string ClassName = ID->getNameAsString();
4127 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4128 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4129 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4130 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4131 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004132 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4133 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004134 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004135 // const struct _method_list_t * const baseMethods;
4136 std::vector<llvm::Constant*> Methods;
4137 std::string MethodListName("\01l_OBJC_$_");
4138 if (flags & CLS_META) {
4139 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004140 for (ObjCImplementationDecl::classmeth_iterator
4141 i = ID->classmeth_begin(CGM.getContext()),
4142 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004143 // Class methods should always be defined.
4144 Methods.push_back(GetMethodConstant(*i));
4145 }
4146 } else {
4147 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004148 for (ObjCImplementationDecl::instmeth_iterator
4149 i = ID->instmeth_begin(CGM.getContext()),
4150 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004151 // Instance methods should always be defined.
4152 Methods.push_back(GetMethodConstant(*i));
4153 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004154 for (ObjCImplementationDecl::propimpl_iterator
4155 i = ID->propimpl_begin(CGM.getContext()),
4156 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004157 ObjCPropertyImplDecl *PID = *i;
4158
4159 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4160 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4161
4162 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4163 if (llvm::Constant *C = GetMethodConstant(MD))
4164 Methods.push_back(C);
4165 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4166 if (llvm::Constant *C = GetMethodConstant(MD))
4167 Methods.push_back(C);
4168 }
4169 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004170 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004171 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004172 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004173
4174 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4175 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4176 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4177 + OID->getNameAsString(),
4178 OID->protocol_begin(),
4179 OID->protocol_end());
4180
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004181 if (flags & CLS_META)
4182 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4183 else
4184 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004185 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4186 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004187 if (flags & CLS_META)
4188 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4189 else
4190 Values[ 9] =
4191 EmitPropertyList(
4192 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4193 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004194 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4195 Values);
4196 llvm::GlobalVariable *CLASS_RO_GV =
4197 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4198 llvm::GlobalValue::InternalLinkage,
4199 Init,
4200 (flags & CLS_META) ?
4201 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4202 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4203 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004204 CLASS_RO_GV->setAlignment(
4205 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004206 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004207 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004208
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004209}
4210
4211/// BuildClassMetaData - This routine defines that to-level meta-data
4212/// for the given ClassName for:
4213/// struct _class_t {
4214/// struct _class_t *isa;
4215/// struct _class_t * const superclass;
4216/// void *cache;
4217/// IMP *vtable;
4218/// struct class_ro_t *ro;
4219/// }
4220///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004221llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4222 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004223 llvm::Constant *IsAGV,
4224 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004225 llvm::Constant *ClassRoGV,
4226 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004227 std::vector<llvm::Constant*> Values(5);
4228 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004229 Values[1] = SuperClassGV
4230 ? SuperClassGV
4231 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004232 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4233 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4234 Values[4] = ClassRoGV; // &CLASS_RO_GV
4235 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4236 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004237 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4238 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004239 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004240 GV->setAlignment(
4241 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004242 if (HiddenVisibility)
4243 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004244 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004245}
4246
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004247void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004248 uint32_t &InstanceStart,
4249 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004250 // Find first and last (non-padding) ivars in this interface.
4251
4252 // FIXME: Use iterator.
4253 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004254 GetNamedIvarList(OID->getClassInterface(), OIvars);
Daniel Dunbar97776872009-04-22 07:32:20 +00004255
4256 if (OIvars.empty()) {
4257 InstanceStart = InstanceSize = 0;
4258 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004259 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004260
4261 const ObjCIvarDecl *First = OIvars.front();
4262 const ObjCIvarDecl *Last = OIvars.back();
4263
4264 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4265 const llvm::Type *FieldTy =
4266 CGM.getTypes().ConvertTypeForMem(Last->getType());
4267 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004268// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4269// with gcc-4.2). We postpone this for now.
4270#if 0
4271 if (Last->isBitField()) {
4272 Expr *BitWidth = Last->getBitWidth();
4273 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00004274 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004275 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4276 }
4277#endif
Daniel Dunbar97776872009-04-22 07:32:20 +00004278 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004279}
4280
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004281void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4282 std::string ClassName = ID->getNameAsString();
4283 if (!ObjCEmptyCacheVar) {
4284 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004285 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004286 false,
4287 llvm::GlobalValue::ExternalLinkage,
4288 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004289 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004290 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004291
4292 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004293 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004294 false,
4295 llvm::GlobalValue::ExternalLinkage,
4296 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004297 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004298 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004299 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004300 assert(ID->getClassInterface() &&
4301 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004302 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004303 uint32_t InstanceStart =
4304 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4305 uint32_t InstanceSize = InstanceStart;
4306 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004307 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4308 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004309
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004310 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004311
Daniel Dunbar04d40782009-04-14 06:00:08 +00004312 bool classIsHidden =
4313 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004314 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004315 flags |= OBJC2_CLS_HIDDEN;
4316 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004317 // class is root
4318 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004319 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004320 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004321 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004322 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004323 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4324 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4325 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004326 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004327 // work on super class metadata symbol.
4328 std::string SuperClassName =
4329 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004330 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004331 }
4332 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4333 InstanceStart,
4334 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004335 std::string TClassName = ObjCMetaClassName + ClassName;
4336 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004337 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4338 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004339
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004340 // Metadata for the class
4341 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004342 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004343 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004344
4345 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4346 flags |= CLS_EXCEPTION;
4347
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004348 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004349 flags |= CLS_ROOT;
4350 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004351 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004352 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004353 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004354 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004355 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004356 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004357 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004358 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004359 InstanceStart,
4360 InstanceSize,
4361 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004362
4363 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004364 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004365 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4366 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004367 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004368
4369 // Force the definition of the EHType if necessary.
4370 if (flags & CLS_EXCEPTION)
4371 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004372}
4373
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004374/// GenerateProtocolRef - This routine is called to generate code for
4375/// a protocol reference expression; as in:
4376/// @code
4377/// @protocol(Proto1);
4378/// @endcode
4379/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4380/// which will hold address of the protocol meta-data.
4381///
4382llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4383 const ObjCProtocolDecl *PD) {
4384
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004385 // This routine is called for @protocol only. So, we must build definition
4386 // of protocol's meta-data (not a reference to it!)
4387 //
4388 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004389 ObjCTypes.ExternalProtocolPtrTy);
4390
4391 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4392 ProtocolName += PD->getNameAsCString();
4393
4394 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4395 if (PTGV)
4396 return Builder.CreateLoad(PTGV, false, "tmp");
4397 PTGV = new llvm::GlobalVariable(
4398 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004399 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004400 Init,
4401 ProtocolName,
4402 &CGM.getModule());
4403 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4404 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4405 UsedGlobals.push_back(PTGV);
4406 return Builder.CreateLoad(PTGV, false, "tmp");
4407}
4408
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004409/// GenerateCategory - Build metadata for a category implementation.
4410/// struct _category_t {
4411/// const char * const name;
4412/// struct _class_t *const cls;
4413/// const struct _method_list_t * const instance_methods;
4414/// const struct _method_list_t * const class_methods;
4415/// const struct _protocol_list_t * const protocols;
4416/// const struct _prop_list_t * const properties;
4417/// }
4418///
4419void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4420{
4421 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004422 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4423 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004424 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004425 std::string ExtClassName(getClassSymbolPrefix() +
4426 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004427
4428 std::vector<llvm::Constant*> Values(6);
4429 Values[0] = GetClassName(OCD->getIdentifier());
4430 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004431 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004432 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004433 std::vector<llvm::Constant*> Methods;
4434 std::string MethodListName(Prefix);
4435 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4436 "_$_" + OCD->getNameAsString();
4437
Douglas Gregor653f1b12009-04-23 01:02:12 +00004438 for (ObjCCategoryImplDecl::instmeth_iterator
4439 i = OCD->instmeth_begin(CGM.getContext()),
4440 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004441 // Instance methods should always be defined.
4442 Methods.push_back(GetMethodConstant(*i));
4443 }
4444
4445 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004446 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004447 Methods);
4448
4449 MethodListName = Prefix;
4450 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4451 OCD->getNameAsString();
4452 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004453 for (ObjCCategoryImplDecl::classmeth_iterator
4454 i = OCD->classmeth_begin(CGM.getContext()),
4455 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004456 // Class methods should always be defined.
4457 Methods.push_back(GetMethodConstant(*i));
4458 }
4459
4460 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004461 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004462 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004463 const ObjCCategoryDecl *Category =
4464 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004465 if (Category) {
4466 std::string ExtName(Interface->getNameAsString() + "_$_" +
4467 OCD->getNameAsString());
4468 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4469 + Interface->getNameAsString() + "_$_"
4470 + Category->getNameAsString(),
4471 Category->protocol_begin(),
4472 Category->protocol_end());
4473 Values[5] =
4474 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4475 OCD, Category, ObjCTypes);
4476 }
4477 else {
4478 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4479 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4480 }
4481
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004482 llvm::Constant *Init =
4483 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4484 Values);
4485 llvm::GlobalVariable *GCATV
4486 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4487 false,
4488 llvm::GlobalValue::InternalLinkage,
4489 Init,
4490 ExtCatName,
4491 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004492 GCATV->setAlignment(
4493 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004494 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004495 UsedGlobals.push_back(GCATV);
4496 DefinedCategories.push_back(GCATV);
4497}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004498
4499/// GetMethodConstant - Return a struct objc_method constant for the
4500/// given method if it has been defined. The result is null if the
4501/// method has not been defined. The return value has type MethodPtrTy.
4502llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4503 const ObjCMethodDecl *MD) {
4504 // FIXME: Use DenseMap::lookup
4505 llvm::Function *Fn = MethodDefinitions[MD];
4506 if (!Fn)
4507 return 0;
4508
4509 std::vector<llvm::Constant*> Method(3);
4510 Method[0] =
4511 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4512 ObjCTypes.SelectorPtrTy);
4513 Method[1] = GetMethodVarType(MD);
4514 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4515 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4516}
4517
4518/// EmitMethodList - Build meta-data for method declarations
4519/// struct _method_list_t {
4520/// uint32_t entsize; // sizeof(struct _objc_method)
4521/// uint32_t method_count;
4522/// struct _objc_method method_list[method_count];
4523/// }
4524///
4525llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4526 const std::string &Name,
4527 const char *Section,
4528 const ConstantVector &Methods) {
4529 // Return null for empty list.
4530 if (Methods.empty())
4531 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4532
4533 std::vector<llvm::Constant*> Values(3);
4534 // sizeof(struct _objc_method)
4535 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4536 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4537 // method_count
4538 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4539 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4540 Methods.size());
4541 Values[2] = llvm::ConstantArray::get(AT, Methods);
4542 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4543
4544 llvm::GlobalVariable *GV =
4545 new llvm::GlobalVariable(Init->getType(), false,
4546 llvm::GlobalValue::InternalLinkage,
4547 Init,
4548 Name,
4549 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004550 GV->setAlignment(
4551 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004552 GV->setSection(Section);
4553 UsedGlobals.push_back(GV);
4554 return llvm::ConstantExpr::getBitCast(GV,
4555 ObjCTypes.MethodListnfABIPtrTy);
4556}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004557
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004558/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4559/// the given ivar.
4560///
4561llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004562 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004563 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004564 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004565 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4566 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004567 llvm::GlobalVariable *IvarOffsetGV =
4568 CGM.getModule().getGlobalVariable(Name);
4569 if (!IvarOffsetGV)
4570 IvarOffsetGV =
4571 new llvm::GlobalVariable(ObjCTypes.LongTy,
4572 false,
4573 llvm::GlobalValue::ExternalLinkage,
4574 0,
4575 Name,
4576 &CGM.getModule());
4577 return IvarOffsetGV;
4578}
4579
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004580llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004581 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004582 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004583 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004584 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4585 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4586 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004587 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004588 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004589
4590 // FIXME: This matches gcc, but shouldn't the visibility be set on
4591 // the use as well (i.e., in ObjCIvarOffsetVariable).
4592 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4593 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4594 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004595 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004596 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004597 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004598 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004599 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004600}
4601
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004602/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004603/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004604/// IvarListnfABIPtrTy.
4605/// struct _ivar_t {
4606/// unsigned long int *offset; // pointer to ivar offset location
4607/// char *name;
4608/// char *type;
4609/// uint32_t alignment;
4610/// uint32_t size;
4611/// }
4612/// struct _ivar_list_t {
4613/// uint32 entsize; // sizeof(struct _ivar_t)
4614/// uint32 count;
4615/// struct _iver_t list[count];
4616/// }
4617///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004618
4619void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4620 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4621 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4622 E = OID->ivar_end(); I != E; ++I) {
4623 // Ignore unnamed bit-fields.
4624 if (!(*I)->getDeclName())
4625 continue;
4626
4627 Res.push_back(*I);
4628 }
4629
4630 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4631 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4632 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4633 Res.push_back(IV);
4634}
4635
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004636llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4637 const ObjCImplementationDecl *ID) {
4638
4639 std::vector<llvm::Constant*> Ivars, Ivar(5);
4640
4641 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4642 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4643
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004644 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004645
Daniel Dunbar91636d62009-04-20 00:33:43 +00004646 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004647 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004648 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004649
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004650 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4651 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004652 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004653 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004654 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4655 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004656 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004657 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004658 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4659 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004660 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004661 Align = llvm::Log2_32(Align);
4662 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004663 // NOTE. Size of a bitfield does not match gcc's, because of the
4664 // way bitfields are treated special in each. But I am told that
4665 // 'size' for bitfield ivars is ignored by the runtime so it does
4666 // not matter. If it matters, there is enough info to get the
4667 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004668 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4669 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4670 }
4671 // Return null for empty list.
4672 if (Ivars.empty())
4673 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4674 std::vector<llvm::Constant*> Values(3);
4675 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4676 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4677 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4678 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4679 Ivars.size());
4680 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4681 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4682 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4683 llvm::GlobalVariable *GV =
4684 new llvm::GlobalVariable(Init->getType(), false,
4685 llvm::GlobalValue::InternalLinkage,
4686 Init,
4687 Prefix + OID->getNameAsString(),
4688 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004689 GV->setAlignment(
4690 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004691 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004692
4693 UsedGlobals.push_back(GV);
4694 return llvm::ConstantExpr::getBitCast(GV,
4695 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004696}
4697
4698llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4699 const ObjCProtocolDecl *PD) {
4700 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4701
4702 if (!Entry) {
4703 // We use the initializer as a marker of whether this is a forward
4704 // reference or not. At module finalization we add the empty
4705 // contents for protocols which were referenced but never defined.
4706 Entry =
4707 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4708 llvm::GlobalValue::ExternalLinkage,
4709 0,
4710 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4711 &CGM.getModule());
4712 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4713 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004714 }
4715
4716 return Entry;
4717}
4718
4719/// GetOrEmitProtocol - Generate the protocol meta-data:
4720/// @code
4721/// struct _protocol_t {
4722/// id isa; // NULL
4723/// const char * const protocol_name;
4724/// const struct _protocol_list_t * protocol_list; // super protocols
4725/// const struct method_list_t * const instance_methods;
4726/// const struct method_list_t * const class_methods;
4727/// const struct method_list_t *optionalInstanceMethods;
4728/// const struct method_list_t *optionalClassMethods;
4729/// const struct _prop_list_t * properties;
4730/// const uint32_t size; // sizeof(struct _protocol_t)
4731/// const uint32_t flags; // = 0
4732/// }
4733/// @endcode
4734///
4735
4736llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4737 const ObjCProtocolDecl *PD) {
4738 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4739
4740 // Early exit if a defining object has already been generated.
4741 if (Entry && Entry->hasInitializer())
4742 return Entry;
4743
4744 const char *ProtocolName = PD->getNameAsCString();
4745
4746 // Construct method lists.
4747 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4748 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004749 for (ObjCProtocolDecl::instmeth_iterator
4750 i = PD->instmeth_begin(CGM.getContext()),
4751 e = PD->instmeth_end(CGM.getContext());
4752 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004754 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4756 OptInstanceMethods.push_back(C);
4757 } else {
4758 InstanceMethods.push_back(C);
4759 }
4760 }
4761
Douglas Gregor6ab35242009-04-09 21:40:53 +00004762 for (ObjCProtocolDecl::classmeth_iterator
4763 i = PD->classmeth_begin(CGM.getContext()),
4764 e = PD->classmeth_end(CGM.getContext());
4765 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004767 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004768 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4769 OptClassMethods.push_back(C);
4770 } else {
4771 ClassMethods.push_back(C);
4772 }
4773 }
4774
4775 std::vector<llvm::Constant*> Values(10);
4776 // isa is NULL
4777 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4778 Values[1] = GetClassName(PD->getIdentifier());
4779 Values[2] = EmitProtocolList(
4780 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4781 PD->protocol_begin(),
4782 PD->protocol_end());
4783
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004784 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 + PD->getNameAsString(),
4786 "__DATA, __objc_const",
4787 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004788 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 + PD->getNameAsString(),
4790 "__DATA, __objc_const",
4791 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004792 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 + PD->getNameAsString(),
4794 "__DATA, __objc_const",
4795 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004796 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 + PD->getNameAsString(),
4798 "__DATA, __objc_const",
4799 OptClassMethods);
4800 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4801 0, PD, ObjCTypes);
4802 uint32_t Size =
4803 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4804 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4805 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4806 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4807 Values);
4808
4809 if (Entry) {
4810 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004811 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 Entry->setInitializer(Init);
4813 } else {
4814 Entry =
4815 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004816 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 Init,
4818 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4819 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004820 Entry->setAlignment(
4821 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004824 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4825
4826 // Use this protocol meta-data to build protocol list table in section
4827 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004828 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004829 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004830 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004831 Entry,
4832 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4833 +ProtocolName,
4834 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004835 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004836 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004837 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004838 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4839 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004840 return Entry;
4841}
4842
4843/// EmitProtocolList - Generate protocol list meta-data:
4844/// @code
4845/// struct _protocol_list_t {
4846/// long protocol_count; // Note, this is 32/64 bit
4847/// struct _protocol_t[protocol_count];
4848/// }
4849/// @endcode
4850///
4851llvm::Constant *
4852CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4853 ObjCProtocolDecl::protocol_iterator begin,
4854 ObjCProtocolDecl::protocol_iterator end) {
4855 std::vector<llvm::Constant*> ProtocolRefs;
4856
Fariborz Jahanianda320092009-01-29 19:24:30 +00004857 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004858 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004859 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4860
Daniel Dunbar948e2582009-02-15 07:36:20 +00004861 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004862 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4863 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004864 return llvm::ConstantExpr::getBitCast(GV,
4865 ObjCTypes.ProtocolListnfABIPtrTy);
4866
4867 for (; begin != end; ++begin)
4868 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4869
Fariborz Jahanianda320092009-01-29 19:24:30 +00004870 // This list is null terminated.
4871 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004872 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004873
4874 std::vector<llvm::Constant*> Values(2);
4875 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4876 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004877 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004878 ProtocolRefs.size()),
4879 ProtocolRefs);
4880
4881 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4882 GV = new llvm::GlobalVariable(Init->getType(), false,
4883 llvm::GlobalValue::InternalLinkage,
4884 Init,
4885 Name,
4886 &CGM.getModule());
4887 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004888 GV->setAlignment(
4889 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004890 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004891 return llvm::ConstantExpr::getBitCast(GV,
4892 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004893}
4894
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004895/// GetMethodDescriptionConstant - This routine build following meta-data:
4896/// struct _objc_method {
4897/// SEL _cmd;
4898/// char *method_type;
4899/// char *_imp;
4900/// }
4901
4902llvm::Constant *
4903CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4904 std::vector<llvm::Constant*> Desc(3);
4905 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4906 ObjCTypes.SelectorPtrTy);
4907 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004908 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004909 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4910 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4911}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004912
4913/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4914/// This code gen. amounts to generating code for:
4915/// @code
4916/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4917/// @encode
4918///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004919LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004920 CodeGen::CodeGenFunction &CGF,
4921 QualType ObjectTy,
4922 llvm::Value *BaseValue,
4923 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004924 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004925 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004926 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4927 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004928}
4929
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004930llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4931 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004932 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004933 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004934 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4935 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004936}
4937
Fariborz Jahanian46551122009-02-04 00:22:57 +00004938CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4939 CodeGen::CodeGenFunction &CGF,
4940 QualType ResultType,
4941 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004942 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004943 QualType Arg0Ty,
4944 bool IsSuper,
4945 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004946 // FIXME. Even though IsSuper is passes. This function doese not
4947 // handle calls to 'super' receivers.
4948 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004949 llvm::Value *Arg0 = Receiver;
4950 if (!IsSuper)
4951 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952
4953 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004954 // FIXME. This is too much work to get the ABI-specific result type
4955 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4957 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004958 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004959 std::string Name("\01l_");
4960 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004961#if 0
4962 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004963 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004964 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004965 // FIXME. Is there a better way of getting these names.
4966 // They are available in RuntimeFunctions vector pair.
4967 Name += "objc_msgSendId_stret_fixup";
4968 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004969 else
4970#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004971 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004972 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004973 Name += "objc_msgSendSuper2_stret_fixup";
4974 }
4975 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004976 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004977 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978 Name += "objc_msgSend_stret_fixup";
4979 }
4980 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00004981 else if (!IsSuper && ResultType->isFloatingType()) {
4982 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
4983 BuiltinType::Kind k = BT->getKind();
4984 if (k == BuiltinType::LongDouble) {
4985 Fn = ObjCTypes.getMessageSendFpretFixupFn();
4986 Name += "objc_msgSend_fpret_fixup";
4987 }
4988 else {
4989 Fn = ObjCTypes.getMessageSendFixupFn();
4990 Name += "objc_msgSend_fixup";
4991 }
4992 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004993 }
4994 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004995#if 0
4996// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004997 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004998 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004999 Name += "objc_msgSendId_fixup";
5000 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005001 else
5002#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005003 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005004 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005005 Name += "objc_msgSendSuper2_fixup";
5006 }
5007 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005008 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005009 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 Name += "objc_msgSend_fixup";
5011 }
5012 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005013 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005014 Name += '_';
5015 std::string SelName(Sel.getAsString());
5016 // Replace all ':' in selector name with '_' ouch!
5017 for(unsigned i = 0; i < SelName.size(); i++)
5018 if (SelName[i] == ':')
5019 SelName[i] = '_';
5020 Name += SelName;
5021 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5022 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005023 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005024 std::vector<llvm::Constant*> Values(2);
5025 Values[0] = Fn;
5026 Values[1] = GetMethodVarName(Sel);
5027 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5028 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005029 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005030 Init,
5031 Name,
5032 &CGM.getModule());
5033 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005034 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005035 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 }
5037 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005038
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005039 CallArgList ActualArgs;
5040 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5041 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5042 ObjCTypes.MessageRefCPtrTy));
5043 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005044 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5045 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5046 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005047 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005048 Callee = CGF.Builder.CreateBitCast(Callee,
5049 llvm::PointerType::getUnqual(FTy));
5050 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005051}
5052
5053/// Generate code for a message send expression in the nonfragile abi.
5054CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5055 CodeGen::CodeGenFunction &CGF,
5056 QualType ResultType,
5057 Selector Sel,
5058 llvm::Value *Receiver,
5059 bool IsClassMessage,
5060 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005061 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005062 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005063 false, CallArgs);
5064}
5065
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005066llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005067CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005068 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5069
Daniel Dunbardfff2302009-03-02 05:18:14 +00005070 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005071 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5072 llvm::GlobalValue::ExternalLinkage,
5073 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005074 }
5075
5076 return GV;
5077}
5078
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005079llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005080 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005081 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5082
5083 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005084 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005085 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005086 Entry =
5087 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5088 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005089 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005090 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005091 &CGM.getModule());
5092 Entry->setAlignment(
5093 CGM.getTargetData().getPrefTypeAlignment(
5094 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005095 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5096 UsedGlobals.push_back(Entry);
5097 }
5098
5099 return Builder.CreateLoad(Entry, false, "tmp");
5100}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005101
Daniel Dunbar11394522009-04-18 08:51:00 +00005102llvm::Value *
5103CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5104 const ObjCInterfaceDecl *ID) {
5105 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5106
5107 if (!Entry) {
5108 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5109 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5110 Entry =
5111 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5112 llvm::GlobalValue::InternalLinkage,
5113 ClassGV,
5114 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5115 &CGM.getModule());
5116 Entry->setAlignment(
5117 CGM.getTargetData().getPrefTypeAlignment(
5118 ObjCTypes.ClassnfABIPtrTy));
5119 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005120 UsedGlobals.push_back(Entry);
5121 }
5122
5123 return Builder.CreateLoad(Entry, false, "tmp");
5124}
5125
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005126/// EmitMetaClassRef - Return a Value * of the address of _class_t
5127/// meta-data
5128///
5129llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5130 const ObjCInterfaceDecl *ID) {
5131 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5132 if (Entry)
5133 return Builder.CreateLoad(Entry, false, "tmp");
5134
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005135 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005136 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005137 Entry =
5138 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5139 llvm::GlobalValue::InternalLinkage,
5140 MetaClassGV,
5141 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5142 &CGM.getModule());
5143 Entry->setAlignment(
5144 CGM.getTargetData().getPrefTypeAlignment(
5145 ObjCTypes.ClassnfABIPtrTy));
5146
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005147 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005148 UsedGlobals.push_back(Entry);
5149
5150 return Builder.CreateLoad(Entry, false, "tmp");
5151}
5152
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005153/// GetClass - Return a reference to the class for the given interface
5154/// decl.
5155llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5156 const ObjCInterfaceDecl *ID) {
5157 return EmitClassRef(Builder, ID);
5158}
5159
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005160/// Generates a message send where the super is the receiver. This is
5161/// a message send to self with special delivery semantics indicating
5162/// which class's method should be called.
5163CodeGen::RValue
5164CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5165 QualType ResultType,
5166 Selector Sel,
5167 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005168 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005169 llvm::Value *Receiver,
5170 bool IsClassMessage,
5171 const CodeGen::CallArgList &CallArgs) {
5172 // ...
5173 // Create and init a super structure; this is a (receiver, class)
5174 // pair we will pass to objc_msgSendSuper.
5175 llvm::Value *ObjCSuper =
5176 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5177
5178 llvm::Value *ReceiverAsObject =
5179 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5180 CGF.Builder.CreateStore(ReceiverAsObject,
5181 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5182
5183 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005184 llvm::Value *Target;
5185 if (IsClassMessage) {
5186 if (isCategoryImpl) {
5187 // Message sent to "super' in a class method defined in
5188 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005189 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005190 Target = CGF.Builder.CreateStructGEP(Target, 0);
5191 Target = CGF.Builder.CreateLoad(Target);
5192 }
5193 else
5194 Target = EmitMetaClassRef(CGF.Builder, Class);
5195 }
5196 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005197 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005198
5199 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5200 // and ObjCTypes types.
5201 const llvm::Type *ClassTy =
5202 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5203 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5204 CGF.Builder.CreateStore(Target,
5205 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5206
5207 return EmitMessageSend(CGF, ResultType, Sel,
5208 ObjCSuper, ObjCTypes.SuperPtrCTy,
5209 true, CallArgs);
5210}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005211
5212llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5213 Selector Sel) {
5214 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5215
5216 if (!Entry) {
5217 llvm::Constant *Casted =
5218 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5219 ObjCTypes.SelectorPtrTy);
5220 Entry =
5221 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5222 llvm::GlobalValue::InternalLinkage,
5223 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5224 &CGM.getModule());
5225 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5226 UsedGlobals.push_back(Entry);
5227 }
5228
5229 return Builder.CreateLoad(Entry, false, "tmp");
5230}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005231/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5232/// objc_assign_ivar (id src, id *dst)
5233///
5234void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5235 llvm::Value *src, llvm::Value *dst)
5236{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005237 const llvm::Type * SrcTy = src->getType();
5238 if (!isa<llvm::PointerType>(SrcTy)) {
5239 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5240 assert(Size <= 8 && "does not support size > 8");
5241 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5242 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005243 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5244 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005245 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5246 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005247 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005248 src, dst, "assignivar");
5249 return;
5250}
5251
5252/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5253/// objc_assign_strongCast (id src, id *dst)
5254///
5255void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5256 CodeGen::CodeGenFunction &CGF,
5257 llvm::Value *src, llvm::Value *dst)
5258{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005259 const llvm::Type * SrcTy = src->getType();
5260 if (!isa<llvm::PointerType>(SrcTy)) {
5261 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5262 assert(Size <= 8 && "does not support size > 8");
5263 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5264 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005265 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5266 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005267 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5268 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005269 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005270 src, dst, "weakassign");
5271 return;
5272}
5273
5274/// EmitObjCWeakRead - Code gen for loading value of a __weak
5275/// object: objc_read_weak (id *src)
5276///
5277llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5278 CodeGen::CodeGenFunction &CGF,
5279 llvm::Value *AddrWeakObj)
5280{
Eli Friedman8339b352009-03-07 03:57:15 +00005281 const llvm::Type* DestTy =
5282 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005283 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005284 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005285 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005286 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005287 return read_weak;
5288}
5289
5290/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5291/// objc_assign_weak (id src, id *dst)
5292///
5293void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5294 llvm::Value *src, llvm::Value *dst)
5295{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005296 const llvm::Type * SrcTy = src->getType();
5297 if (!isa<llvm::PointerType>(SrcTy)) {
5298 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5299 assert(Size <= 8 && "does not support size > 8");
5300 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5301 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005302 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5303 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005304 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5305 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005306 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005307 src, dst, "weakassign");
5308 return;
5309}
5310
5311/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5312/// objc_assign_global (id src, id *dst)
5313///
5314void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5315 llvm::Value *src, llvm::Value *dst)
5316{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005317 const llvm::Type * SrcTy = src->getType();
5318 if (!isa<llvm::PointerType>(SrcTy)) {
5319 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5320 assert(Size <= 8 && "does not support size > 8");
5321 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5322 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005323 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5324 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005325 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5326 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005327 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005328 src, dst, "globalassign");
5329 return;
5330}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005331
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005332void
5333CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5334 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005335 bool isTry = isa<ObjCAtTryStmt>(S);
5336 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5337 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005338 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005339 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005340 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005341 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5342
5343 // For @synchronized, call objc_sync_enter(sync.expr). The
5344 // evaluation of the expression must occur before we enter the
5345 // @synchronized. We can safely avoid a temp here because jumps into
5346 // @synchronized are illegal & this will dominate uses.
5347 llvm::Value *SyncArg = 0;
5348 if (!isTry) {
5349 SyncArg =
5350 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5351 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005352 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005353 }
5354
5355 // Push an EH context entry, used for handling rethrows and jumps
5356 // through finally.
5357 CGF.PushCleanupBlock(FinallyBlock);
5358
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005359 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005360
5361 CGF.EmitBlock(TryBlock);
5362 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5363 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5364 CGF.EmitBranchThroughCleanup(FinallyEnd);
5365
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005366 // Emit the exception handler.
5367
5368 CGF.EmitBlock(TryHandler);
5369
5370 llvm::Value *llvm_eh_exception =
5371 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5372 llvm::Value *llvm_eh_selector_i64 =
5373 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5374 llvm::Value *llvm_eh_typeid_for_i64 =
5375 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5376 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5377 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5378
5379 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5380 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005381 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005382
5383 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005384 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005385 bool HasCatchAll = false;
5386 if (isTry) {
5387 if (const ObjCAtCatchStmt* CatchStmt =
5388 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5389 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005390 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005391 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005392
5393 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005394 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005395 // Use i8* null here to signal this is a catch all, not a cleanup.
5396 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5397 SelectorArgs.push_back(Null);
5398 HasCatchAll = true;
5399 break;
5400 }
5401
Daniel Dunbarede8de92009-03-06 00:01:21 +00005402 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5403 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005404 llvm::Value *IDEHType =
5405 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5406 if (!IDEHType)
5407 IDEHType =
5408 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5409 llvm::GlobalValue::ExternalLinkage,
5410 0, "OBJC_EHTYPE_id", &CGM.getModule());
5411 SelectorArgs.push_back(IDEHType);
5412 HasCatchAll = true;
5413 break;
5414 }
5415
5416 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005417 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005418 assert(PT && "Invalid @catch type.");
5419 const ObjCInterfaceType *IT =
5420 PT->getPointeeType()->getAsObjCInterfaceType();
5421 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005422 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005423 SelectorArgs.push_back(EHType);
5424 }
5425 }
5426 }
5427
5428 // We use a cleanup unless there was already a catch all.
5429 if (!HasCatchAll) {
5430 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005431 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005432 }
5433
5434 llvm::Value *Selector =
5435 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5436 SelectorArgs.begin(), SelectorArgs.end(),
5437 "selector");
5438 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005439 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005440 const Stmt *CatchBody = Handlers[i].second;
5441
5442 llvm::BasicBlock *Next = 0;
5443
5444 // The last handler always matches.
5445 if (i + 1 != e) {
5446 assert(CatchParam && "Only last handler can be a catch all.");
5447
5448 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5449 Next = CGF.createBasicBlock("catch.next");
5450 llvm::Value *Id =
5451 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5452 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5453 ObjCTypes.Int8PtrTy));
5454 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5455 Match, Next);
5456
5457 CGF.EmitBlock(Match);
5458 }
5459
5460 if (CatchBody) {
5461 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5462 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5463
5464 // Cleanups must call objc_end_catch.
5465 //
5466 // FIXME: It seems incorrect for objc_begin_catch to be inside
5467 // this context, but this matches gcc.
5468 CGF.PushCleanupBlock(MatchEnd);
5469 CGF.setInvokeDest(MatchHandler);
5470
5471 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005472 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005473
5474 // Bind the catch parameter if it exists.
5475 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005476 ExcObject =
5477 CGF.Builder.CreateBitCast(ExcObject,
5478 CGF.ConvertType(CatchParam->getType()));
5479 // CatchParam is a ParmVarDecl because of the grammar
5480 // construction used to handle this, but for codegen purposes
5481 // we treat this as a local decl.
5482 CGF.EmitLocalBlockVarDecl(*CatchParam);
5483 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005484 }
5485
5486 CGF.ObjCEHValueStack.push_back(ExcObject);
5487 CGF.EmitStmt(CatchBody);
5488 CGF.ObjCEHValueStack.pop_back();
5489
5490 CGF.EmitBranchThroughCleanup(FinallyEnd);
5491
5492 CGF.EmitBlock(MatchHandler);
5493
5494 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5495 // We are required to emit this call to satisfy LLVM, even
5496 // though we don't use the result.
5497 llvm::SmallVector<llvm::Value*, 8> Args;
5498 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005499 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005500 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5501 0));
5502 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5503 CGF.Builder.CreateStore(Exc, RethrowPtr);
5504 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5505
5506 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5507
5508 CGF.EmitBlock(MatchEnd);
5509
5510 // Unfortunately, we also have to generate another EH frame here
5511 // in case this throws.
5512 llvm::BasicBlock *MatchEndHandler =
5513 CGF.createBasicBlock("match.end.handler");
5514 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005515 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005516 Cont, MatchEndHandler,
5517 Args.begin(), Args.begin());
5518
5519 CGF.EmitBlock(Cont);
5520 if (Info.SwitchBlock)
5521 CGF.EmitBlock(Info.SwitchBlock);
5522 if (Info.EndBlock)
5523 CGF.EmitBlock(Info.EndBlock);
5524
5525 CGF.EmitBlock(MatchEndHandler);
5526 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5527 // We are required to emit this call to satisfy LLVM, even
5528 // though we don't use the result.
5529 Args.clear();
5530 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005531 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005532 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5533 0));
5534 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5535 CGF.Builder.CreateStore(Exc, RethrowPtr);
5536 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5537
5538 if (Next)
5539 CGF.EmitBlock(Next);
5540 } else {
5541 assert(!Next && "catchup should be last handler.");
5542
5543 CGF.Builder.CreateStore(Exc, RethrowPtr);
5544 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5545 }
5546 }
5547
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005548 // Pop the cleanup entry, the @finally is outside this cleanup
5549 // scope.
5550 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5551 CGF.setInvokeDest(PrevLandingPad);
5552
5553 CGF.EmitBlock(FinallyBlock);
5554
5555 if (isTry) {
5556 if (const ObjCAtFinallyStmt* FinallyStmt =
5557 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5558 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5559 } else {
5560 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5561 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005562 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005563 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005564
5565 if (Info.SwitchBlock)
5566 CGF.EmitBlock(Info.SwitchBlock);
5567 if (Info.EndBlock)
5568 CGF.EmitBlock(Info.EndBlock);
5569
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005570 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005571 CGF.EmitBranch(FinallyEnd);
5572
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005573 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005574 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005575 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005576 CGF.Builder.CreateUnreachable();
5577
5578 CGF.EmitBlock(FinallyEnd);
5579}
5580
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005581/// EmitThrowStmt - Generate code for a throw statement.
5582void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5583 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005584 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005585 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005586 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005587 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005588 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5589 "Unexpected rethrow outside @catch block.");
5590 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005591 }
5592
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005593 llvm::Value *ExceptionAsObject =
5594 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5595 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5596 if (InvokeDest) {
5597 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005598 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005599 Cont, InvokeDest,
5600 &ExceptionAsObject, &ExceptionAsObject + 1);
5601 CGF.EmitBlock(Cont);
5602 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005603 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005604 CGF.Builder.CreateUnreachable();
5605
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005606 // Clear the insertion point to indicate we are in unreachable code.
5607 CGF.Builder.ClearInsertionPoint();
5608}
Daniel Dunbare588b992009-03-01 04:46:24 +00005609
5610llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005611CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5612 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005613 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005614
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005615 // If we don't need a definition, return the entry if found or check
5616 // if we use an external reference.
5617 if (!ForDefinition) {
5618 if (Entry)
5619 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005620
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005621 // If this type (or a super class) has the __objc_exception__
5622 // attribute, emit an external reference.
5623 if (hasObjCExceptionAttribute(ID))
5624 return Entry =
5625 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5626 llvm::GlobalValue::ExternalLinkage,
5627 0,
5628 (std::string("OBJC_EHTYPE_$_") +
5629 ID->getIdentifier()->getName()),
5630 &CGM.getModule());
5631 }
5632
5633 // Otherwise we need to either make a new entry or fill in the
5634 // initializer.
5635 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005636 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005637 std::string VTableName = "objc_ehtype_vtable";
5638 llvm::GlobalVariable *VTableGV =
5639 CGM.getModule().getGlobalVariable(VTableName);
5640 if (!VTableGV)
5641 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5642 llvm::GlobalValue::ExternalLinkage,
5643 0, VTableName, &CGM.getModule());
5644
5645 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5646
5647 std::vector<llvm::Constant*> Values(3);
5648 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5649 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005650 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005651 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5652
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005653 if (Entry) {
5654 Entry->setInitializer(Init);
5655 } else {
5656 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5657 llvm::GlobalValue::WeakAnyLinkage,
5658 Init,
5659 (std::string("OBJC_EHTYPE_$_") +
5660 ID->getIdentifier()->getName()),
5661 &CGM.getModule());
5662 }
5663
Daniel Dunbar04d40782009-04-14 06:00:08 +00005664 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005665 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005666 Entry->setAlignment(8);
5667
5668 if (ForDefinition) {
5669 Entry->setSection("__DATA,__objc_const");
5670 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5671 } else {
5672 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5673 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005674
5675 return Entry;
5676}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005677
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005678/* *** */
5679
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005680CodeGen::CGObjCRuntime *
5681CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005682 return new CGObjCMac(CGM);
5683}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005684
5685CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005686CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005687 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005688}