blob: 5c2dbf8110767eb30674e3954ec03c629881d6d2 [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 Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
Daniel Dunbar97776872009-04-22 07:32:20 +000032// Common CGObjCRuntime functions, these don't belong here, but they
33// don't belong in CGObjCRuntime either so we will live with it for
34// now.
35
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000036const llvm::StructType *
37CGObjCRuntime::GetConcreteClassStruct(CodeGen::CodeGenModule &CGM,
38 const ObjCInterfaceDecl *OID) {
39 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar412f59b2009-04-22 10:28:39 +000040 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
41 return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000042}
43
Daniel Dunbara2435782009-04-22 12:00:04 +000044
45/// LookupFieldDeclForIvar - looks up a field decl in the laid out
46/// storage which matches this 'ivar'.
47///
48static const FieldDecl *LookupFieldDeclForIvar(ASTContext &Context,
49 const ObjCInterfaceDecl *OID,
Daniel Dunbara80a0f62009-04-22 17:43:55 +000050 const ObjCIvarDecl *OIVD,
51 const ObjCInterfaceDecl *&Found) {
Daniel Dunbara2435782009-04-22 12:00:04 +000052 assert(!OID->isForwardDecl() && "Invalid interface decl!");
53 const RecordDecl *RecordForDecl = Context.addRecordToClass(OID);
54 assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class");
55 DeclContext::lookup_const_result Lookup =
56 RecordForDecl->lookup(Context, OIVD->getDeclName());
Daniel Dunbara80a0f62009-04-22 17:43:55 +000057
58 if (Lookup.first != Lookup.second) {
59 Found = OID;
60 return cast<FieldDecl>(*Lookup.first);
61 }
62
63 // If lookup failed, try the superclass.
64 //
65 // FIXME: This is slow, we shouldn't need to do this.
66 const ObjCInterfaceDecl *Super = OID->getSuperClass();
67 assert(OID && "field decl not found!");
68 return LookupFieldDeclForIvar(Context, Super, OIVD, Found);
Daniel Dunbara2435782009-04-22 12:00:04 +000069}
70
Daniel Dunbar97776872009-04-22 07:32:20 +000071uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
72 const ObjCInterfaceDecl *OID,
73 const ObjCIvarDecl *Ivar) {
74 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbara80a0f62009-04-22 17:43:55 +000075 const ObjCInterfaceDecl *Container;
76 const FieldDecl *Field =
77 LookupFieldDeclForIvar(CGM.getContext(), OID, Ivar, Container);
78 QualType T = CGM.getContext().getObjCInterfaceType(Container);
79 const llvm::StructType *STy = GetConcreteClassStruct(CGM, Container);
Daniel Dunbar97776872009-04-22 07:32:20 +000080 const llvm::StructLayout *Layout =
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000081 CGM.getTargetData().getStructLayout(STy);
Daniel Dunbar97776872009-04-22 07:32:20 +000082 if (!Field->isBitField())
83 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
84
85 // FIXME. Must be a better way of getting a bitfield base offset.
86 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
87 // FIXME: The "field no" for bitfields is something completely
88 // different; it is the offset in multiples of the base type size!
89 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
90 const llvm::Type *Ty =
91 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
92 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
93 return (Offset + BFI.Begin) / 8;
94}
95
96LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
97 const ObjCInterfaceDecl *OID,
98 llvm::Value *BaseValue,
99 const ObjCIvarDecl *Ivar,
100 unsigned CVRQualifiers,
101 llvm::Value *Offset) {
Daniel Dunbar412f59b2009-04-22 10:28:39 +0000102 // Force generation of the codegen information for this structure.
103 //
104 // FIXME: Remove once we don't use the bit-field lookup map.
105 (void) GetConcreteClassStruct(CGF.CGM, OID);
106
Daniel Dunbar97776872009-04-22 07:32:20 +0000107 // FIXME: For now, we use an implementation based on just computing
108 // the offset and calculating things directly. For optimization
109 // purposes, it would be cleaner to use a GEP on the proper type
110 // since the structure layout is fixed; however for that we need to
111 // be able to walk the class chain for an Ivar.
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000112 const ObjCInterfaceDecl *Container;
Daniel Dunbar97776872009-04-22 07:32:20 +0000113 const FieldDecl *Field =
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000114 LookupFieldDeclForIvar(CGF.CGM.getContext(), OID, Ivar, Container);
Daniel Dunbar97776872009-04-22 07:32:20 +0000115
116 // (char *) BaseValue
117 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
118 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
119 // (char*)BaseValue + Offset_symbol
120 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
121 // (type *)((char*)BaseValue + Offset_symbol)
122 const llvm::Type *IvarTy =
123 CGF.CGM.getTypes().ConvertTypeForMem(Ivar->getType());
124 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
125 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
126
127 if (Ivar->isBitField()) {
128 QualType FieldTy = Field->getType();
129 CodeGenTypes::BitFieldInfo bitFieldInfo =
130 CGF.CGM.getTypes().getBitFieldInfo(Field);
131 return LValue::MakeBitfield(V, bitFieldInfo.Begin % 8, bitFieldInfo.Size,
132 FieldTy->isSignedIntegerType(),
133 FieldTy.getCVRQualifiers()|CVRQualifiers);
134 }
135
136 LValue LV = LValue::MakeAddr(V,
137 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
138 CGF.CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
139 LValue::SetObjCIvar(LV, true);
140 return LV;
141}
142
143///
144
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000145namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000146
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000147 typedef std::vector<llvm::Constant*> ConstantVector;
148
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000149 // FIXME: We should find a nicer way to make the labels for
150 // metadata, string concatenation is lame.
151
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000152class ObjCCommonTypesHelper {
153protected:
154 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000155
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000156public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000157 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000158 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000159
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000160 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
161 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000162
163 /// PtrObjectPtrTy - LLVM type for id *
164 const llvm::Type *PtrObjectPtrTy;
165
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000166 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000167 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolPtrTy - LLVM type for external protocol handles
169 /// (typeof(Protocol))
170 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000171
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000172 // SuperCTy - clang type for struct objc_super.
173 QualType SuperCTy;
174 // SuperPtrCTy - clang type for struct objc_super *.
175 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000176
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000177 /// SuperTy - LLVM type for struct objc_super.
178 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000179 /// SuperPtrTy - LLVM type for struct objc_super *.
180 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000181
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000182 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
183 /// in GCC parlance).
184 const llvm::StructType *PropertyTy;
185
186 /// PropertyListTy - LLVM type for struct objc_property_list
187 /// (_prop_list_t in GCC parlance).
188 const llvm::StructType *PropertyListTy;
189 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
190 const llvm::Type *PropertyListPtrTy;
191
192 // MethodTy - LLVM type for struct objc_method.
193 const llvm::StructType *MethodTy;
194
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000195 /// CacheTy - LLVM type for struct objc_cache.
196 const llvm::Type *CacheTy;
197 /// CachePtrTy - LLVM type for struct objc_cache *.
198 const llvm::Type *CachePtrTy;
199
Chris Lattner72db6c32009-04-22 02:44:54 +0000200 llvm::Constant *getGetPropertyFn() {
201 CodeGen::CodeGenTypes &Types = CGM.getTypes();
202 ASTContext &Ctx = CGM.getContext();
203 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
204 llvm::SmallVector<QualType,16> Params;
205 QualType IdType = Ctx.getObjCIdType();
206 QualType SelType = Ctx.getObjCSelType();
207 Params.push_back(IdType);
208 Params.push_back(SelType);
209 Params.push_back(Ctx.LongTy);
210 Params.push_back(Ctx.BoolTy);
211 const llvm::FunctionType *FTy =
212 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
213 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
214 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000215
Chris Lattner72db6c32009-04-22 02:44:54 +0000216 llvm::Constant *getSetPropertyFn() {
217 CodeGen::CodeGenTypes &Types = CGM.getTypes();
218 ASTContext &Ctx = CGM.getContext();
219 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
220 llvm::SmallVector<QualType,16> Params;
221 QualType IdType = Ctx.getObjCIdType();
222 QualType SelType = Ctx.getObjCSelType();
223 Params.push_back(IdType);
224 Params.push_back(SelType);
225 Params.push_back(Ctx.LongTy);
226 Params.push_back(IdType);
227 Params.push_back(Ctx.BoolTy);
228 Params.push_back(Ctx.BoolTy);
229 const llvm::FunctionType *FTy =
230 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
231 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
232 }
233
234 llvm::Constant *getEnumerationMutationFn() {
235 // void objc_enumerationMutation (id)
236 std::vector<const llvm::Type*> Args;
237 Args.push_back(ObjectPtrTy);
238 llvm::FunctionType *FTy =
239 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
240 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
241 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000242
243 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000244 llvm::Constant *getGcReadWeakFn() {
245 // id objc_read_weak (id *)
246 std::vector<const llvm::Type*> Args;
247 Args.push_back(ObjectPtrTy->getPointerTo());
248 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
249 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
250 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000251
252 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000253 llvm::Constant *getGcAssignWeakFn() {
254 // id objc_assign_weak (id, id *)
255 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
256 Args.push_back(ObjectPtrTy->getPointerTo());
257 llvm::FunctionType *FTy =
258 llvm::FunctionType::get(ObjectPtrTy, Args, false);
259 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
260 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000261
262 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000263 llvm::Constant *getGcAssignGlobalFn() {
264 // id objc_assign_global(id, id *)
265 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
266 Args.push_back(ObjectPtrTy->getPointerTo());
267 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
268 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
269 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000270
271 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000272 llvm::Constant *getGcAssignIvarFn() {
273 // id objc_assign_ivar(id, id *)
274 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
275 Args.push_back(ObjectPtrTy->getPointerTo());
276 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
277 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
278 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000279
280 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000281 llvm::Constant *getGcAssignStrongCastFn() {
282 // id objc_assign_global(id, id *)
283 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
284 Args.push_back(ObjectPtrTy->getPointerTo());
285 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
286 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
287 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000288
289 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000290 llvm::Constant *getExceptionThrowFn() {
291 // void objc_exception_throw(id)
292 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
293 llvm::FunctionType *FTy =
294 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
295 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
296 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000297
Daniel Dunbar1c566672009-02-24 01:43:46 +0000298 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000299 llvm::Constant *getSyncEnterFn() {
300 // void objc_sync_enter (id)
301 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
302 llvm::FunctionType *FTy =
303 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
304 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
305 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000306
307 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000308 llvm::Constant *getSyncExitFn() {
309 // void objc_sync_exit (id)
310 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
311 llvm::FunctionType *FTy =
312 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
313 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
314 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000315
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000316 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
317 ~ObjCCommonTypesHelper(){}
318};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000319
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320/// ObjCTypesHelper - Helper class that encapsulates lazy
321/// construction of varies types used during ObjC generation.
322class ObjCTypesHelper : public ObjCCommonTypesHelper {
323private:
324
Chris Lattner4176b0c2009-04-22 02:32:31 +0000325 llvm::Constant *getMessageSendFn() {
326 // id objc_msgSend (id, SEL, ...)
327 std::vector<const llvm::Type*> Params;
328 Params.push_back(ObjectPtrTy);
329 Params.push_back(SelectorPtrTy);
330 return
331 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
332 Params, true),
333 "objc_msgSend");
334 }
335
336 llvm::Constant *getMessageSendStretFn() {
337 // id objc_msgSend_stret (id, SEL, ...)
338 std::vector<const llvm::Type*> Params;
339 Params.push_back(ObjectPtrTy);
340 Params.push_back(SelectorPtrTy);
341 return
342 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
343 Params, true),
344 "objc_msgSend_stret");
345
346 }
347
348 llvm::Constant *getMessageSendFpretFn() {
349 // FIXME: This should be long double on x86_64?
350 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
351 std::vector<const llvm::Type*> Params;
352 Params.push_back(ObjectPtrTy);
353 Params.push_back(SelectorPtrTy);
354 return
355 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
356 Params,
357 true),
358 "objc_msgSend_fpret");
359
360 }
361
362 llvm::Constant *getMessageSendSuperFn() {
363 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
364 std::vector<const llvm::Type*> Params;
365 Params.push_back(SuperPtrTy);
366 Params.push_back(SelectorPtrTy);
367 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
368 Params, true),
369 "objc_msgSendSuper");
370 }
371 llvm::Constant *getMessageSendSuperStretFn() {
372 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
373 // SEL op, ...)
374 std::vector<const llvm::Type*> Params;
375 Params.push_back(Int8PtrTy);
376 Params.push_back(SuperPtrTy);
377 Params.push_back(SelectorPtrTy);
378 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
379 Params, true),
380 "objc_msgSendSuper_stret");
381 }
382
383 llvm::Constant *getMessageSendSuperFpretFn() {
384 // There is no objc_msgSendSuper_fpret? How can that work?
385 return getMessageSendSuperFn();
386 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000387
388public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000389 /// SymtabTy - LLVM type for struct objc_symtab.
390 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
392 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000393 /// ModuleTy - LLVM type for struct objc_module.
394 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000395
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000396 /// ProtocolTy - LLVM type for struct objc_protocol.
397 const llvm::StructType *ProtocolTy;
398 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
399 const llvm::Type *ProtocolPtrTy;
400 /// ProtocolExtensionTy - LLVM type for struct
401 /// objc_protocol_extension.
402 const llvm::StructType *ProtocolExtensionTy;
403 /// ProtocolExtensionTy - LLVM type for struct
404 /// objc_protocol_extension *.
405 const llvm::Type *ProtocolExtensionPtrTy;
406 /// MethodDescriptionTy - LLVM type for struct
407 /// objc_method_description.
408 const llvm::StructType *MethodDescriptionTy;
409 /// MethodDescriptionListTy - LLVM type for struct
410 /// objc_method_description_list.
411 const llvm::StructType *MethodDescriptionListTy;
412 /// MethodDescriptionListPtrTy - LLVM type for struct
413 /// objc_method_description_list *.
414 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000415 /// ProtocolListTy - LLVM type for struct objc_property_list.
416 const llvm::Type *ProtocolListTy;
417 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
418 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000419 /// CategoryTy - LLVM type for struct objc_category.
420 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000421 /// ClassTy - LLVM type for struct objc_class.
422 const llvm::StructType *ClassTy;
423 /// ClassPtrTy - LLVM type for struct objc_class *.
424 const llvm::Type *ClassPtrTy;
425 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
426 const llvm::StructType *ClassExtensionTy;
427 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
428 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000429 // IvarTy - LLVM type for struct objc_ivar.
430 const llvm::StructType *IvarTy;
431 /// IvarListTy - LLVM type for struct objc_ivar_list.
432 const llvm::Type *IvarListTy;
433 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
434 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000435 /// MethodListTy - LLVM type for struct objc_method_list.
436 const llvm::Type *MethodListTy;
437 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
438 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000439
440 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
441 const llvm::Type *ExceptionDataTy;
442
Anders Carlsson124526b2008-09-09 10:10:21 +0000443 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000444 llvm::Constant *getExceptionTryEnterFn() {
445 std::vector<const llvm::Type*> Params;
446 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
447 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
448 Params, false),
449 "objc_exception_try_enter");
450 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000451
452 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000453 llvm::Constant *getExceptionTryExitFn() {
454 std::vector<const llvm::Type*> Params;
455 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
456 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
457 Params, false),
458 "objc_exception_try_exit");
459 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000460
461 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000462 llvm::Constant *getExceptionExtractFn() {
463 std::vector<const llvm::Type*> Params;
464 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
465 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
466 Params, false),
467 "objc_exception_extract");
468
469 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000470
471 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000472 llvm::Constant *getExceptionMatchFn() {
473 std::vector<const llvm::Type*> Params;
474 Params.push_back(ClassPtrTy);
475 Params.push_back(ObjectPtrTy);
476 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
477 Params, false),
478 "objc_exception_match");
479
480 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000481
482 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000483 llvm::Constant *getSetJmpFn() {
484 std::vector<const llvm::Type*> Params;
485 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
486 return
487 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
488 Params, false),
489 "_setjmp");
490
491 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000492
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000493public:
494 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000495 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000496
497
Chris Lattner74391b42009-03-22 21:03:39 +0000498 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000499 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000500 }
501
Chris Lattner74391b42009-03-22 21:03:39 +0000502 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000503 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000504 }
505
Chris Lattner74391b42009-03-22 21:03:39 +0000506 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000507 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000508 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000509};
510
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000511/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000512/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000513class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000514public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000515
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000516 // MethodListnfABITy - LLVM for struct _method_list_t
517 const llvm::StructType *MethodListnfABITy;
518
519 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
520 const llvm::Type *MethodListnfABIPtrTy;
521
522 // ProtocolnfABITy = LLVM for struct _protocol_t
523 const llvm::StructType *ProtocolnfABITy;
524
Daniel Dunbar948e2582009-02-15 07:36:20 +0000525 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
526 const llvm::Type *ProtocolnfABIPtrTy;
527
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000528 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
529 const llvm::StructType *ProtocolListnfABITy;
530
531 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
532 const llvm::Type *ProtocolListnfABIPtrTy;
533
534 // ClassnfABITy - LLVM for struct _class_t
535 const llvm::StructType *ClassnfABITy;
536
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000537 // ClassnfABIPtrTy - LLVM for struct _class_t*
538 const llvm::Type *ClassnfABIPtrTy;
539
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000540 // IvarnfABITy - LLVM for struct _ivar_t
541 const llvm::StructType *IvarnfABITy;
542
543 // IvarListnfABITy - LLVM for struct _ivar_list_t
544 const llvm::StructType *IvarListnfABITy;
545
546 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
547 const llvm::Type *IvarListnfABIPtrTy;
548
549 // ClassRonfABITy - LLVM for struct _class_ro_t
550 const llvm::StructType *ClassRonfABITy;
551
552 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
553 const llvm::Type *ImpnfABITy;
554
555 // CategorynfABITy - LLVM for struct _category_t
556 const llvm::StructType *CategorynfABITy;
557
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000558 // New types for nonfragile abi messaging.
559
560 // MessageRefTy - LLVM for:
561 // struct _message_ref_t {
562 // IMP messenger;
563 // SEL name;
564 // };
565 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000566 // MessageRefCTy - clang type for struct _message_ref_t
567 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000568
569 // MessageRefPtrTy - LLVM for struct _message_ref_t*
570 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000571 // MessageRefCPtrTy - clang type for struct _message_ref_t*
572 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000573
Fariborz Jahanianef163782009-02-05 01:13:09 +0000574 // MessengerTy - Type of the messenger (shown as IMP above)
575 const llvm::FunctionType *MessengerTy;
576
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000577 // SuperMessageRefTy - LLVM for:
578 // struct _super_message_ref_t {
579 // SUPER_IMP messenger;
580 // SEL name;
581 // };
582 const llvm::StructType *SuperMessageRefTy;
583
584 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
585 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000586
Chris Lattner1c02f862009-04-22 02:53:24 +0000587 llvm::Constant *getMessageSendFixupFn() {
588 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
589 std::vector<const llvm::Type*> Params;
590 Params.push_back(ObjectPtrTy);
591 Params.push_back(MessageRefPtrTy);
592 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
593 Params, true),
594 "objc_msgSend_fixup");
595 }
596
597 llvm::Constant *getMessageSendFpretFixupFn() {
598 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
599 std::vector<const llvm::Type*> Params;
600 Params.push_back(ObjectPtrTy);
601 Params.push_back(MessageRefPtrTy);
602 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
603 Params, true),
604 "objc_msgSend_fpret_fixup");
605 }
606
607 llvm::Constant *getMessageSendStretFixupFn() {
608 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
609 std::vector<const llvm::Type*> Params;
610 Params.push_back(ObjectPtrTy);
611 Params.push_back(MessageRefPtrTy);
612 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
613 Params, true),
614 "objc_msgSend_stret_fixup");
615 }
616
617 llvm::Constant *getMessageSendIdFixupFn() {
618 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
619 std::vector<const llvm::Type*> Params;
620 Params.push_back(ObjectPtrTy);
621 Params.push_back(MessageRefPtrTy);
622 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
623 Params, true),
624 "objc_msgSendId_fixup");
625 }
626
627 llvm::Constant *getMessageSendIdStretFixupFn() {
628 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
629 std::vector<const llvm::Type*> Params;
630 Params.push_back(ObjectPtrTy);
631 Params.push_back(MessageRefPtrTy);
632 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
633 Params, true),
634 "objc_msgSendId_stret_fixup");
635 }
636 llvm::Constant *getMessageSendSuper2FixupFn() {
637 // id objc_msgSendSuper2_fixup (struct objc_super *,
638 // struct _super_message_ref_t*, ...)
639 std::vector<const llvm::Type*> Params;
640 Params.push_back(SuperPtrTy);
641 Params.push_back(SuperMessageRefPtrTy);
642 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
643 Params, true),
644 "objc_msgSendSuper2_fixup");
645 }
646
647 llvm::Constant *getMessageSendSuper2StretFixupFn() {
648 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
649 // struct _super_message_ref_t*, ...)
650 std::vector<const llvm::Type*> Params;
651 Params.push_back(SuperPtrTy);
652 Params.push_back(SuperMessageRefPtrTy);
653 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
654 Params, true),
655 "objc_msgSendSuper2_stret_fixup");
656 }
657
658
659
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000660 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
661 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000662 llvm::Value *getEHPersonalityPtr() {
663 llvm::Constant *Personality =
664 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
665 std::vector<const llvm::Type*>(),
666 true),
667 "__objc_personality_v0");
668 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
669 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000670
Chris Lattner8a569112009-04-22 02:15:23 +0000671 llvm::Constant *getUnwindResumeOrRethrowFn() {
672 std::vector<const llvm::Type*> Params;
673 Params.push_back(Int8PtrTy);
674 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
675 Params, false),
676 "_Unwind_Resume_or_Rethrow");
677 }
678
679 llvm::Constant *getObjCEndCatchFn() {
680 std::vector<const llvm::Type*> Params;
681 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
682 Params, false),
683 "objc_end_catch");
684
685 }
686
687 llvm::Constant *getObjCBeginCatchFn() {
688 std::vector<const llvm::Type*> Params;
689 Params.push_back(Int8PtrTy);
690 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
691 Params, false),
692 "objc_begin_catch");
693 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000694
695 const llvm::StructType *EHTypeTy;
696 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000698 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
699 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000700};
701
702class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000703public:
704 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000705 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000706 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000707 unsigned int ivar_bytepos;
708 unsigned int ivar_size;
709 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000710
711 // Allow sorting based on byte pos.
712 bool operator<(const GC_IVAR &b) const {
713 return ivar_bytepos < b.ivar_bytepos;
714 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000715 };
716
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000717 class SKIP_SCAN {
718 public:
719 unsigned int skip;
720 unsigned int scan;
721 SKIP_SCAN() : skip(0), scan(0) {}
722 };
723
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000724protected:
725 CodeGen::CodeGenModule &CGM;
726 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000727 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000728
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000729 // gc ivar layout bitmap calculation helper caches.
730 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
731 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000732
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000733 /// LazySymbols - Symbols to generate a lazy reference for. See
734 /// DefinedSymbols and FinishModule().
735 std::set<IdentifierInfo*> LazySymbols;
736
737 /// DefinedSymbols - External symbols which are defined by this
738 /// module. The symbols in this list and LazySymbols are used to add
739 /// special linker symbols which ensure that Objective-C modules are
740 /// linked properly.
741 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000742
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000743 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000744 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000745
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000746 /// MethodVarNames - uniqued method variable names.
747 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000748
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000749 /// MethodVarTypes - uniqued method type signatures. We have to use
750 /// a StringMap here because have no other unique reference.
751 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000752
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000753 /// MethodDefinitions - map of methods which have been defined in
754 /// this translation unit.
755 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000756
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000757 /// PropertyNames - uniqued method variable names.
758 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000759
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000760 /// ClassReferences - uniqued class references.
761 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000762
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000763 /// SelectorReferences - uniqued selector references.
764 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000765
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000766 /// Protocols - Protocols for which an objc_protocol structure has
767 /// been emitted. Forward declarations are handled by creating an
768 /// empty structure whose initializer is filled in when/if defined.
769 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000770
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000771 /// DefinedProtocols - Protocols which have actually been
772 /// defined. We should not need this, see FIXME in GenerateProtocol.
773 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000774
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000775 /// DefinedClasses - List of defined classes.
776 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000777
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000778 /// DefinedCategories - List of defined categories.
779 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000780
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000781 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000782 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000783 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000784
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000785 /// GetNameForMethod - Return a name for the given method.
786 /// \param[out] NameOut - The return value.
787 void GetNameForMethod(const ObjCMethodDecl *OMD,
788 const ObjCContainerDecl *CD,
789 std::string &NameOut);
790
791 /// GetMethodVarName - Return a unique constant for the given
792 /// selector's name. The return value has type char *.
793 llvm::Constant *GetMethodVarName(Selector Sel);
794 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
795 llvm::Constant *GetMethodVarName(const std::string &Name);
796
797 /// GetMethodVarType - Return a unique constant for the given
798 /// selector's name. The return value has type char *.
799
800 // FIXME: This is a horrible name.
801 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000802 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000803
804 /// GetPropertyName - Return a unique constant for the given
805 /// name. The return value has type char *.
806 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
807
808 // FIXME: This can be dropped once string functions are unified.
809 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
810 const Decl *Container);
811
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000812 /// GetClassName - Return a unique constant for the given selector's
813 /// name. The return value has type char *.
814 llvm::Constant *GetClassName(IdentifierInfo *Ident);
815
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000816 /// BuildIvarLayout - Builds ivar layout bitmap for the class
817 /// implementation for the __strong or __weak case.
818 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000819 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
820 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000821
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000822 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
823 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000824 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000825 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000826 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000827 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000828
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000829 /// GetIvarLayoutName - Returns a unique constant for the given
830 /// ivar layout bitmap.
831 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
832 const ObjCCommonTypesHelper &ObjCTypes);
833
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000834 /// EmitPropertyList - Emit the given property list. The return
835 /// value has type PropertyListPtrTy.
836 llvm::Constant *EmitPropertyList(const std::string &Name,
837 const Decl *Container,
838 const ObjCContainerDecl *OCD,
839 const ObjCCommonTypesHelper &ObjCTypes);
840
Fariborz Jahanianda320092009-01-29 19:24:30 +0000841 /// GetProtocolRef - Return a reference to the internal protocol
842 /// description, creating an empty one if it has not been
843 /// defined. The return value has type ProtocolPtrTy.
844 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000845
Chris Lattnercd0ee142009-03-31 08:33:16 +0000846 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000847 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
848 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000849 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000850
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000851 /// CreateMetadataVar - Create a global variable with internal
852 /// linkage for use by the Objective-C runtime.
853 ///
854 /// This is a convenience wrapper which not only creates the
855 /// variable, but also sets the section and alignment and adds the
856 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000857 ///
858 /// \param Name - The variable name.
859 /// \param Init - The variable initializer; this is also used to
860 /// define the type of the variable.
861 /// \param Section - The section the variable should go into, or 0.
862 /// \param Align - The alignment for the variable, or 0.
863 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000864 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000865 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
866 llvm::Constant *Init,
867 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000868 unsigned Align,
869 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000870
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000871 /// GetNamedIvarList - Return the list of ivars in the interface
872 /// itself (not including super classes and not including unnamed
873 /// bitfields).
874 ///
875 /// For the non-fragile ABI, this also includes synthesized property
876 /// ivars.
877 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
878 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
879
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000880public:
881 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
882 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000883
Steve Naroff33fdb732009-03-31 16:53:37 +0000884 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000885
886 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
887 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000888
889 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
890
891 /// GetOrEmitProtocol - Get the protocol object for the given
892 /// declaration, emitting it if necessary. The return value has type
893 /// ProtocolPtrTy.
894 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
895
896 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
897 /// object for the given declaration, emitting it if needed. These
898 /// forward references will be filled in with empty bodies if no
899 /// definition is seen. The return value has type ProtocolPtrTy.
900 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000901};
902
903class CGObjCMac : public CGObjCCommonMac {
904private:
905 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000906 /// EmitImageInfo - Emit the image info marker used to encode some module
907 /// level information.
908 void EmitImageInfo();
909
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000910 /// EmitModuleInfo - Another marker encoding module level
911 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000912 void EmitModuleInfo();
913
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000914 /// EmitModuleSymols - Emit module symbols, the list of defined
915 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000916 llvm::Constant *EmitModuleSymbols();
917
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000918 /// FinishModule - Write out global data structures at the end of
919 /// processing a translation unit.
920 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000921
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000922 /// EmitClassExtension - Generate the class extension structure used
923 /// to store the weak ivar layout and properties. The return value
924 /// has type ClassExtensionPtrTy.
925 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
926
927 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
928 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000929 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000930 const ObjCInterfaceDecl *ID);
931
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000932 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000933 QualType ResultType,
934 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000935 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000936 QualType Arg0Ty,
937 bool IsSuper,
938 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000939
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000940 /// EmitIvarList - Emit the ivar list for the given
941 /// implementation. If ForClass is true the list of class ivars
942 /// (i.e. metaclass ivars) is emitted, otherwise the list of
943 /// interface ivars will be emitted. The return value has type
944 /// IvarListPtrTy.
945 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000946 bool ForClass);
947
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000948 /// EmitMetaClass - Emit a forward reference to the class structure
949 /// for the metaclass of the given interface. The return value has
950 /// type ClassPtrTy.
951 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
952
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000953 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000954 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000955 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
956 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000957 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000958 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000959
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000960 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000961
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000962 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000963
964 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000965 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000966 llvm::Constant *EmitMethodList(const std::string &Name,
967 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000968 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000969
970 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000971 /// method declarations.
972 /// - TypeName: The name for the type containing the methods.
973 /// - IsProtocol: True iff these methods are for a protocol.
974 /// - ClassMethds: True iff these are class methods.
975 /// - Required: When true, only "required" methods are
976 /// listed. Similarly, when false only "optional" methods are
977 /// listed. For classes this should always be true.
978 /// - begin, end: The method list to output.
979 ///
980 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000981 llvm::Constant *EmitMethodDescList(const std::string &Name,
982 const char *Section,
983 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000984
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000985 /// GetOrEmitProtocol - Get the protocol object for the given
986 /// declaration, emitting it if necessary. The return value has type
987 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000988 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000989
990 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
991 /// object for the given declaration, emitting it if needed. These
992 /// forward references will be filled in with empty bodies if no
993 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000994 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000995
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000996 /// EmitProtocolExtension - Generate the protocol extension
997 /// structure used to store optional instance and class methods, and
998 /// protocol properties. The return value has type
999 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001000 llvm::Constant *
1001 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1002 const ConstantVector &OptInstanceMethods,
1003 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001004
1005 /// EmitProtocolList - Generate the list of referenced
1006 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001007 llvm::Constant *EmitProtocolList(const std::string &Name,
1008 ObjCProtocolDecl::protocol_iterator begin,
1009 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001010
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001011 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1012 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001013 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001014
Fariborz Jahanianda320092009-01-29 19:24:30 +00001015 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001016 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001018 virtual llvm::Function *ModuleInitFunction();
1019
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001020 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001021 QualType ResultType,
1022 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001023 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001024 bool IsClassMessage,
1025 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001026
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001027 virtual CodeGen::RValue
1028 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001029 QualType ResultType,
1030 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001031 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001032 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001033 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001034 bool IsClassMessage,
1035 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001036
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001037 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001038 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001040 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001041
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001042 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001043
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001044 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001045
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001046 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001047 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001048
Chris Lattner74391b42009-03-22 21:03:39 +00001049 virtual llvm::Constant *GetPropertyGetFunction();
1050 virtual llvm::Constant *GetPropertySetFunction();
1051 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001052
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001053 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1054 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001055 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1056 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001057 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001058 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001059 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1060 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001061 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1062 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001063 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1064 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001065 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1066 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001067
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001068 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1069 QualType ObjectTy,
1070 llvm::Value *BaseValue,
1071 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001072 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001073 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001074 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001075 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001076};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001077
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001078class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001079private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001080 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001081 llvm::GlobalVariable* ObjCEmptyCacheVar;
1082 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001083
Daniel Dunbar11394522009-04-18 08:51:00 +00001084 /// SuperClassReferences - uniqued super class references.
1085 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1086
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001087 /// MetaClassReferences - uniqued meta class references.
1088 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001089
1090 /// EHTypeReferences - uniqued class ehtype references.
1091 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001092
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001093 /// FinishNonFragileABIModule - Write out global data structures at the end of
1094 /// processing a translation unit.
1095 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001096
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001097 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1098 unsigned InstanceStart,
1099 unsigned InstanceSize,
1100 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001101 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1102 llvm::Constant *IsAGV,
1103 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001104 llvm::Constant *ClassRoGV,
1105 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001106
1107 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1108
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001109 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1110
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001111 /// EmitMethodList - Emit the method list for the given
1112 /// implementation. The return value has type MethodListnfABITy.
1113 llvm::Constant *EmitMethodList(const std::string &Name,
1114 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001115 const ConstantVector &Methods);
1116 /// EmitIvarList - Emit the ivar list for the given
1117 /// implementation. If ForClass is true the list of class ivars
1118 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1119 /// interface ivars will be emitted. The return value has type
1120 /// IvarListnfABIPtrTy.
1121 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001122
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001123 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001124 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001125 unsigned long int offset);
1126
Fariborz Jahanianda320092009-01-29 19:24:30 +00001127 /// GetOrEmitProtocol - Get the protocol object for the given
1128 /// declaration, emitting it if necessary. The return value has type
1129 /// ProtocolPtrTy.
1130 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1131
1132 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1133 /// object for the given declaration, emitting it if needed. These
1134 /// forward references will be filled in with empty bodies if no
1135 /// definition is seen. The return value has type ProtocolPtrTy.
1136 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1137
1138 /// EmitProtocolList - Generate the list of referenced
1139 /// protocols. The return value has type ProtocolListPtrTy.
1140 llvm::Constant *EmitProtocolList(const std::string &Name,
1141 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001142 ObjCProtocolDecl::protocol_iterator end);
1143
1144 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1145 QualType ResultType,
1146 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001147 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001148 QualType Arg0Ty,
1149 bool IsSuper,
1150 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001151
1152 /// GetClassGlobal - Return the global variable for the Objective-C
1153 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001154 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1155
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001156 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001157 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001158 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001159 const ObjCInterfaceDecl *ID);
1160
1161 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1162 /// for the given super class reference.
1163 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1164 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001165
1166 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1167 /// meta-data
1168 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1169 const ObjCInterfaceDecl *ID);
1170
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001171 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1172 /// the given ivar.
1173 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001174 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001175 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001176 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001177
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001178 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1179 /// for the given selector.
1180 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001181
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001182 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001183 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001184 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1185 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001186
1187 const char *getMetaclassSymbolPrefix() const {
1188 return "OBJC_METACLASS_$_";
1189 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001190
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001191 const char *getClassSymbolPrefix() const {
1192 return "OBJC_CLASS_$_";
1193 }
1194
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001195 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1196 uint32_t &InstanceStart,
1197 uint32_t &InstanceSize);
1198
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001199public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001200 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001201 // FIXME. All stubs for now!
1202 virtual llvm::Function *ModuleInitFunction();
1203
1204 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1205 QualType ResultType,
1206 Selector Sel,
1207 llvm::Value *Receiver,
1208 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001209 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001210
1211 virtual CodeGen::RValue
1212 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1213 QualType ResultType,
1214 Selector Sel,
1215 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001216 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001217 llvm::Value *Receiver,
1218 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001219 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001220
1221 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001222 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001223
1224 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001225 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001226
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001227 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001228
1229 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001230 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001231 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001232
Chris Lattner74391b42009-03-22 21:03:39 +00001233 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001234 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001235 }
Chris Lattner74391b42009-03-22 21:03:39 +00001236 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001237 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001238 }
Chris Lattner74391b42009-03-22 21:03:39 +00001239 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001240 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001241 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001242
1243 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001244 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001245 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001246 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001247 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001248 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001249 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001250 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001251 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001252 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001253 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001254 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001255 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001256 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001257 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1258 QualType ObjectTy,
1259 llvm::Value *BaseValue,
1260 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001261 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001262 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001263 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001264 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001265};
1266
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001267} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001268
1269/* *** Helper Functions *** */
1270
1271/// getConstantGEP() - Help routine to construct simple GEPs.
1272static llvm::Constant *getConstantGEP(llvm::Constant *C,
1273 unsigned idx0,
1274 unsigned idx1) {
1275 llvm::Value *Idxs[] = {
1276 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1277 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1278 };
1279 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1280}
1281
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001282/// hasObjCExceptionAttribute - Return true if this class or any super
1283/// class has the __objc_exception__ attribute.
1284static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001285 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001286 return true;
1287 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1288 return hasObjCExceptionAttribute(Super);
1289 return false;
1290}
1291
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001292/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001293
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001294CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1295 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001296{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001297 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001298 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001299}
1300
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001301/// GetClass - Return a reference to the class for the given interface
1302/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001303llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001304 const ObjCInterfaceDecl *ID) {
1305 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001306}
1307
1308/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001309llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001310 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001311}
1312
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001313/// Generate a constant CFString object.
1314/*
1315 struct __builtin_CFString {
1316 const int *isa; // point to __CFConstantStringClassReference
1317 int flags;
1318 const char *str;
1319 long length;
1320 };
1321*/
1322
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001323llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001324 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001325 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001326}
1327
1328/// Generates a message send where the super is the receiver. This is
1329/// a message send to self with special delivery semantics indicating
1330/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001331CodeGen::RValue
1332CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001333 QualType ResultType,
1334 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001335 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001336 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001337 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001338 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001339 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001340 // Create and init a super structure; this is a (receiver, class)
1341 // pair we will pass to objc_msgSendSuper.
1342 llvm::Value *ObjCSuper =
1343 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1344 llvm::Value *ReceiverAsObject =
1345 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1346 CGF.Builder.CreateStore(ReceiverAsObject,
1347 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001348
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001349 // If this is a class message the metaclass is passed as the target.
1350 llvm::Value *Target;
1351 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001352 if (isCategoryImpl) {
1353 // Message sent to 'super' in a class method defined in a category
1354 // implementation requires an odd treatment.
1355 // If we are in a class method, we must retrieve the
1356 // _metaclass_ for the current class, pointed at by
1357 // the class's "isa" pointer. The following assumes that
1358 // isa" is the first ivar in a class (which it must be).
1359 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1360 Target = CGF.Builder.CreateStructGEP(Target, 0);
1361 Target = CGF.Builder.CreateLoad(Target);
1362 }
1363 else {
1364 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1365 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1366 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1367 Target = Super;
1368 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001369 } else {
1370 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1371 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001372 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1373 // and ObjCTypes types.
1374 const llvm::Type *ClassTy =
1375 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001376 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001377 CGF.Builder.CreateStore(Target,
1378 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1379
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001380 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001381 ObjCSuper, ObjCTypes.SuperPtrCTy,
1382 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001383}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001384
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001385/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001386CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001387 QualType ResultType,
1388 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001389 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001390 bool IsClassMessage,
1391 const CallArgList &CallArgs) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001392 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001393 Receiver, CGF.getContext().getObjCIdType(),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001394 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001395}
1396
1397CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001398 QualType ResultType,
1399 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001400 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001401 QualType Arg0Ty,
1402 bool IsSuper,
1403 const CallArgList &CallArgs) {
1404 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001405 if (!IsSuper)
1406 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001407 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1408 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1409 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001410 CGF.getContext().getObjCSelType()));
1411 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001412
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001413 CodeGenTypes &Types = CGM.getTypes();
1414 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1415 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001416
1417 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001418 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001419 Fn = ObjCTypes.getSendStretFn(IsSuper);
1420 } else if (ResultType->isFloatingType()) {
1421 // FIXME: Sadly, this is wrong. This actually depends on the
1422 // architecture. This happens to be right for x86-32 though.
1423 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1424 } else {
1425 Fn = ObjCTypes.getSendFn(IsSuper);
1426 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001427 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001428 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001429}
1430
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001431llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001432 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001433 // FIXME: I don't understand why gcc generates this, or where it is
1434 // resolved. Investigate. Its also wasteful to look this up over and
1435 // over.
1436 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1437
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001438 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1439 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001440}
1441
Fariborz Jahanianda320092009-01-29 19:24:30 +00001442void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001443 // FIXME: We shouldn't need this, the protocol decl should contain
1444 // enough information to tell us whether this was a declaration or a
1445 // definition.
1446 DefinedProtocols.insert(PD->getIdentifier());
1447
1448 // If we have generated a forward reference to this protocol, emit
1449 // it now. Otherwise do nothing, the protocol objects are lazily
1450 // emitted.
1451 if (Protocols.count(PD->getIdentifier()))
1452 GetOrEmitProtocol(PD);
1453}
1454
Fariborz Jahanianda320092009-01-29 19:24:30 +00001455llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001456 if (DefinedProtocols.count(PD->getIdentifier()))
1457 return GetOrEmitProtocol(PD);
1458 return GetOrEmitProtocolRef(PD);
1459}
1460
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001461/*
1462 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1463 struct _objc_protocol {
1464 struct _objc_protocol_extension *isa;
1465 char *protocol_name;
1466 struct _objc_protocol_list *protocol_list;
1467 struct _objc__method_prototype_list *instance_methods;
1468 struct _objc__method_prototype_list *class_methods
1469 };
1470
1471 See EmitProtocolExtension().
1472*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001473llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1474 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1475
1476 // Early exit if a defining object has already been generated.
1477 if (Entry && Entry->hasInitializer())
1478 return Entry;
1479
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001480 // FIXME: I don't understand why gcc generates this, or where it is
1481 // resolved. Investigate. Its also wasteful to look this up over and
1482 // over.
1483 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1484
Chris Lattner8ec03f52008-11-24 03:54:41 +00001485 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001486
1487 // Construct method lists.
1488 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1489 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001490 for (ObjCProtocolDecl::instmeth_iterator
1491 i = PD->instmeth_begin(CGM.getContext()),
1492 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001493 ObjCMethodDecl *MD = *i;
1494 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1495 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1496 OptInstanceMethods.push_back(C);
1497 } else {
1498 InstanceMethods.push_back(C);
1499 }
1500 }
1501
Douglas Gregor6ab35242009-04-09 21:40:53 +00001502 for (ObjCProtocolDecl::classmeth_iterator
1503 i = PD->classmeth_begin(CGM.getContext()),
1504 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001505 ObjCMethodDecl *MD = *i;
1506 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1507 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1508 OptClassMethods.push_back(C);
1509 } else {
1510 ClassMethods.push_back(C);
1511 }
1512 }
1513
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001514 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001515 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001516 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001517 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001518 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001519 PD->protocol_begin(),
1520 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001521 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001522 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1523 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001524 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1525 InstanceMethods);
1526 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001527 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1528 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001529 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1530 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001531 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1532 Values);
1533
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001534 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001535 // Already created, fix the linkage and update the initializer.
1536 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001537 Entry->setInitializer(Init);
1538 } else {
1539 Entry =
1540 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1541 llvm::GlobalValue::InternalLinkage,
1542 Init,
1543 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1544 &CGM.getModule());
1545 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001546 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001547 UsedGlobals.push_back(Entry);
1548 // FIXME: Is this necessary? Why only for protocol?
1549 Entry->setAlignment(4);
1550 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001551
1552 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001553}
1554
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001555llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001556 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1557
1558 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001559 // We use the initializer as a marker of whether this is a forward
1560 // reference or not. At module finalization we add the empty
1561 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001562 Entry =
1563 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001564 llvm::GlobalValue::ExternalLinkage,
1565 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001566 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001567 &CGM.getModule());
1568 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001569 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001570 UsedGlobals.push_back(Entry);
1571 // FIXME: Is this necessary? Why only for protocol?
1572 Entry->setAlignment(4);
1573 }
1574
1575 return Entry;
1576}
1577
1578/*
1579 struct _objc_protocol_extension {
1580 uint32_t size;
1581 struct objc_method_description_list *optional_instance_methods;
1582 struct objc_method_description_list *optional_class_methods;
1583 struct objc_property_list *instance_properties;
1584 };
1585*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001586llvm::Constant *
1587CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1588 const ConstantVector &OptInstanceMethods,
1589 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001590 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001591 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001592 std::vector<llvm::Constant*> Values(4);
1593 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001594 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001595 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1596 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001597 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1598 OptInstanceMethods);
1599 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001600 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1601 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001602 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1603 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001604 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1605 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001606 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001607
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001608 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001609 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1610 Values[3]->isNullValue())
1611 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1612
1613 llvm::Constant *Init =
1614 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001615
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001616 // No special section, but goes in llvm.used
1617 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1618 Init,
1619 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001620}
1621
1622/*
1623 struct objc_protocol_list {
1624 struct objc_protocol_list *next;
1625 long count;
1626 Protocol *list[];
1627 };
1628*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001629llvm::Constant *
1630CGObjCMac::EmitProtocolList(const std::string &Name,
1631 ObjCProtocolDecl::protocol_iterator begin,
1632 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001633 std::vector<llvm::Constant*> ProtocolRefs;
1634
Daniel Dunbardbc933702008-08-21 21:57:41 +00001635 for (; begin != end; ++begin)
1636 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001637
1638 // Just return null for empty protocol lists
1639 if (ProtocolRefs.empty())
1640 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1641
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001642 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001643 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1644
1645 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001646 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001647 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1648 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1649 Values[2] =
1650 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1651 ProtocolRefs.size()),
1652 ProtocolRefs);
1653
1654 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1655 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001656 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001657 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001658 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1659}
1660
1661/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001662 struct _objc_property {
1663 const char * const name;
1664 const char * const attributes;
1665 };
1666
1667 struct _objc_property_list {
1668 uint32_t entsize; // sizeof (struct _objc_property)
1669 uint32_t prop_count;
1670 struct _objc_property[prop_count];
1671 };
1672*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001673llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1674 const Decl *Container,
1675 const ObjCContainerDecl *OCD,
1676 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001677 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001678 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1679 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001680 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001681 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001682 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001683 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1684 Prop));
1685 }
1686
1687 // Return null for empty list.
1688 if (Properties.empty())
1689 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1690
1691 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001692 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001693 std::vector<llvm::Constant*> Values(3);
1694 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1695 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1696 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1697 Properties.size());
1698 Values[2] = llvm::ConstantArray::get(AT, Properties);
1699 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1700
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001701 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001702 CreateMetadataVar(Name, Init,
1703 (ObjCABI == 2) ? "__DATA, __objc_const" :
1704 "__OBJC,__property,regular,no_dead_strip",
1705 (ObjCABI == 2) ? 8 : 4,
1706 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001707 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001708}
1709
1710/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001711 struct objc_method_description_list {
1712 int count;
1713 struct objc_method_description list[];
1714 };
1715*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001716llvm::Constant *
1717CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1718 std::vector<llvm::Constant*> Desc(2);
1719 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1720 ObjCTypes.SelectorPtrTy);
1721 Desc[1] = GetMethodVarType(MD);
1722 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1723 Desc);
1724}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001725
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001726llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1727 const char *Section,
1728 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001729 // Return null for empty list.
1730 if (Methods.empty())
1731 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1732
1733 std::vector<llvm::Constant*> Values(2);
1734 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1735 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1736 Methods.size());
1737 Values[1] = llvm::ConstantArray::get(AT, Methods);
1738 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1739
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001740 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001741 return llvm::ConstantExpr::getBitCast(GV,
1742 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001743}
1744
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001745/*
1746 struct _objc_category {
1747 char *category_name;
1748 char *class_name;
1749 struct _objc_method_list *instance_methods;
1750 struct _objc_method_list *class_methods;
1751 struct _objc_protocol_list *protocols;
1752 uint32_t size; // <rdar://4585769>
1753 struct _objc_property_list *instance_properties;
1754 };
1755 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001756void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001757 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001758
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001759 // FIXME: This is poor design, the OCD should have a pointer to the
1760 // category decl. Additionally, note that Category can be null for
1761 // the @implementation w/o an @interface case. Sema should just
1762 // create one for us as it does for @implementation so everyone else
1763 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001764 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001765 const ObjCCategoryDecl *Category =
1766 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001767 std::string ExtName(Interface->getNameAsString() + "_" +
1768 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001769
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001770 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001771 for (ObjCCategoryImplDecl::instmeth_iterator
1772 i = OCD->instmeth_begin(CGM.getContext()),
1773 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001774 // Instance methods should always be defined.
1775 InstanceMethods.push_back(GetMethodConstant(*i));
1776 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001777 for (ObjCCategoryImplDecl::classmeth_iterator
1778 i = OCD->classmeth_begin(CGM.getContext()),
1779 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001780 // Class methods should always be defined.
1781 ClassMethods.push_back(GetMethodConstant(*i));
1782 }
1783
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001784 std::vector<llvm::Constant*> Values(7);
1785 Values[0] = GetClassName(OCD->getIdentifier());
1786 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001787 Values[2] =
1788 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1789 ExtName,
1790 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001791 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001792 Values[3] =
1793 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001794 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001795 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001796 if (Category) {
1797 Values[4] =
1798 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1799 Category->protocol_begin(),
1800 Category->protocol_end());
1801 } else {
1802 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1803 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001804 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001805
1806 // If there is no category @interface then there can be no properties.
1807 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001808 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001809 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001810 } else {
1811 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1812 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001813
1814 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1815 Values);
1816
1817 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001818 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1819 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001820 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001821 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001822}
1823
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001824// FIXME: Get from somewhere?
1825enum ClassFlags {
1826 eClassFlags_Factory = 0x00001,
1827 eClassFlags_Meta = 0x00002,
1828 // <rdr://5142207>
1829 eClassFlags_HasCXXStructors = 0x02000,
1830 eClassFlags_Hidden = 0x20000,
1831 eClassFlags_ABI2_Hidden = 0x00010,
1832 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1833};
1834
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001835/*
1836 struct _objc_class {
1837 Class isa;
1838 Class super_class;
1839 const char *name;
1840 long version;
1841 long info;
1842 long instance_size;
1843 struct _objc_ivar_list *ivars;
1844 struct _objc_method_list *methods;
1845 struct _objc_cache *cache;
1846 struct _objc_protocol_list *protocols;
1847 // Objective-C 1.0 extensions (<rdr://4585769>)
1848 const char *ivar_layout;
1849 struct _objc_class_ext *ext;
1850 };
1851
1852 See EmitClassExtension();
1853 */
1854void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001855 DefinedSymbols.insert(ID->getIdentifier());
1856
Chris Lattner8ec03f52008-11-24 03:54:41 +00001857 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001858 // FIXME: Gross
1859 ObjCInterfaceDecl *Interface =
1860 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001861 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001862 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001863 Interface->protocol_begin(),
1864 Interface->protocol_end());
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00001865 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001866 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001867 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001868
1869 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001870 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001871 Flags |= eClassFlags_Hidden;
1872
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001873 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001874 for (ObjCImplementationDecl::instmeth_iterator
1875 i = ID->instmeth_begin(CGM.getContext()),
1876 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001877 // Instance methods should always be defined.
1878 InstanceMethods.push_back(GetMethodConstant(*i));
1879 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001880 for (ObjCImplementationDecl::classmeth_iterator
1881 i = ID->classmeth_begin(CGM.getContext()),
1882 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001883 // Class methods should always be defined.
1884 ClassMethods.push_back(GetMethodConstant(*i));
1885 }
1886
Douglas Gregor653f1b12009-04-23 01:02:12 +00001887 for (ObjCImplementationDecl::propimpl_iterator
1888 i = ID->propimpl_begin(CGM.getContext()),
1889 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001890 ObjCPropertyImplDecl *PID = *i;
1891
1892 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1893 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1894
1895 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1896 if (llvm::Constant *C = GetMethodConstant(MD))
1897 InstanceMethods.push_back(C);
1898 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1899 if (llvm::Constant *C = GetMethodConstant(MD))
1900 InstanceMethods.push_back(C);
1901 }
1902 }
1903
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001904 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001905 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001906 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001907 // Record a reference to the super class.
1908 LazySymbols.insert(Super->getIdentifier());
1909
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001910 Values[ 1] =
1911 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1912 ObjCTypes.ClassPtrTy);
1913 } else {
1914 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1915 }
1916 Values[ 2] = GetClassName(ID->getIdentifier());
1917 // Version is always 0.
1918 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1919 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1920 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001921 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001922 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001923 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001924 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001925 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001926 // cache is always NULL.
1927 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1928 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001929 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001930 Values[11] = EmitClassExtension(ID);
1931 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1932 Values);
1933
1934 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001935 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1936 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001937 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001938 DefinedClasses.push_back(GV);
1939}
1940
1941llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1942 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001943 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001944 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001945 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001946 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001947
Daniel Dunbar04d40782009-04-14 06:00:08 +00001948 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001949 Flags |= eClassFlags_Hidden;
1950
1951 std::vector<llvm::Constant*> Values(12);
1952 // The isa for the metaclass is the root of the hierarchy.
1953 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1954 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1955 Root = Super;
1956 Values[ 0] =
1957 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1958 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001959 // The super class for the metaclass is emitted as the name of the
1960 // super class. The runtime fixes this up to point to the
1961 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001962 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1963 Values[ 1] =
1964 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1965 ObjCTypes.ClassPtrTy);
1966 } else {
1967 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1968 }
1969 Values[ 2] = GetClassName(ID->getIdentifier());
1970 // Version is always 0.
1971 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1972 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1973 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001974 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001975 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001976 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001977 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001978 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001979 // cache is always NULL.
1980 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1981 Values[ 9] = Protocols;
1982 // ivar_layout for metaclass is always NULL.
1983 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1984 // The class extension is always unused for metaclasses.
1985 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1986 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1987 Values);
1988
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001989 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001990 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001991
1992 // Check for a forward reference.
1993 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1994 if (GV) {
1995 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1996 "Forward metaclass reference has incorrect type.");
1997 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1998 GV->setInitializer(Init);
1999 } else {
2000 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2001 llvm::GlobalValue::InternalLinkage,
2002 Init, Name,
2003 &CGM.getModule());
2004 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002005 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002006 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002007 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008
2009 return GV;
2010}
2011
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002012llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002013 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002014
2015 // FIXME: Should we look these up somewhere other than the
2016 // module. Its a bit silly since we only generate these while
2017 // processing an implementation, so exactly one pointer would work
2018 // if know when we entered/exitted an implementation block.
2019
2020 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002021 // Previously, metaclass with internal linkage may have been defined.
2022 // pass 'true' as 2nd argument so it is returned.
2023 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002024 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2025 "Forward metaclass reference has incorrect type.");
2026 return GV;
2027 } else {
2028 // Generate as an external reference to keep a consistent
2029 // module. This will be patched up when we emit the metaclass.
2030 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2031 llvm::GlobalValue::ExternalLinkage,
2032 0,
2033 Name,
2034 &CGM.getModule());
2035 }
2036}
2037
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002038/*
2039 struct objc_class_ext {
2040 uint32_t size;
2041 const char *weak_ivar_layout;
2042 struct _objc_property_list *properties;
2043 };
2044*/
2045llvm::Constant *
2046CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2047 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002048 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002049
2050 std::vector<llvm::Constant*> Values(3);
2051 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002052 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002053 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002054 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002055
2056 // Return null if no extension bits are used.
2057 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2058 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2059
2060 llvm::Constant *Init =
2061 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002062 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002063 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2064 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002065}
2066
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002067/// getInterfaceDeclForIvar - Get the interface declaration node where
2068/// this ivar is declared in.
2069/// FIXME. Ideally, this info should be in the ivar node. But currently
2070/// it is not and prevailing wisdom is that ASTs should not have more
2071/// info than is absolutely needed, even though this info reflects the
2072/// source language.
2073///
2074static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2075 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002076 const ObjCIvarDecl *IVD,
2077 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002078 if (!OI)
2079 return 0;
2080 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2081 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2082 E = OI->ivar_end(); I != E; ++I)
2083 if ((*I)->getIdentifier() == IVD->getIdentifier())
2084 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002085 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002086 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2087 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002088 ObjCPropertyDecl *PDecl = (*I);
2089 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2090 if (IV->getIdentifier() == IVD->getIdentifier())
2091 return OI;
2092 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002093 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002094}
2095
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002096/*
2097 struct objc_ivar {
2098 char *ivar_name;
2099 char *ivar_type;
2100 int ivar_offset;
2101 };
2102
2103 struct objc_ivar_list {
2104 int ivar_count;
2105 struct objc_ivar list[count];
2106 };
2107 */
2108llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002109 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002110 std::vector<llvm::Constant*> Ivars, Ivar(3);
2111
2112 // When emitting the root class GCC emits ivar entries for the
2113 // actual class structure. It is not clear if we need to follow this
2114 // behavior; for now lets try and get away with not doing it. If so,
2115 // the cleanest solution would be to make up an ObjCInterfaceDecl
2116 // for the class.
2117 if (ForClass)
2118 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002119
2120 ObjCInterfaceDecl *OID =
2121 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002122
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002123 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2124 GetNamedIvarList(OID, OIvars);
2125
2126 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2127 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002128 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2129 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002130 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002131 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002132 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002133 }
2134
2135 // Return null for empty list.
2136 if (Ivars.empty())
2137 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2138
2139 std::vector<llvm::Constant*> Values(2);
2140 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2141 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2142 Ivars.size());
2143 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2144 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2145
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002146 llvm::GlobalVariable *GV;
2147 if (ForClass)
2148 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002149 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2150 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002151 else
2152 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2153 + ID->getNameAsString(),
2154 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002155 4, true);
2156 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002157}
2158
2159/*
2160 struct objc_method {
2161 SEL method_name;
2162 char *method_types;
2163 void *method;
2164 };
2165
2166 struct objc_method_list {
2167 struct objc_method_list *obsolete;
2168 int count;
2169 struct objc_method methods_list[count];
2170 };
2171*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002172
2173/// GetMethodConstant - Return a struct objc_method constant for the
2174/// given method if it has been defined. The result is null if the
2175/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002176llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002177 // FIXME: Use DenseMap::lookup
2178 llvm::Function *Fn = MethodDefinitions[MD];
2179 if (!Fn)
2180 return 0;
2181
2182 std::vector<llvm::Constant*> Method(3);
2183 Method[0] =
2184 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2185 ObjCTypes.SelectorPtrTy);
2186 Method[1] = GetMethodVarType(MD);
2187 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2188 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2189}
2190
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002191llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2192 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002193 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002194 // Return null for empty list.
2195 if (Methods.empty())
2196 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2197
2198 std::vector<llvm::Constant*> Values(3);
2199 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2200 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2201 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2202 Methods.size());
2203 Values[2] = llvm::ConstantArray::get(AT, Methods);
2204 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2205
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002206 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002207 return llvm::ConstantExpr::getBitCast(GV,
2208 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002209}
2210
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002211llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002212 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002213 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002214 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002215
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002216 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002217 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002218 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002219 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002220 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002221 llvm::GlobalValue::InternalLinkage,
2222 Name,
2223 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002224 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002225
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002226 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002227}
2228
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002229/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002230uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2231 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002232 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002233 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002234 if (!OI)
2235 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002236 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002237}
2238
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002239llvm::GlobalVariable *
2240CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2241 llvm::Constant *Init,
2242 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002243 unsigned Align,
2244 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002245 const llvm::Type *Ty = Init->getType();
2246 llvm::GlobalVariable *GV =
2247 new llvm::GlobalVariable(Ty, false,
2248 llvm::GlobalValue::InternalLinkage,
2249 Init,
2250 Name,
2251 &CGM.getModule());
2252 if (Section)
2253 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002254 if (Align)
2255 GV->setAlignment(Align);
2256 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002257 UsedGlobals.push_back(GV);
2258 return GV;
2259}
2260
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002261llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002262 // Abuse this interface function as a place to finalize.
2263 FinishModule();
2264
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002265 return NULL;
2266}
2267
Chris Lattner74391b42009-03-22 21:03:39 +00002268llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002269 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002270}
2271
Chris Lattner74391b42009-03-22 21:03:39 +00002272llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002273 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002274}
2275
Chris Lattner74391b42009-03-22 21:03:39 +00002276llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002277 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002278}
2279
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002280/*
2281
2282Objective-C setjmp-longjmp (sjlj) Exception Handling
2283--
2284
2285The basic framework for a @try-catch-finally is as follows:
2286{
2287 objc_exception_data d;
2288 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002289 bool _call_try_exit = true;
2290
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002291 objc_exception_try_enter(&d);
2292 if (!setjmp(d.jmp_buf)) {
2293 ... try body ...
2294 } else {
2295 // exception path
2296 id _caught = objc_exception_extract(&d);
2297
2298 // enter new try scope for handlers
2299 if (!setjmp(d.jmp_buf)) {
2300 ... match exception and execute catch blocks ...
2301
2302 // fell off end, rethrow.
2303 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002304 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002305 } else {
2306 // exception in catch block
2307 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002308 _call_try_exit = false;
2309 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002310 }
2311 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002312 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002313
2314finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002315 if (_call_try_exit)
2316 objc_exception_try_exit(&d);
2317
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002318 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002319 ... dispatch to finally destination ...
2320
2321finally_rethrow:
2322 objc_exception_throw(_rethrow);
2323
2324finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002325}
2326
2327This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002328uses _rethrow to determine if objc_exception_try_exit should be called
2329and if the object should be rethrown. This breaks in the face of
2330throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002331
2332We specialize this framework for a few particular circumstances:
2333
2334 - If there are no catch blocks, then we avoid emitting the second
2335 exception handling context.
2336
2337 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2338 e)) we avoid emitting the code to rethrow an uncaught exception.
2339
2340 - FIXME: If there is no @finally block we can do a few more
2341 simplifications.
2342
2343Rethrows and Jumps-Through-Finally
2344--
2345
2346Support for implicit rethrows and jumping through the finally block is
2347handled by storing the current exception-handling context in
2348ObjCEHStack.
2349
Daniel Dunbar898d5082008-09-30 01:06:03 +00002350In order to implement proper @finally semantics, we support one basic
2351mechanism for jumping through the finally block to an arbitrary
2352destination. Constructs which generate exits from a @try or @catch
2353block use this mechanism to implement the proper semantics by chaining
2354jumps, as necessary.
2355
2356This mechanism works like the one used for indirect goto: we
2357arbitrarily assign an ID to each destination and store the ID for the
2358destination in a variable prior to entering the finally block. At the
2359end of the finally block we simply create a switch to the proper
2360destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002361
2362Code gen for @synchronized(expr) stmt;
2363Effectively generating code for:
2364objc_sync_enter(expr);
2365@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002366*/
2367
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002368void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2369 const Stmt &S) {
2370 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002371 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002372 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002373 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002374 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2375 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2376 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002377
2378 // For @synchronized, call objc_sync_enter(sync.expr). The
2379 // evaluation of the expression must occur before we enter the
2380 // @synchronized. We can safely avoid a temp here because jumps into
2381 // @synchronized are illegal & this will dominate uses.
2382 llvm::Value *SyncArg = 0;
2383 if (!isTry) {
2384 SyncArg =
2385 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2386 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002387 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002388 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002389
2390 // Push an EH context entry, used for handling rethrows and jumps
2391 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002392 CGF.PushCleanupBlock(FinallyBlock);
2393
Anders Carlsson273558f2009-02-07 21:37:21 +00002394 CGF.ObjCEHValueStack.push_back(0);
2395
Daniel Dunbar898d5082008-09-30 01:06:03 +00002396 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002397 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2398 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002399 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2400 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002401 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2402 "_call_try_exit");
2403 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2404
Anders Carlsson80f25672008-09-09 17:59:25 +00002405 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002406 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002407 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2408 "jmpbufarray");
2409 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002410 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002411 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002412
Daniel Dunbar55e87422008-11-11 02:29:29 +00002413 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2414 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002415 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002416 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002417
2418 // Emit the @try block.
2419 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002420 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2421 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002422 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002423
2424 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002425 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002426
2427 // Retrieve the exception object. We may emit multiple blocks but
2428 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002429 llvm::Value *Caught =
2430 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2431 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002432 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002433 if (!isTry)
2434 {
2435 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002436 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002437 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002438 }
2439 else if (const ObjCAtCatchStmt* CatchStmt =
2440 cast<ObjCAtTryStmt>(S).getCatchStmts())
2441 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002442 // Enter a new exception try block (in case a @catch block throws
2443 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002444 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002445
Chris Lattner34b02a12009-04-22 02:26:14 +00002446 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002447 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002448 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002449
Daniel Dunbar55e87422008-11-11 02:29:29 +00002450 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2451 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002452 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002453
2454 CGF.EmitBlock(CatchBlock);
2455
Daniel Dunbar55e40722008-09-27 07:03:52 +00002456 // Handle catch list. As a special case we check if everything is
2457 // matched and avoid generating code for falling off the end if
2458 // so.
2459 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002460 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002461 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002462
Steve Naroff7ba138a2009-03-03 19:52:17 +00002463 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002464 const PointerType *PT = 0;
2465
Anders Carlsson80f25672008-09-09 17:59:25 +00002466 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002467 if (!CatchParam) {
2468 AllMatched = true;
2469 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002470 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002471
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002472 // catch(id e) always matches.
2473 // FIXME: For the time being we also match id<X>; this should
2474 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002475 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002476 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002477 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002478 }
2479
Daniel Dunbar55e40722008-09-27 07:03:52 +00002480 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002481 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002482 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002483 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002484 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002485 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002486
Anders Carlssondde0a942008-09-11 09:15:33 +00002487 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002488 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002489 break;
2490 }
2491
Daniel Dunbar129271a2008-09-27 07:36:24 +00002492 assert(PT && "Unexpected non-pointer type in @catch");
2493 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002494 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002495 assert(ObjCType && "Catch parameter must have Objective-C type!");
2496
2497 // Check if the @catch block matches the exception object.
2498 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2499
Chris Lattner34b02a12009-04-22 02:26:14 +00002500 llvm::Value *Match =
2501 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2502 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002503
Daniel Dunbar55e87422008-11-11 02:29:29 +00002504 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002505
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002506 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002507 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002508
2509 // Emit the @catch block.
2510 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002511 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002512 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002513
2514 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002515 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002516 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002517 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002518
2519 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002520 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002521
2522 CGF.EmitBlock(NextCatchBlock);
2523 }
2524
Daniel Dunbar55e40722008-09-27 07:03:52 +00002525 if (!AllMatched) {
2526 // None of the handlers caught the exception, so store it to be
2527 // rethrown at the end of the @finally block.
2528 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002529 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002530 }
2531
2532 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002533 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002534 CGF.Builder.CreateStore(
2535 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2536 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002537 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002538 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002539 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002540 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002541 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002542 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002543 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002544 }
2545
Daniel Dunbar898d5082008-09-30 01:06:03 +00002546 // Pop the exception-handling stack entry. It is important to do
2547 // this now, because the code in the @finally block is not in this
2548 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002549 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2550
Anders Carlsson273558f2009-02-07 21:37:21 +00002551 CGF.ObjCEHValueStack.pop_back();
2552
Anders Carlsson80f25672008-09-09 17:59:25 +00002553 // Emit the @finally block.
2554 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002555 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2556
2557 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2558
2559 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002560 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002561
2562 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002563 if (isTry) {
2564 if (const ObjCAtFinallyStmt* FinallyStmt =
2565 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2566 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002567 } else {
2568 // Emit objc_sync_exit(expr); as finally's sole statement for
2569 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002570 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002571 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002572
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002573 // Emit the switch block
2574 if (Info.SwitchBlock)
2575 CGF.EmitBlock(Info.SwitchBlock);
2576 if (Info.EndBlock)
2577 CGF.EmitBlock(Info.EndBlock);
2578
Daniel Dunbar898d5082008-09-30 01:06:03 +00002579 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002580 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002581 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002582 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002583
2584 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002585}
2586
2587void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002588 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002589 llvm::Value *ExceptionAsObject;
2590
2591 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2592 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2593 ExceptionAsObject =
2594 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2595 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002596 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002597 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002598 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002599 }
2600
Chris Lattnerbbccd612009-04-22 02:38:11 +00002601 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002602 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002603
2604 // Clear the insertion point to indicate we are in unreachable code.
2605 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002606}
2607
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002608/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002609/// object: objc_read_weak (id *src)
2610///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002611llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002612 llvm::Value *AddrWeakObj)
2613{
Eli Friedman8339b352009-03-07 03:57:15 +00002614 const llvm::Type* DestTy =
2615 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002616 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002617 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002618 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002619 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002620 return read_weak;
2621}
2622
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002623/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2624/// objc_assign_weak (id src, id *dst)
2625///
2626void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2627 llvm::Value *src, llvm::Value *dst)
2628{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002629 const llvm::Type * SrcTy = src->getType();
2630 if (!isa<llvm::PointerType>(SrcTy)) {
2631 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2632 assert(Size <= 8 && "does not support size > 8");
2633 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2634 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002635 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2636 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002637 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2638 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002639 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002640 src, dst, "weakassign");
2641 return;
2642}
2643
Fariborz Jahanian58626502008-11-19 00:59:10 +00002644/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2645/// objc_assign_global (id src, id *dst)
2646///
2647void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2648 llvm::Value *src, llvm::Value *dst)
2649{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002650 const llvm::Type * SrcTy = src->getType();
2651 if (!isa<llvm::PointerType>(SrcTy)) {
2652 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2653 assert(Size <= 8 && "does not support size > 8");
2654 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2655 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002656 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2657 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002658 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2659 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002660 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002661 src, dst, "globalassign");
2662 return;
2663}
2664
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002665/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2666/// objc_assign_ivar (id src, id *dst)
2667///
2668void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2669 llvm::Value *src, llvm::Value *dst)
2670{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002671 const llvm::Type * SrcTy = src->getType();
2672 if (!isa<llvm::PointerType>(SrcTy)) {
2673 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2674 assert(Size <= 8 && "does not support size > 8");
2675 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2676 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002677 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2678 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002679 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2680 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002681 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002682 src, dst, "assignivar");
2683 return;
2684}
2685
Fariborz Jahanian58626502008-11-19 00:59:10 +00002686/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2687/// objc_assign_strongCast (id src, id *dst)
2688///
2689void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2690 llvm::Value *src, llvm::Value *dst)
2691{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002692 const llvm::Type * SrcTy = src->getType();
2693 if (!isa<llvm::PointerType>(SrcTy)) {
2694 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2695 assert(Size <= 8 && "does not support size > 8");
2696 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2697 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002698 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2699 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002700 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2701 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002702 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002703 src, dst, "weakassign");
2704 return;
2705}
2706
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002707/// EmitObjCValueForIvar - Code Gen for ivar reference.
2708///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002709LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2710 QualType ObjectTy,
2711 llvm::Value *BaseValue,
2712 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002713 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002714 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002715 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2716 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002717}
2718
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002719llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002720 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002721 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002722 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002723 return llvm::ConstantInt::get(
2724 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2725 Offset);
2726}
2727
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002728/* *** Private Interface *** */
2729
2730/// EmitImageInfo - Emit the image info marker used to encode some module
2731/// level information.
2732///
2733/// See: <rdr://4810609&4810587&4810587>
2734/// struct IMAGE_INFO {
2735/// unsigned version;
2736/// unsigned flags;
2737/// };
2738enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002739 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2740 // this implies.
2741 eImageInfo_GarbageCollected = (1 << 1),
2742 eImageInfo_GCOnly = (1 << 2),
2743 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2744
2745 // A flag indicating that the module has no instances of an
2746 // @synthesize of a superclass variable. <rdar://problem/6803242>
2747 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002748};
2749
2750void CGObjCMac::EmitImageInfo() {
2751 unsigned version = 0; // Version is unused?
2752 unsigned flags = 0;
2753
2754 // FIXME: Fix and continue?
2755 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2756 flags |= eImageInfo_GarbageCollected;
2757 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2758 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002759
2760 // We never allow @synthesize of a superclass property.
2761 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002762
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002763 // Emitted as int[2];
2764 llvm::Constant *values[2] = {
2765 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2766 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2767 };
2768 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002769
2770 const char *Section;
2771 if (ObjCABI == 1)
2772 Section = "__OBJC, __image_info,regular";
2773 else
2774 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002775 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002776 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2777 llvm::ConstantArray::get(AT, values, 2),
2778 Section,
2779 0,
2780 true);
2781 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002782}
2783
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002784
2785// struct objc_module {
2786// unsigned long version;
2787// unsigned long size;
2788// const char *name;
2789// Symtab symtab;
2790// };
2791
2792// FIXME: Get from somewhere
2793static const int ModuleVersion = 7;
2794
2795void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002796 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002797
2798 std::vector<llvm::Constant*> Values(4);
2799 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2800 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002801 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002802 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002803 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002804 CreateMetadataVar("\01L_OBJC_MODULES",
2805 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2806 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002807 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002808}
2809
2810llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002811 unsigned NumClasses = DefinedClasses.size();
2812 unsigned NumCategories = DefinedCategories.size();
2813
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002814 // Return null if no symbols were defined.
2815 if (!NumClasses && !NumCategories)
2816 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2817
2818 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002819 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2820 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2821 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2822 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2823
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002824 // The runtime expects exactly the list of defined classes followed
2825 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002826 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002827 for (unsigned i=0; i<NumClasses; i++)
2828 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2829 ObjCTypes.Int8PtrTy);
2830 for (unsigned i=0; i<NumCategories; i++)
2831 Symbols[NumClasses + i] =
2832 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2833 ObjCTypes.Int8PtrTy);
2834
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002835 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002836 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002837 NumClasses + NumCategories),
2838 Symbols);
2839
2840 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2841
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002842 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002843 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2844 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002845 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002846 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2847}
2848
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002849llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002850 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002851 LazySymbols.insert(ID->getIdentifier());
2852
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002853 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2854
2855 if (!Entry) {
2856 llvm::Constant *Casted =
2857 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2858 ObjCTypes.ClassPtrTy);
2859 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002860 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2861 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002862 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002863 }
2864
2865 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002866}
2867
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002868llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002869 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2870
2871 if (!Entry) {
2872 llvm::Constant *Casted =
2873 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2874 ObjCTypes.SelectorPtrTy);
2875 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002876 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2877 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002878 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002879 }
2880
2881 return Builder.CreateLoad(Entry, false, "tmp");
2882}
2883
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002884llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002885 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002886
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002887 if (!Entry)
2888 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2889 llvm::ConstantArray::get(Ident->getName()),
2890 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002891 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002892
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002893 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002894}
2895
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002896/// GetIvarLayoutName - Returns a unique constant for the given
2897/// ivar layout bitmap.
2898llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2899 const ObjCCommonTypesHelper &ObjCTypes) {
2900 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2901}
2902
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002903void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2904 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002905 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002906 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002907 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002908 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002909 bool IsUnion = (RD && RD->isUnion());
2910 uint64_t MaxUnionIvarSize = 0;
2911 uint64_t MaxSkippedUnionIvarSize = 0;
2912 FieldDecl *MaxField = 0;
2913 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002914 FieldDecl *LastFieldBitfield = 0;
2915
Chris Lattnerf1690852009-03-31 08:48:01 +00002916 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002917 if (RecFields.empty())
2918 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002919 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002920 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002921 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2922 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2923
2924 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2925
2926 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002927 FieldDecl *Field = RecFields[i];
2928 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002929 if (!Field->getIdentifier() || Field->isBitField()) {
2930 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002931 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002932 }
2933 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002934 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002935 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002936 if (FQT->isUnionType())
2937 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002938 else
2939 assert(FQT->isRecordType() &&
2940 "only union/record is supported for ivar layout bitmap");
2941
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002942 const RecordType *RT = FQT->getAsRecordType();
2943 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002944 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002945 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2946 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002947 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2948 const llvm::StructLayout *RecLayout =
2949 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2950
2951 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002952 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002953 ForStrongLayout, HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002954 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002955 continue;
2956 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002957
2958 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002959 const ConstantArrayType *CArray =
2960 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002961 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002962 assert(CArray && "only array with know element size is supported");
2963 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002964 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2965 const ConstantArrayType *CArray =
2966 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002967 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002968 FQT = CArray->getElementType();
2969 }
2970
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002971 assert(!FQT->isUnionType() &&
2972 "layout for array of unions not supported");
2973 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002974 int OldIndex = IvarsInfo.size() - 1;
2975 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002976
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002977 // FIXME - Use a common routine with the above!
2978 const RecordType *RT = FQT->getAsRecordType();
2979 const RecordDecl *RD = RT->getDecl();
2980 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002981 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2982 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002983 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2984 const llvm::StructLayout *RecLayout =
2985 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002986
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002987 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002988 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002989 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002990 ForStrongLayout, HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002991 TmpRecFields.clear();
2992
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002993 // Replicate layout information for each array element. Note that
2994 // one element is already done.
2995 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002996 for (int FirstIndex = IvarsInfo.size() - 1,
2997 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002998 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002999 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3000 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003001 GC_IVAR gcivar;
3002 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3003 gcivar.ivar_size = IvarsInfo[i].ivar_size;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003004 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003005 }
3006
Chris Lattnerf1690852009-03-31 08:48:01 +00003007 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003008 GC_IVAR skivar;
3009 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3010 skivar.ivar_size = SkipIvars[i].ivar_size;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003011 SkipIvars.push_back(skivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003012 }
3013 }
3014 continue;
3015 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003016 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003017 // At this point, we are done with Record/Union and array there of.
3018 // For other arrays we are down to its element type.
3019 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3020 do {
3021 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3022 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3023 break;
3024 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003025 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003026 GCAttr = QualType::Strong;
3027 break;
3028 }
3029 else if (const PointerType *PT = FQT->getAsPointerType()) {
3030 FQT = PT->getPointeeType();
3031 }
3032 else {
3033 break;
3034 }
3035 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003036
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003037 if ((ForStrongLayout && GCAttr == QualType::Strong)
3038 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3039 if (IsUnion)
3040 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003041 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3042 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003043 if (UnionIvarSize > MaxUnionIvarSize)
3044 {
3045 MaxUnionIvarSize = UnionIvarSize;
3046 MaxField = Field;
3047 }
3048 }
3049 else
3050 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003051 GC_IVAR gcivar;
3052 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3053 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3054 WordSizeInBits;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003055 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003056 }
3057 }
3058 else if ((ForStrongLayout &&
3059 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3060 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3061 if (IsUnion)
3062 {
3063 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3064 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3065 {
3066 MaxSkippedUnionIvarSize = UnionIvarSize;
3067 MaxSkippedField = Field;
3068 }
3069 }
3070 else
3071 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003072 GC_IVAR skivar;
3073 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3074 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003075 ByteSizeInBits;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003076 SkipIvars.push_back(skivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003077 }
3078 }
3079 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003080 if (LastFieldBitfield) {
3081 // Last field was a bitfield. Must update skip info.
3082 GC_IVAR skivar;
3083 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3084 LastFieldBitfield);
3085 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3086 uint64_t BitFieldSize =
3087 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3088 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3089 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003090 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003091 }
3092
Chris Lattnerf1690852009-03-31 08:48:01 +00003093 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003094 GC_IVAR gcivar;
3095 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3096 gcivar.ivar_size = MaxUnionIvarSize;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003097 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003098 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003099
3100 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003101 GC_IVAR skivar;
3102 skivar.ivar_bytepos = BytePos +
3103 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3104 skivar.ivar_size = MaxSkippedUnionIvarSize;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003105 SkipIvars.push_back(skivar);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003106 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003107}
3108
3109/// BuildIvarLayout - Builds ivar layout bitmap for the class
3110/// implementation for the __strong or __weak case.
3111/// The layout map displays which words in ivar list must be skipped
3112/// and which must be scanned by GC (see below). String is built of bytes.
3113/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3114/// of words to skip and right nibble is count of words to scan. So, each
3115/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3116/// represented by a 0x00 byte which also ends the string.
3117/// 1. when ForStrongLayout is true, following ivars are scanned:
3118/// - id, Class
3119/// - object *
3120/// - __strong anything
3121///
3122/// 2. When ForStrongLayout is false, following ivars are scanned:
3123/// - __weak anything
3124///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003125llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003126 const ObjCImplementationDecl *OMD,
3127 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003128 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003129
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003130 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003131 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3132 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3133 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003134
Chris Lattnerf1690852009-03-31 08:48:01 +00003135 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003136 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003137 CGM.getContext().CollectObjCIvars(OI, RecFields);
3138 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003139 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003140
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003141 SkipIvars.clear();
3142 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003143
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00003144 const llvm::StructLayout *Layout =
3145 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003146 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, hasUnion);
3147 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003148 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003149
3150 // Sort on byte position in case we encounterred a union nested in
3151 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003152 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003153 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003154 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003155 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003156
3157 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003158 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003159 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003160 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003161 if (IvarsInfo[0].ivar_bytepos == 0) {
3162 WordsToSkip = 0;
3163 WordsToScan = IvarsInfo[0].ivar_size;
3164 }
3165 else {
3166 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3167 WordsToScan = IvarsInfo[0].ivar_size;
3168 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003169 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003170 {
3171 unsigned int TailPrevGCObjC =
3172 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3173 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3174 {
3175 // consecutive 'scanned' object pointers.
3176 WordsToScan += IvarsInfo[i].ivar_size;
3177 }
3178 else
3179 {
3180 // Skip over 'gc'able object pointer which lay over each other.
3181 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3182 continue;
3183 // Must skip over 1 or more words. We save current skip/scan values
3184 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003185 SKIP_SCAN SkScan;
3186 SkScan.skip = WordsToSkip;
3187 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003188 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003189
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003190 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003191 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3192 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003193 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003194 WordsToSkip = 0;
3195 WordsToScan = IvarsInfo[i].ivar_size;
3196 }
3197 }
3198 if (WordsToScan > 0)
3199 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003200 SKIP_SCAN SkScan;
3201 SkScan.skip = WordsToSkip;
3202 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003203 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003204 }
3205
3206 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003207 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003209 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003210 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003211 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3212 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003213 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003214 IvarsInfo[LastIndex].ivar_bytepos +
3215 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003216 BytesSkipped = (LastByteSkipped > LastByteScanned);
3217 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3218 if (BytesSkipped)
3219 {
3220 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003221 SKIP_SCAN SkScan;
3222 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3223 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003224 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003225 }
3226 }
3227 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3228 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003229 int SkipScan = SkipScanIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003230 for (int i = 0; i <= SkipScan; i++)
3231 {
3232 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3233 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3234 // 0xM0 followed by 0x0N detected.
3235 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3236 for (int j = i+1; j < SkipScan; j++)
3237 SkipScanIvars[j] = SkipScanIvars[j+1];
3238 --SkipScan;
3239 }
3240 }
3241
3242 // Generate the string.
3243 std::string BitMap;
3244 for (int i = 0; i <= SkipScan; i++)
3245 {
3246 unsigned char byte;
3247 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3248 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3249 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3250 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3251
3252 if (skip_small > 0 || skip_big > 0)
3253 BytesSkipped = true;
3254 // first skip big.
3255 for (unsigned int ix = 0; ix < skip_big; ix++)
3256 BitMap += (unsigned char)(0xf0);
3257
3258 // next (skip small, scan)
3259 if (skip_small)
3260 {
3261 byte = skip_small << 4;
3262 if (scan_big > 0)
3263 {
3264 byte |= 0xf;
3265 --scan_big;
3266 }
3267 else if (scan_small)
3268 {
3269 byte |= scan_small;
3270 scan_small = 0;
3271 }
3272 BitMap += byte;
3273 }
3274 // next scan big
3275 for (unsigned int ix = 0; ix < scan_big; ix++)
3276 BitMap += (unsigned char)(0x0f);
3277 // last scan small
3278 if (scan_small)
3279 {
3280 byte = scan_small;
3281 BitMap += byte;
3282 }
3283 }
3284 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003285 unsigned char zero = 0;
3286 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003287
3288 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3289 printf("\n%s ivar layout for class '%s': ",
3290 ForStrongLayout ? "strong" : "weak",
3291 OMD->getClassInterface()->getNameAsCString());
3292 const unsigned char *s = (unsigned char*)BitMap.c_str();
3293 for (unsigned i = 0; i < BitMap.size(); i++)
3294 if (!(s[i] & 0xf0))
3295 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3296 else
3297 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3298 printf("\n");
3299 }
3300
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003301 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3302 // final layout.
3303 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003304 return llvm::Constant::getNullValue(PtrTy);
3305 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3306 llvm::ConstantArray::get(BitMap.c_str()),
3307 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003308 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003309 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003310}
3311
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003312llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003313 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3314
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003315 // FIXME: Avoid std::string copying.
3316 if (!Entry)
3317 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3318 llvm::ConstantArray::get(Sel.getAsString()),
3319 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003320 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003321
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003322 return getConstantGEP(Entry, 0, 0);
3323}
3324
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003325// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003326llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003327 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3328}
3329
3330// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003331llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003332 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3333}
3334
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003335llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003336 std::string TypeStr;
3337 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3338
3339 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003340
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003341 if (!Entry)
3342 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3343 llvm::ConstantArray::get(TypeStr),
3344 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003345 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003346
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003348}
3349
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003350llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003351 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003352 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3353 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003354
3355 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3356
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003357 if (!Entry)
3358 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3359 llvm::ConstantArray::get(TypeStr),
3360 "__TEXT,__cstring,cstring_literals",
3361 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003362
3363 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003364}
3365
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003366// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003367llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003368 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3369
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003370 if (!Entry)
3371 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3372 llvm::ConstantArray::get(Ident->getName()),
3373 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003374 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003375
3376 return getConstantGEP(Entry, 0, 0);
3377}
3378
3379// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003380// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003381llvm::Constant *
3382 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3383 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003384 std::string TypeStr;
3385 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003386 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3387}
3388
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003389void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3390 const ObjCContainerDecl *CD,
3391 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003392 NameOut = '\01';
3393 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003394 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003395 assert (CD && "Missing container decl in GetNameForMethod");
3396 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003397 if (const ObjCCategoryImplDecl *CID =
3398 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3399 NameOut += '(';
3400 NameOut += CID->getNameAsString();
3401 NameOut+= ')';
3402 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003403 NameOut += ' ';
3404 NameOut += D->getSelector().getAsString();
3405 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003406}
3407
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003408void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003409 EmitModuleInfo();
3410
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003411 // Emit the dummy bodies for any protocols which were referenced but
3412 // never defined.
3413 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3414 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3415 if (i->second->hasInitializer())
3416 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003417
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003418 std::vector<llvm::Constant*> Values(5);
3419 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3420 Values[1] = GetClassName(i->first);
3421 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3422 Values[3] = Values[4] =
3423 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3424 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3425 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3426 Values));
3427 }
3428
3429 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003430 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003431 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003432 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003433 }
3434
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003435 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003436 llvm::GlobalValue *GV =
3437 new llvm::GlobalVariable(AT, false,
3438 llvm::GlobalValue::AppendingLinkage,
3439 llvm::ConstantArray::get(AT, Used),
3440 "llvm.used",
3441 &CGM.getModule());
3442
3443 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003444
3445 // Add assembler directives to add lazy undefined symbol references
3446 // for classes which are referenced but not defined. This is
3447 // important for correct linker interaction.
3448
3449 // FIXME: Uh, this isn't particularly portable.
3450 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003451
3452 if (!CGM.getModule().getModuleInlineAsm().empty())
3453 s << "\n";
3454
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003455 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3456 e = LazySymbols.end(); i != e; ++i) {
3457 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3458 }
3459 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3460 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003461 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003462 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3463 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003464
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003465 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003466}
3467
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003468CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003469 : CGObjCCommonMac(cgm),
3470 ObjCTypes(cgm)
3471{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003472 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003473 ObjCABI = 2;
3474}
3475
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003476/* *** */
3477
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003478ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3479: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003480{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003481 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3482 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003483
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003484 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003485 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003486 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003487 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003488 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3489
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003490 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003491 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003492 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003493
3494 // FIXME: It would be nice to unify this with the opaque type, so
3495 // that the IR comes out a bit cleaner.
3496 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3497 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003498
3499 // I'm not sure I like this. The implicit coordination is a bit
3500 // gross. We should solve this in a reasonable fashion because this
3501 // is a pretty common task (match some runtime data structure with
3502 // an LLVM data structure).
3503
3504 // FIXME: This is leaked.
3505 // FIXME: Merge with rewriter code?
3506
3507 // struct _objc_super {
3508 // id self;
3509 // Class cls;
3510 // }
3511 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3512 SourceLocation(),
3513 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003514 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3515 Ctx.getObjCIdType(), 0, false));
3516 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3517 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003518 RD->completeDefinition(Ctx);
3519
3520 SuperCTy = Ctx.getTagDeclType(RD);
3521 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3522
3523 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003524 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3525
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003526 // struct _prop_t {
3527 // char *name;
3528 // char *attributes;
3529 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003530 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003531 CGM.getModule().addTypeName("struct._prop_t",
3532 PropertyTy);
3533
3534 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003535 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003536 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003537 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003538 // }
3539 PropertyListTy = llvm::StructType::get(IntTy,
3540 IntTy,
3541 llvm::ArrayType::get(PropertyTy, 0),
3542 NULL);
3543 CGM.getModule().addTypeName("struct._prop_list_t",
3544 PropertyListTy);
3545 // struct _prop_list_t *
3546 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3547
3548 // struct _objc_method {
3549 // SEL _cmd;
3550 // char *method_type;
3551 // char *_imp;
3552 // }
3553 MethodTy = llvm::StructType::get(SelectorPtrTy,
3554 Int8PtrTy,
3555 Int8PtrTy,
3556 NULL);
3557 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003558
3559 // struct _objc_cache *
3560 CacheTy = llvm::OpaqueType::get();
3561 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3562 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003563}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003564
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003565ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3566 : ObjCCommonTypesHelper(cgm)
3567{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003568 // struct _objc_method_description {
3569 // SEL name;
3570 // char *types;
3571 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003572 MethodDescriptionTy =
3573 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003574 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003575 NULL);
3576 CGM.getModule().addTypeName("struct._objc_method_description",
3577 MethodDescriptionTy);
3578
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003579 // struct _objc_method_description_list {
3580 // int count;
3581 // struct _objc_method_description[1];
3582 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003583 MethodDescriptionListTy =
3584 llvm::StructType::get(IntTy,
3585 llvm::ArrayType::get(MethodDescriptionTy, 0),
3586 NULL);
3587 CGM.getModule().addTypeName("struct._objc_method_description_list",
3588 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003589
3590 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003591 MethodDescriptionListPtrTy =
3592 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3593
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003594 // Protocol description structures
3595
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003596 // struct _objc_protocol_extension {
3597 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3598 // struct _objc_method_description_list *optional_instance_methods;
3599 // struct _objc_method_description_list *optional_class_methods;
3600 // struct _objc_property_list *instance_properties;
3601 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003602 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003603 llvm::StructType::get(IntTy,
3604 MethodDescriptionListPtrTy,
3605 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003606 PropertyListPtrTy,
3607 NULL);
3608 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3609 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003610
3611 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003612 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3613
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003614 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003615
3616 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3617 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3618
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003619 const llvm::Type *T =
3620 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3621 LongTy,
3622 llvm::ArrayType::get(ProtocolTyHolder, 0),
3623 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003624 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3625
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003626 // struct _objc_protocol {
3627 // struct _objc_protocol_extension *isa;
3628 // char *protocol_name;
3629 // struct _objc_protocol **_objc_protocol_list;
3630 // struct _objc_method_description_list *instance_methods;
3631 // struct _objc_method_description_list *class_methods;
3632 // }
3633 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003634 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003635 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3636 MethodDescriptionListPtrTy,
3637 MethodDescriptionListPtrTy,
3638 NULL);
3639 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3640
3641 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3642 CGM.getModule().addTypeName("struct._objc_protocol_list",
3643 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003644 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003645 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3646
3647 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003648 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003649 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003650
3651 // Class description structures
3652
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003653 // struct _objc_ivar {
3654 // char *ivar_name;
3655 // char *ivar_type;
3656 // int ivar_offset;
3657 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003658 IvarTy = llvm::StructType::get(Int8PtrTy,
3659 Int8PtrTy,
3660 IntTy,
3661 NULL);
3662 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3663
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003664 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003665 IvarListTy = llvm::OpaqueType::get();
3666 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3667 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3668
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003669 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003670 MethodListTy = llvm::OpaqueType::get();
3671 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3672 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3673
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003674 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003675 ClassExtensionTy =
3676 llvm::StructType::get(IntTy,
3677 Int8PtrTy,
3678 PropertyListPtrTy,
3679 NULL);
3680 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3681 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3682
3683 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3684
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003685 // struct _objc_class {
3686 // Class isa;
3687 // Class super_class;
3688 // char *name;
3689 // long version;
3690 // long info;
3691 // long instance_size;
3692 // struct _objc_ivar_list *ivars;
3693 // struct _objc_method_list *methods;
3694 // struct _objc_cache *cache;
3695 // struct _objc_protocol_list *protocols;
3696 // char *ivar_layout;
3697 // struct _objc_class_ext *ext;
3698 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003699 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3700 llvm::PointerType::getUnqual(ClassTyHolder),
3701 Int8PtrTy,
3702 LongTy,
3703 LongTy,
3704 LongTy,
3705 IvarListPtrTy,
3706 MethodListPtrTy,
3707 CachePtrTy,
3708 ProtocolListPtrTy,
3709 Int8PtrTy,
3710 ClassExtensionPtrTy,
3711 NULL);
3712 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3713
3714 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3715 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3716 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3717
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003718 // struct _objc_category {
3719 // char *category_name;
3720 // char *class_name;
3721 // struct _objc_method_list *instance_method;
3722 // struct _objc_method_list *class_method;
3723 // uint32_t size; // sizeof(struct _objc_category)
3724 // struct _objc_property_list *instance_properties;// category's @property
3725 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003726 CategoryTy = llvm::StructType::get(Int8PtrTy,
3727 Int8PtrTy,
3728 MethodListPtrTy,
3729 MethodListPtrTy,
3730 ProtocolListPtrTy,
3731 IntTy,
3732 PropertyListPtrTy,
3733 NULL);
3734 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3735
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003736 // Global metadata structures
3737
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003738 // struct _objc_symtab {
3739 // long sel_ref_cnt;
3740 // SEL *refs;
3741 // short cls_def_cnt;
3742 // short cat_def_cnt;
3743 // char *defs[cls_def_cnt + cat_def_cnt];
3744 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003745 SymtabTy = llvm::StructType::get(LongTy,
3746 SelectorPtrTy,
3747 ShortTy,
3748 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003749 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003750 NULL);
3751 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3752 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3753
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003754 // struct _objc_module {
3755 // long version;
3756 // long size; // sizeof(struct _objc_module)
3757 // char *name;
3758 // struct _objc_symtab* symtab;
3759 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003760 ModuleTy =
3761 llvm::StructType::get(LongTy,
3762 LongTy,
3763 Int8PtrTy,
3764 SymtabPtrTy,
3765 NULL);
3766 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003767
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003768
Anders Carlsson124526b2008-09-09 10:10:21 +00003769 // FIXME: This is the size of the setjmp buffer and should be
3770 // target specific. 18 is what's used on 32-bit X86.
3771 uint64_t SetJmpBufferSize = 18;
3772
3773 // Exceptions
3774 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003775 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003776
3777 ExceptionDataTy =
3778 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3779 SetJmpBufferSize),
3780 StackPtrTy, NULL);
3781 CGM.getModule().addTypeName("struct._objc_exception_data",
3782 ExceptionDataTy);
3783
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003784}
3785
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003786ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003787: ObjCCommonTypesHelper(cgm)
3788{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003789 // struct _method_list_t {
3790 // uint32_t entsize; // sizeof(struct _objc_method)
3791 // uint32_t method_count;
3792 // struct _objc_method method_list[method_count];
3793 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003794 MethodListnfABITy = llvm::StructType::get(IntTy,
3795 IntTy,
3796 llvm::ArrayType::get(MethodTy, 0),
3797 NULL);
3798 CGM.getModule().addTypeName("struct.__method_list_t",
3799 MethodListnfABITy);
3800 // struct method_list_t *
3801 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003802
3803 // struct _protocol_t {
3804 // id isa; // NULL
3805 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003806 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003807 // const struct method_list_t * const instance_methods;
3808 // const struct method_list_t * const class_methods;
3809 // const struct method_list_t *optionalInstanceMethods;
3810 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003811 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003812 // const uint32_t size; // sizeof(struct _protocol_t)
3813 // const uint32_t flags; // = 0
3814 // }
3815
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003816 // Holder for struct _protocol_list_t *
3817 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3818
3819 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3820 Int8PtrTy,
3821 llvm::PointerType::getUnqual(
3822 ProtocolListTyHolder),
3823 MethodListnfABIPtrTy,
3824 MethodListnfABIPtrTy,
3825 MethodListnfABIPtrTy,
3826 MethodListnfABIPtrTy,
3827 PropertyListPtrTy,
3828 IntTy,
3829 IntTy,
3830 NULL);
3831 CGM.getModule().addTypeName("struct._protocol_t",
3832 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003833
3834 // struct _protocol_t*
3835 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003836
Fariborz Jahanianda320092009-01-29 19:24:30 +00003837 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003838 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003839 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003840 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003841 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3842 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003843 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003844 NULL);
3845 CGM.getModule().addTypeName("struct._objc_protocol_list",
3846 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003847 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3848 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003849
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003850 // struct _objc_protocol_list*
3851 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003852
3853 // struct _ivar_t {
3854 // unsigned long int *offset; // pointer to ivar offset location
3855 // char *name;
3856 // char *type;
3857 // uint32_t alignment;
3858 // uint32_t size;
3859 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003860 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3861 Int8PtrTy,
3862 Int8PtrTy,
3863 IntTy,
3864 IntTy,
3865 NULL);
3866 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3867
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003868 // struct _ivar_list_t {
3869 // uint32 entsize; // sizeof(struct _ivar_t)
3870 // uint32 count;
3871 // struct _iver_t list[count];
3872 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003873 IvarListnfABITy = llvm::StructType::get(IntTy,
3874 IntTy,
3875 llvm::ArrayType::get(
3876 IvarnfABITy, 0),
3877 NULL);
3878 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3879
3880 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003881
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003882 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003883 // uint32_t const flags;
3884 // uint32_t const instanceStart;
3885 // uint32_t const instanceSize;
3886 // uint32_t const reserved; // only when building for 64bit targets
3887 // const uint8_t * const ivarLayout;
3888 // const char *const name;
3889 // const struct _method_list_t * const baseMethods;
3890 // const struct _objc_protocol_list *const baseProtocols;
3891 // const struct _ivar_list_t *const ivars;
3892 // const uint8_t * const weakIvarLayout;
3893 // const struct _prop_list_t * const properties;
3894 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003895
3896 // FIXME. Add 'reserved' field in 64bit abi mode!
3897 ClassRonfABITy = llvm::StructType::get(IntTy,
3898 IntTy,
3899 IntTy,
3900 Int8PtrTy,
3901 Int8PtrTy,
3902 MethodListnfABIPtrTy,
3903 ProtocolListnfABIPtrTy,
3904 IvarListnfABIPtrTy,
3905 Int8PtrTy,
3906 PropertyListPtrTy,
3907 NULL);
3908 CGM.getModule().addTypeName("struct._class_ro_t",
3909 ClassRonfABITy);
3910
3911 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3912 std::vector<const llvm::Type*> Params;
3913 Params.push_back(ObjectPtrTy);
3914 Params.push_back(SelectorPtrTy);
3915 ImpnfABITy = llvm::PointerType::getUnqual(
3916 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3917
3918 // struct _class_t {
3919 // struct _class_t *isa;
3920 // struct _class_t * const superclass;
3921 // void *cache;
3922 // IMP *vtable;
3923 // struct class_ro_t *ro;
3924 // }
3925
3926 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3927 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3928 llvm::PointerType::getUnqual(ClassTyHolder),
3929 CachePtrTy,
3930 llvm::PointerType::getUnqual(ImpnfABITy),
3931 llvm::PointerType::getUnqual(
3932 ClassRonfABITy),
3933 NULL);
3934 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3935
3936 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3937 ClassnfABITy);
3938
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003939 // LLVM for struct _class_t *
3940 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3941
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003942 // struct _category_t {
3943 // const char * const name;
3944 // struct _class_t *const cls;
3945 // const struct _method_list_t * const instance_methods;
3946 // const struct _method_list_t * const class_methods;
3947 // const struct _protocol_list_t * const protocols;
3948 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003949 // }
3950 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003951 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003952 MethodListnfABIPtrTy,
3953 MethodListnfABIPtrTy,
3954 ProtocolListnfABIPtrTy,
3955 PropertyListPtrTy,
3956 NULL);
3957 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003958
3959 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003960 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3961 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003962
3963 // MessageRefTy - LLVM for:
3964 // struct _message_ref_t {
3965 // IMP messenger;
3966 // SEL name;
3967 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003968
3969 // First the clang type for struct _message_ref_t
3970 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3971 SourceLocation(),
3972 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003973 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3974 Ctx.VoidPtrTy, 0, false));
3975 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3976 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003977 RD->completeDefinition(Ctx);
3978
3979 MessageRefCTy = Ctx.getTagDeclType(RD);
3980 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3981 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003982
3983 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3984 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3985
3986 // SuperMessageRefTy - LLVM for:
3987 // struct _super_message_ref_t {
3988 // SUPER_IMP messenger;
3989 // SEL name;
3990 // };
3991 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3992 SelectorPtrTy,
3993 NULL);
3994 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3995
3996 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3997 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3998
Daniel Dunbare588b992009-03-01 04:46:24 +00003999
4000 // struct objc_typeinfo {
4001 // const void** vtable; // objc_ehtype_vtable + 2
4002 // const char* name; // c++ typeinfo string
4003 // Class cls;
4004 // };
4005 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4006 Int8PtrTy,
4007 ClassnfABIPtrTy,
4008 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004009 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004010 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004011}
4012
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004013llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4014 FinishNonFragileABIModule();
4015
4016 return NULL;
4017}
4018
4019void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4020 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004021
4022 // Build list of all implemented classe addresses in array
4023 // L_OBJC_LABEL_CLASS_$.
4024 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4025 // list of 'nonlazy' implementations (defined as those with a +load{}
4026 // method!!).
4027 unsigned NumClasses = DefinedClasses.size();
4028 if (NumClasses) {
4029 std::vector<llvm::Constant*> Symbols(NumClasses);
4030 for (unsigned i=0; i<NumClasses; i++)
4031 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4032 ObjCTypes.Int8PtrTy);
4033 llvm::Constant* Init =
4034 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4035 NumClasses),
4036 Symbols);
4037
4038 llvm::GlobalVariable *GV =
4039 new llvm::GlobalVariable(Init->getType(), false,
4040 llvm::GlobalValue::InternalLinkage,
4041 Init,
4042 "\01L_OBJC_LABEL_CLASS_$",
4043 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004044 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004045 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4046 UsedGlobals.push_back(GV);
4047 }
4048
4049 // Build list of all implemented category addresses in array
4050 // L_OBJC_LABEL_CATEGORY_$.
4051 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4052 // list of 'nonlazy' category implementations (defined as those with a +load{}
4053 // method!!).
4054 unsigned NumCategory = DefinedCategories.size();
4055 if (NumCategory) {
4056 std::vector<llvm::Constant*> Symbols(NumCategory);
4057 for (unsigned i=0; i<NumCategory; i++)
4058 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4059 ObjCTypes.Int8PtrTy);
4060 llvm::Constant* Init =
4061 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4062 NumCategory),
4063 Symbols);
4064
4065 llvm::GlobalVariable *GV =
4066 new llvm::GlobalVariable(Init->getType(), false,
4067 llvm::GlobalValue::InternalLinkage,
4068 Init,
4069 "\01L_OBJC_LABEL_CATEGORY_$",
4070 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004071 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004072 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4073 UsedGlobals.push_back(GV);
4074 }
4075
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004076 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4077 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4078 std::vector<llvm::Constant*> Values(2);
4079 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004080 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004081 // FIXME: Fix and continue?
4082 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4083 flags |= eImageInfo_GarbageCollected;
4084 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4085 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004086 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004087 llvm::Constant* Init = llvm::ConstantArray::get(
4088 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4089 Values);
4090 llvm::GlobalVariable *IMGV =
4091 new llvm::GlobalVariable(Init->getType(), false,
4092 llvm::GlobalValue::InternalLinkage,
4093 Init,
4094 "\01L_OBJC_IMAGE_INFO",
4095 &CGM.getModule());
4096 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004097 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004098 UsedGlobals.push_back(IMGV);
4099
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004100 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004101
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004102 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4103 e = UsedGlobals.end(); i != e; ++i) {
4104 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4105 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004106
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004107 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4108 llvm::GlobalValue *GV =
4109 new llvm::GlobalVariable(AT, false,
4110 llvm::GlobalValue::AppendingLinkage,
4111 llvm::ConstantArray::get(AT, Used),
4112 "llvm.used",
4113 &CGM.getModule());
4114
4115 GV->setSection("llvm.metadata");
4116
4117}
4118
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004119// Metadata flags
4120enum MetaDataDlags {
4121 CLS = 0x0,
4122 CLS_META = 0x1,
4123 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004124 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004125 CLS_EXCEPTION = 0x20
4126};
4127/// BuildClassRoTInitializer - generate meta-data for:
4128/// struct _class_ro_t {
4129/// uint32_t const flags;
4130/// uint32_t const instanceStart;
4131/// uint32_t const instanceSize;
4132/// uint32_t const reserved; // only when building for 64bit targets
4133/// const uint8_t * const ivarLayout;
4134/// const char *const name;
4135/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004136/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004137/// const struct _ivar_list_t *const ivars;
4138/// const uint8_t * const weakIvarLayout;
4139/// const struct _prop_list_t * const properties;
4140/// }
4141///
4142llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4143 unsigned flags,
4144 unsigned InstanceStart,
4145 unsigned InstanceSize,
4146 const ObjCImplementationDecl *ID) {
4147 std::string ClassName = ID->getNameAsString();
4148 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4149 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4150 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4151 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4152 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004153 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4154 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004155 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004156 // const struct _method_list_t * const baseMethods;
4157 std::vector<llvm::Constant*> Methods;
4158 std::string MethodListName("\01l_OBJC_$_");
4159 if (flags & CLS_META) {
4160 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004161 for (ObjCImplementationDecl::classmeth_iterator
4162 i = ID->classmeth_begin(CGM.getContext()),
4163 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004164 // Class methods should always be defined.
4165 Methods.push_back(GetMethodConstant(*i));
4166 }
4167 } else {
4168 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004169 for (ObjCImplementationDecl::instmeth_iterator
4170 i = ID->instmeth_begin(CGM.getContext()),
4171 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004172 // Instance methods should always be defined.
4173 Methods.push_back(GetMethodConstant(*i));
4174 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004175 for (ObjCImplementationDecl::propimpl_iterator
4176 i = ID->propimpl_begin(CGM.getContext()),
4177 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004178 ObjCPropertyImplDecl *PID = *i;
4179
4180 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4181 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4182
4183 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4184 if (llvm::Constant *C = GetMethodConstant(MD))
4185 Methods.push_back(C);
4186 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4187 if (llvm::Constant *C = GetMethodConstant(MD))
4188 Methods.push_back(C);
4189 }
4190 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004191 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004192 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004193 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004194
4195 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4196 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4197 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4198 + OID->getNameAsString(),
4199 OID->protocol_begin(),
4200 OID->protocol_end());
4201
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004202 if (flags & CLS_META)
4203 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4204 else
4205 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004206 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4207 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004208 if (flags & CLS_META)
4209 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4210 else
4211 Values[ 9] =
4212 EmitPropertyList(
4213 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4214 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004215 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4216 Values);
4217 llvm::GlobalVariable *CLASS_RO_GV =
4218 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4219 llvm::GlobalValue::InternalLinkage,
4220 Init,
4221 (flags & CLS_META) ?
4222 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4223 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4224 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004225 CLASS_RO_GV->setAlignment(
4226 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004227 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004228 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004229
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004230}
4231
4232/// BuildClassMetaData - This routine defines that to-level meta-data
4233/// for the given ClassName for:
4234/// struct _class_t {
4235/// struct _class_t *isa;
4236/// struct _class_t * const superclass;
4237/// void *cache;
4238/// IMP *vtable;
4239/// struct class_ro_t *ro;
4240/// }
4241///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004242llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4243 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004244 llvm::Constant *IsAGV,
4245 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004246 llvm::Constant *ClassRoGV,
4247 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004248 std::vector<llvm::Constant*> Values(5);
4249 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004250 Values[1] = SuperClassGV
4251 ? SuperClassGV
4252 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004253 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4254 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4255 Values[4] = ClassRoGV; // &CLASS_RO_GV
4256 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4257 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004258 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4259 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004260 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004261 GV->setAlignment(
4262 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004263 if (HiddenVisibility)
4264 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004265 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004266}
4267
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004268void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4269 uint32_t &InstanceStart,
4270 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004271 // Find first and last (non-padding) ivars in this interface.
4272
4273 // FIXME: Use iterator.
4274 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4275 GetNamedIvarList(OID, OIvars);
4276
4277 if (OIvars.empty()) {
4278 InstanceStart = InstanceSize = 0;
4279 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004280 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004281
4282 const ObjCIvarDecl *First = OIvars.front();
4283 const ObjCIvarDecl *Last = OIvars.back();
4284
4285 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4286 const llvm::Type *FieldTy =
4287 CGM.getTypes().ConvertTypeForMem(Last->getType());
4288 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004289// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4290// with gcc-4.2). We postpone this for now.
4291#if 0
4292 if (Last->isBitField()) {
4293 Expr *BitWidth = Last->getBitWidth();
4294 uint64_t BitFieldSize =
4295 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
4296 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4297 }
4298#endif
Daniel Dunbar97776872009-04-22 07:32:20 +00004299 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004300}
4301
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004302void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4303 std::string ClassName = ID->getNameAsString();
4304 if (!ObjCEmptyCacheVar) {
4305 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004306 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004307 false,
4308 llvm::GlobalValue::ExternalLinkage,
4309 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004310 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004311 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004312
4313 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004314 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004315 false,
4316 llvm::GlobalValue::ExternalLinkage,
4317 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004318 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004319 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004320 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004321 assert(ID->getClassInterface() &&
4322 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004323 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004324 uint32_t InstanceStart =
4325 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4326 uint32_t InstanceSize = InstanceStart;
4327 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004328 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4329 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004330
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004331 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004332
Daniel Dunbar04d40782009-04-14 06:00:08 +00004333 bool classIsHidden =
4334 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004335 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004336 flags |= OBJC2_CLS_HIDDEN;
4337 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004338 // class is root
4339 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004340 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004341 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004342 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004343 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004344 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4345 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4346 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004347 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004348 // work on super class metadata symbol.
4349 std::string SuperClassName =
4350 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004351 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004352 }
4353 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4354 InstanceStart,
4355 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004356 std::string TClassName = ObjCMetaClassName + ClassName;
4357 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004358 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4359 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004360
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004361 // Metadata for the class
4362 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004363 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004364 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004365
4366 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4367 flags |= CLS_EXCEPTION;
4368
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004369 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004370 flags |= CLS_ROOT;
4371 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004372 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004373 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004374 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004375 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004376 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004377 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004378 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004379 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004380 InstanceStart,
4381 InstanceSize,
4382 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004383
4384 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004385 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004386 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4387 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004388 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004389
4390 // Force the definition of the EHType if necessary.
4391 if (flags & CLS_EXCEPTION)
4392 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004393}
4394
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004395/// GenerateProtocolRef - This routine is called to generate code for
4396/// a protocol reference expression; as in:
4397/// @code
4398/// @protocol(Proto1);
4399/// @endcode
4400/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4401/// which will hold address of the protocol meta-data.
4402///
4403llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4404 const ObjCProtocolDecl *PD) {
4405
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004406 // This routine is called for @protocol only. So, we must build definition
4407 // of protocol's meta-data (not a reference to it!)
4408 //
4409 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004410 ObjCTypes.ExternalProtocolPtrTy);
4411
4412 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4413 ProtocolName += PD->getNameAsCString();
4414
4415 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4416 if (PTGV)
4417 return Builder.CreateLoad(PTGV, false, "tmp");
4418 PTGV = new llvm::GlobalVariable(
4419 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004420 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004421 Init,
4422 ProtocolName,
4423 &CGM.getModule());
4424 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4425 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4426 UsedGlobals.push_back(PTGV);
4427 return Builder.CreateLoad(PTGV, false, "tmp");
4428}
4429
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004430/// GenerateCategory - Build metadata for a category implementation.
4431/// struct _category_t {
4432/// const char * const name;
4433/// struct _class_t *const cls;
4434/// const struct _method_list_t * const instance_methods;
4435/// const struct _method_list_t * const class_methods;
4436/// const struct _protocol_list_t * const protocols;
4437/// const struct _prop_list_t * const properties;
4438/// }
4439///
4440void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4441{
4442 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004443 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4444 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004445 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004446 std::string ExtClassName(getClassSymbolPrefix() +
4447 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004448
4449 std::vector<llvm::Constant*> Values(6);
4450 Values[0] = GetClassName(OCD->getIdentifier());
4451 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004452 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004453 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004454 std::vector<llvm::Constant*> Methods;
4455 std::string MethodListName(Prefix);
4456 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4457 "_$_" + OCD->getNameAsString();
4458
Douglas Gregor653f1b12009-04-23 01:02:12 +00004459 for (ObjCCategoryImplDecl::instmeth_iterator
4460 i = OCD->instmeth_begin(CGM.getContext()),
4461 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004462 // Instance methods should always be defined.
4463 Methods.push_back(GetMethodConstant(*i));
4464 }
4465
4466 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004467 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004468 Methods);
4469
4470 MethodListName = Prefix;
4471 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4472 OCD->getNameAsString();
4473 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004474 for (ObjCCategoryImplDecl::classmeth_iterator
4475 i = OCD->classmeth_begin(CGM.getContext()),
4476 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004477 // Class methods should always be defined.
4478 Methods.push_back(GetMethodConstant(*i));
4479 }
4480
4481 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004482 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004483 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004484 const ObjCCategoryDecl *Category =
4485 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004486 if (Category) {
4487 std::string ExtName(Interface->getNameAsString() + "_$_" +
4488 OCD->getNameAsString());
4489 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4490 + Interface->getNameAsString() + "_$_"
4491 + Category->getNameAsString(),
4492 Category->protocol_begin(),
4493 Category->protocol_end());
4494 Values[5] =
4495 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4496 OCD, Category, ObjCTypes);
4497 }
4498 else {
4499 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4500 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4501 }
4502
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004503 llvm::Constant *Init =
4504 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4505 Values);
4506 llvm::GlobalVariable *GCATV
4507 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4508 false,
4509 llvm::GlobalValue::InternalLinkage,
4510 Init,
4511 ExtCatName,
4512 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004513 GCATV->setAlignment(
4514 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004515 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004516 UsedGlobals.push_back(GCATV);
4517 DefinedCategories.push_back(GCATV);
4518}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004519
4520/// GetMethodConstant - Return a struct objc_method constant for the
4521/// given method if it has been defined. The result is null if the
4522/// method has not been defined. The return value has type MethodPtrTy.
4523llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4524 const ObjCMethodDecl *MD) {
4525 // FIXME: Use DenseMap::lookup
4526 llvm::Function *Fn = MethodDefinitions[MD];
4527 if (!Fn)
4528 return 0;
4529
4530 std::vector<llvm::Constant*> Method(3);
4531 Method[0] =
4532 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4533 ObjCTypes.SelectorPtrTy);
4534 Method[1] = GetMethodVarType(MD);
4535 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4536 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4537}
4538
4539/// EmitMethodList - Build meta-data for method declarations
4540/// struct _method_list_t {
4541/// uint32_t entsize; // sizeof(struct _objc_method)
4542/// uint32_t method_count;
4543/// struct _objc_method method_list[method_count];
4544/// }
4545///
4546llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4547 const std::string &Name,
4548 const char *Section,
4549 const ConstantVector &Methods) {
4550 // Return null for empty list.
4551 if (Methods.empty())
4552 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4553
4554 std::vector<llvm::Constant*> Values(3);
4555 // sizeof(struct _objc_method)
4556 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4557 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4558 // method_count
4559 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4560 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4561 Methods.size());
4562 Values[2] = llvm::ConstantArray::get(AT, Methods);
4563 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4564
4565 llvm::GlobalVariable *GV =
4566 new llvm::GlobalVariable(Init->getType(), false,
4567 llvm::GlobalValue::InternalLinkage,
4568 Init,
4569 Name,
4570 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004571 GV->setAlignment(
4572 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004573 GV->setSection(Section);
4574 UsedGlobals.push_back(GV);
4575 return llvm::ConstantExpr::getBitCast(GV,
4576 ObjCTypes.MethodListnfABIPtrTy);
4577}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004578
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004579/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4580/// the given ivar.
4581///
4582llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004583 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004584 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004585 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004586 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4587 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004588 llvm::GlobalVariable *IvarOffsetGV =
4589 CGM.getModule().getGlobalVariable(Name);
4590 if (!IvarOffsetGV)
4591 IvarOffsetGV =
4592 new llvm::GlobalVariable(ObjCTypes.LongTy,
4593 false,
4594 llvm::GlobalValue::ExternalLinkage,
4595 0,
4596 Name,
4597 &CGM.getModule());
4598 return IvarOffsetGV;
4599}
4600
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004601llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004602 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004603 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004604 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004605 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4606 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4607 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004608 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004609 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004610
4611 // FIXME: This matches gcc, but shouldn't the visibility be set on
4612 // the use as well (i.e., in ObjCIvarOffsetVariable).
4613 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4614 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4615 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004616 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004617 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004618 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004619 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004620 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004621}
4622
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004623/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004624/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004625/// IvarListnfABIPtrTy.
4626/// struct _ivar_t {
4627/// unsigned long int *offset; // pointer to ivar offset location
4628/// char *name;
4629/// char *type;
4630/// uint32_t alignment;
4631/// uint32_t size;
4632/// }
4633/// struct _ivar_list_t {
4634/// uint32 entsize; // sizeof(struct _ivar_t)
4635/// uint32 count;
4636/// struct _iver_t list[count];
4637/// }
4638///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004639
4640void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4641 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4642 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4643 E = OID->ivar_end(); I != E; ++I) {
4644 // Ignore unnamed bit-fields.
4645 if (!(*I)->getDeclName())
4646 continue;
4647
4648 Res.push_back(*I);
4649 }
4650
4651 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4652 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4653 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4654 Res.push_back(IV);
4655}
4656
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004657llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4658 const ObjCImplementationDecl *ID) {
4659
4660 std::vector<llvm::Constant*> Ivars, Ivar(5);
4661
4662 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4663 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4664
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004665 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004666
Daniel Dunbar91636d62009-04-20 00:33:43 +00004667 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004668 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004669 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004670
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004671 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4672 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004673 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004674 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004675 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4676 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004677 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004678 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004679 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4680 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004681 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004682 Align = llvm::Log2_32(Align);
4683 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004684 // NOTE. Size of a bitfield does not match gcc's, because of the
4685 // way bitfields are treated special in each. But I am told that
4686 // 'size' for bitfield ivars is ignored by the runtime so it does
4687 // not matter. If it matters, there is enough info to get the
4688 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004689 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4690 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4691 }
4692 // Return null for empty list.
4693 if (Ivars.empty())
4694 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4695 std::vector<llvm::Constant*> Values(3);
4696 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4697 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4698 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4699 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4700 Ivars.size());
4701 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4702 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4703 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4704 llvm::GlobalVariable *GV =
4705 new llvm::GlobalVariable(Init->getType(), false,
4706 llvm::GlobalValue::InternalLinkage,
4707 Init,
4708 Prefix + OID->getNameAsString(),
4709 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004710 GV->setAlignment(
4711 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004712 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004713
4714 UsedGlobals.push_back(GV);
4715 return llvm::ConstantExpr::getBitCast(GV,
4716 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004717}
4718
4719llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4720 const ObjCProtocolDecl *PD) {
4721 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4722
4723 if (!Entry) {
4724 // We use the initializer as a marker of whether this is a forward
4725 // reference or not. At module finalization we add the empty
4726 // contents for protocols which were referenced but never defined.
4727 Entry =
4728 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4729 llvm::GlobalValue::ExternalLinkage,
4730 0,
4731 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4732 &CGM.getModule());
4733 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4734 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004735 }
4736
4737 return Entry;
4738}
4739
4740/// GetOrEmitProtocol - Generate the protocol meta-data:
4741/// @code
4742/// struct _protocol_t {
4743/// id isa; // NULL
4744/// const char * const protocol_name;
4745/// const struct _protocol_list_t * protocol_list; // super protocols
4746/// const struct method_list_t * const instance_methods;
4747/// const struct method_list_t * const class_methods;
4748/// const struct method_list_t *optionalInstanceMethods;
4749/// const struct method_list_t *optionalClassMethods;
4750/// const struct _prop_list_t * properties;
4751/// const uint32_t size; // sizeof(struct _protocol_t)
4752/// const uint32_t flags; // = 0
4753/// }
4754/// @endcode
4755///
4756
4757llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4758 const ObjCProtocolDecl *PD) {
4759 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4760
4761 // Early exit if a defining object has already been generated.
4762 if (Entry && Entry->hasInitializer())
4763 return Entry;
4764
4765 const char *ProtocolName = PD->getNameAsCString();
4766
4767 // Construct method lists.
4768 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4769 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004770 for (ObjCProtocolDecl::instmeth_iterator
4771 i = PD->instmeth_begin(CGM.getContext()),
4772 e = PD->instmeth_end(CGM.getContext());
4773 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004774 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004775 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004776 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4777 OptInstanceMethods.push_back(C);
4778 } else {
4779 InstanceMethods.push_back(C);
4780 }
4781 }
4782
Douglas Gregor6ab35242009-04-09 21:40:53 +00004783 for (ObjCProtocolDecl::classmeth_iterator
4784 i = PD->classmeth_begin(CGM.getContext()),
4785 e = PD->classmeth_end(CGM.getContext());
4786 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004787 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004788 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4790 OptClassMethods.push_back(C);
4791 } else {
4792 ClassMethods.push_back(C);
4793 }
4794 }
4795
4796 std::vector<llvm::Constant*> Values(10);
4797 // isa is NULL
4798 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4799 Values[1] = GetClassName(PD->getIdentifier());
4800 Values[2] = EmitProtocolList(
4801 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4802 PD->protocol_begin(),
4803 PD->protocol_end());
4804
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004805 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004806 + PD->getNameAsString(),
4807 "__DATA, __objc_const",
4808 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004809 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 + PD->getNameAsString(),
4811 "__DATA, __objc_const",
4812 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004813 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004814 + PD->getNameAsString(),
4815 "__DATA, __objc_const",
4816 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004817 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004818 + PD->getNameAsString(),
4819 "__DATA, __objc_const",
4820 OptClassMethods);
4821 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4822 0, PD, ObjCTypes);
4823 uint32_t Size =
4824 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4825 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4826 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4827 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4828 Values);
4829
4830 if (Entry) {
4831 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004832 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004833 Entry->setInitializer(Init);
4834 } else {
4835 Entry =
4836 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004837 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004838 Init,
4839 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4840 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004841 Entry->setAlignment(
4842 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004844 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004845 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4846
4847 // Use this protocol meta-data to build protocol list table in section
4848 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004849 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004850 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004851 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004852 Entry,
4853 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4854 +ProtocolName,
4855 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004856 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004857 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004858 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004859 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4860 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861 return Entry;
4862}
4863
4864/// EmitProtocolList - Generate protocol list meta-data:
4865/// @code
4866/// struct _protocol_list_t {
4867/// long protocol_count; // Note, this is 32/64 bit
4868/// struct _protocol_t[protocol_count];
4869/// }
4870/// @endcode
4871///
4872llvm::Constant *
4873CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4874 ObjCProtocolDecl::protocol_iterator begin,
4875 ObjCProtocolDecl::protocol_iterator end) {
4876 std::vector<llvm::Constant*> ProtocolRefs;
4877
Fariborz Jahanianda320092009-01-29 19:24:30 +00004878 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004879 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004880 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4881
Daniel Dunbar948e2582009-02-15 07:36:20 +00004882 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004883 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4884 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004885 return llvm::ConstantExpr::getBitCast(GV,
4886 ObjCTypes.ProtocolListnfABIPtrTy);
4887
4888 for (; begin != end; ++begin)
4889 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4890
Fariborz Jahanianda320092009-01-29 19:24:30 +00004891 // This list is null terminated.
4892 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004893 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004894
4895 std::vector<llvm::Constant*> Values(2);
4896 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4897 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004898 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004899 ProtocolRefs.size()),
4900 ProtocolRefs);
4901
4902 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4903 GV = new llvm::GlobalVariable(Init->getType(), false,
4904 llvm::GlobalValue::InternalLinkage,
4905 Init,
4906 Name,
4907 &CGM.getModule());
4908 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004909 GV->setAlignment(
4910 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004911 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004912 return llvm::ConstantExpr::getBitCast(GV,
4913 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004914}
4915
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004916/// GetMethodDescriptionConstant - This routine build following meta-data:
4917/// struct _objc_method {
4918/// SEL _cmd;
4919/// char *method_type;
4920/// char *_imp;
4921/// }
4922
4923llvm::Constant *
4924CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4925 std::vector<llvm::Constant*> Desc(3);
4926 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4927 ObjCTypes.SelectorPtrTy);
4928 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004929 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004930 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4931 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4932}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004933
4934/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4935/// This code gen. amounts to generating code for:
4936/// @code
4937/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4938/// @encode
4939///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004940LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004941 CodeGen::CodeGenFunction &CGF,
4942 QualType ObjectTy,
4943 llvm::Value *BaseValue,
4944 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004945 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004946 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004947 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4948 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004949}
4950
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004951llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4952 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004953 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004954 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004955 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4956 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004957}
4958
Fariborz Jahanian46551122009-02-04 00:22:57 +00004959CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4960 CodeGen::CodeGenFunction &CGF,
4961 QualType ResultType,
4962 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004963 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004964 QualType Arg0Ty,
4965 bool IsSuper,
4966 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004967 // FIXME. Even though IsSuper is passes. This function doese not
4968 // handle calls to 'super' receivers.
4969 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004970 llvm::Value *Arg0 = Receiver;
4971 if (!IsSuper)
4972 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004973
4974 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004975 // FIXME. This is too much work to get the ABI-specific result type
4976 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4978 llvm::SmallVector<QualType, 16>());
4979 llvm::Constant *Fn;
4980 std::string Name("\01l_");
4981 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004982#if 0
4983 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004984 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004985 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004986 // FIXME. Is there a better way of getting these names.
4987 // They are available in RuntimeFunctions vector pair.
4988 Name += "objc_msgSendId_stret_fixup";
4989 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004990 else
4991#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004992 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004993 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004994 Name += "objc_msgSendSuper2_stret_fixup";
4995 }
4996 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004997 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004998 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004999 Name += "objc_msgSend_stret_fixup";
5000 }
5001 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005002 else if (ResultType->isFloatingType() &&
5003 // Selection of frret API only happens in 32bit nonfragile ABI.
5004 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005005 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005006 Name += "objc_msgSend_fpret_fixup";
5007 }
5008 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005009#if 0
5010// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005011 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005012 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005013 Name += "objc_msgSendId_fixup";
5014 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005015 else
5016#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005017 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005018 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005019 Name += "objc_msgSendSuper2_fixup";
5020 }
5021 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005022 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005023 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005024 Name += "objc_msgSend_fixup";
5025 }
5026 }
5027 Name += '_';
5028 std::string SelName(Sel.getAsString());
5029 // Replace all ':' in selector name with '_' ouch!
5030 for(unsigned i = 0; i < SelName.size(); i++)
5031 if (SelName[i] == ':')
5032 SelName[i] = '_';
5033 Name += SelName;
5034 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5035 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005036 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005037 std::vector<llvm::Constant*> Values(2);
5038 Values[0] = Fn;
5039 Values[1] = GetMethodVarName(Sel);
5040 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5041 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005042 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005043 Init,
5044 Name,
5045 &CGM.getModule());
5046 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005047 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005048 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005049 }
5050 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005051
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005052 CallArgList ActualArgs;
5053 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5054 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5055 ObjCTypes.MessageRefCPtrTy));
5056 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005057 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5058 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5059 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005060 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005061 Callee = CGF.Builder.CreateBitCast(Callee,
5062 llvm::PointerType::getUnqual(FTy));
5063 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005064}
5065
5066/// Generate code for a message send expression in the nonfragile abi.
5067CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5068 CodeGen::CodeGenFunction &CGF,
5069 QualType ResultType,
5070 Selector Sel,
5071 llvm::Value *Receiver,
5072 bool IsClassMessage,
5073 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005074 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005075 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005076 false, CallArgs);
5077}
5078
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005079llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005080CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005081 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5082
Daniel Dunbardfff2302009-03-02 05:18:14 +00005083 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005084 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5085 llvm::GlobalValue::ExternalLinkage,
5086 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005087 }
5088
5089 return GV;
5090}
5091
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005092llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005093 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005094 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5095
5096 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005097 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005098 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005099 Entry =
5100 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5101 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005102 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005103 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005104 &CGM.getModule());
5105 Entry->setAlignment(
5106 CGM.getTargetData().getPrefTypeAlignment(
5107 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005108 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5109 UsedGlobals.push_back(Entry);
5110 }
5111
5112 return Builder.CreateLoad(Entry, false, "tmp");
5113}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005114
Daniel Dunbar11394522009-04-18 08:51:00 +00005115llvm::Value *
5116CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5117 const ObjCInterfaceDecl *ID) {
5118 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5119
5120 if (!Entry) {
5121 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5122 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5123 Entry =
5124 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5125 llvm::GlobalValue::InternalLinkage,
5126 ClassGV,
5127 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5128 &CGM.getModule());
5129 Entry->setAlignment(
5130 CGM.getTargetData().getPrefTypeAlignment(
5131 ObjCTypes.ClassnfABIPtrTy));
5132 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005133 UsedGlobals.push_back(Entry);
5134 }
5135
5136 return Builder.CreateLoad(Entry, false, "tmp");
5137}
5138
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005139/// EmitMetaClassRef - Return a Value * of the address of _class_t
5140/// meta-data
5141///
5142llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5143 const ObjCInterfaceDecl *ID) {
5144 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5145 if (Entry)
5146 return Builder.CreateLoad(Entry, false, "tmp");
5147
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005148 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005149 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005150 Entry =
5151 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5152 llvm::GlobalValue::InternalLinkage,
5153 MetaClassGV,
5154 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5155 &CGM.getModule());
5156 Entry->setAlignment(
5157 CGM.getTargetData().getPrefTypeAlignment(
5158 ObjCTypes.ClassnfABIPtrTy));
5159
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005160 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005161 UsedGlobals.push_back(Entry);
5162
5163 return Builder.CreateLoad(Entry, false, "tmp");
5164}
5165
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005166/// GetClass - Return a reference to the class for the given interface
5167/// decl.
5168llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5169 const ObjCInterfaceDecl *ID) {
5170 return EmitClassRef(Builder, ID);
5171}
5172
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005173/// Generates a message send where the super is the receiver. This is
5174/// a message send to self with special delivery semantics indicating
5175/// which class's method should be called.
5176CodeGen::RValue
5177CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5178 QualType ResultType,
5179 Selector Sel,
5180 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005181 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005182 llvm::Value *Receiver,
5183 bool IsClassMessage,
5184 const CodeGen::CallArgList &CallArgs) {
5185 // ...
5186 // Create and init a super structure; this is a (receiver, class)
5187 // pair we will pass to objc_msgSendSuper.
5188 llvm::Value *ObjCSuper =
5189 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5190
5191 llvm::Value *ReceiverAsObject =
5192 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5193 CGF.Builder.CreateStore(ReceiverAsObject,
5194 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5195
5196 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005197 llvm::Value *Target;
5198 if (IsClassMessage) {
5199 if (isCategoryImpl) {
5200 // Message sent to "super' in a class method defined in
5201 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005202 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005203 Target = CGF.Builder.CreateStructGEP(Target, 0);
5204 Target = CGF.Builder.CreateLoad(Target);
5205 }
5206 else
5207 Target = EmitMetaClassRef(CGF.Builder, Class);
5208 }
5209 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005210 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005211
5212 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5213 // and ObjCTypes types.
5214 const llvm::Type *ClassTy =
5215 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5216 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5217 CGF.Builder.CreateStore(Target,
5218 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5219
5220 return EmitMessageSend(CGF, ResultType, Sel,
5221 ObjCSuper, ObjCTypes.SuperPtrCTy,
5222 true, CallArgs);
5223}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005224
5225llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5226 Selector Sel) {
5227 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5228
5229 if (!Entry) {
5230 llvm::Constant *Casted =
5231 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5232 ObjCTypes.SelectorPtrTy);
5233 Entry =
5234 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5235 llvm::GlobalValue::InternalLinkage,
5236 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5237 &CGM.getModule());
5238 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5239 UsedGlobals.push_back(Entry);
5240 }
5241
5242 return Builder.CreateLoad(Entry, false, "tmp");
5243}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005244/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5245/// objc_assign_ivar (id src, id *dst)
5246///
5247void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5248 llvm::Value *src, llvm::Value *dst)
5249{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005250 const llvm::Type * SrcTy = src->getType();
5251 if (!isa<llvm::PointerType>(SrcTy)) {
5252 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5253 assert(Size <= 8 && "does not support size > 8");
5254 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5255 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005256 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5257 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005258 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5259 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005260 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005261 src, dst, "assignivar");
5262 return;
5263}
5264
5265/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5266/// objc_assign_strongCast (id src, id *dst)
5267///
5268void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5269 CodeGen::CodeGenFunction &CGF,
5270 llvm::Value *src, llvm::Value *dst)
5271{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005272 const llvm::Type * SrcTy = src->getType();
5273 if (!isa<llvm::PointerType>(SrcTy)) {
5274 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5275 assert(Size <= 8 && "does not support size > 8");
5276 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5277 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005278 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5279 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005280 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5281 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005282 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005283 src, dst, "weakassign");
5284 return;
5285}
5286
5287/// EmitObjCWeakRead - Code gen for loading value of a __weak
5288/// object: objc_read_weak (id *src)
5289///
5290llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5291 CodeGen::CodeGenFunction &CGF,
5292 llvm::Value *AddrWeakObj)
5293{
Eli Friedman8339b352009-03-07 03:57:15 +00005294 const llvm::Type* DestTy =
5295 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005296 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005297 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005298 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005299 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005300 return read_weak;
5301}
5302
5303/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5304/// objc_assign_weak (id src, id *dst)
5305///
5306void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5307 llvm::Value *src, llvm::Value *dst)
5308{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005309 const llvm::Type * SrcTy = src->getType();
5310 if (!isa<llvm::PointerType>(SrcTy)) {
5311 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5312 assert(Size <= 8 && "does not support size > 8");
5313 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5314 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005315 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5316 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005317 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5318 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005319 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005320 src, dst, "weakassign");
5321 return;
5322}
5323
5324/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5325/// objc_assign_global (id src, id *dst)
5326///
5327void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5328 llvm::Value *src, llvm::Value *dst)
5329{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005330 const llvm::Type * SrcTy = src->getType();
5331 if (!isa<llvm::PointerType>(SrcTy)) {
5332 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5333 assert(Size <= 8 && "does not support size > 8");
5334 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5335 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005336 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5337 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005338 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5339 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005340 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005341 src, dst, "globalassign");
5342 return;
5343}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005344
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005345void
5346CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5347 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005348 bool isTry = isa<ObjCAtTryStmt>(S);
5349 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5350 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005351 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005352 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005353 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005354 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5355
5356 // For @synchronized, call objc_sync_enter(sync.expr). The
5357 // evaluation of the expression must occur before we enter the
5358 // @synchronized. We can safely avoid a temp here because jumps into
5359 // @synchronized are illegal & this will dominate uses.
5360 llvm::Value *SyncArg = 0;
5361 if (!isTry) {
5362 SyncArg =
5363 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5364 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005365 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005366 }
5367
5368 // Push an EH context entry, used for handling rethrows and jumps
5369 // through finally.
5370 CGF.PushCleanupBlock(FinallyBlock);
5371
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005373
5374 CGF.EmitBlock(TryBlock);
5375 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5376 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5377 CGF.EmitBranchThroughCleanup(FinallyEnd);
5378
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005379 // Emit the exception handler.
5380
5381 CGF.EmitBlock(TryHandler);
5382
5383 llvm::Value *llvm_eh_exception =
5384 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5385 llvm::Value *llvm_eh_selector_i64 =
5386 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5387 llvm::Value *llvm_eh_typeid_for_i64 =
5388 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5389 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5390 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5391
5392 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5393 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005394 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005395
5396 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005397 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005398 bool HasCatchAll = false;
5399 if (isTry) {
5400 if (const ObjCAtCatchStmt* CatchStmt =
5401 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5402 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005403 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005404 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005405
5406 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005407 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005408 // Use i8* null here to signal this is a catch all, not a cleanup.
5409 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5410 SelectorArgs.push_back(Null);
5411 HasCatchAll = true;
5412 break;
5413 }
5414
Daniel Dunbarede8de92009-03-06 00:01:21 +00005415 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5416 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005417 llvm::Value *IDEHType =
5418 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5419 if (!IDEHType)
5420 IDEHType =
5421 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5422 llvm::GlobalValue::ExternalLinkage,
5423 0, "OBJC_EHTYPE_id", &CGM.getModule());
5424 SelectorArgs.push_back(IDEHType);
5425 HasCatchAll = true;
5426 break;
5427 }
5428
5429 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005430 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005431 assert(PT && "Invalid @catch type.");
5432 const ObjCInterfaceType *IT =
5433 PT->getPointeeType()->getAsObjCInterfaceType();
5434 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005435 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005436 SelectorArgs.push_back(EHType);
5437 }
5438 }
5439 }
5440
5441 // We use a cleanup unless there was already a catch all.
5442 if (!HasCatchAll) {
5443 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005444 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005445 }
5446
5447 llvm::Value *Selector =
5448 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5449 SelectorArgs.begin(), SelectorArgs.end(),
5450 "selector");
5451 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005452 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005453 const Stmt *CatchBody = Handlers[i].second;
5454
5455 llvm::BasicBlock *Next = 0;
5456
5457 // The last handler always matches.
5458 if (i + 1 != e) {
5459 assert(CatchParam && "Only last handler can be a catch all.");
5460
5461 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5462 Next = CGF.createBasicBlock("catch.next");
5463 llvm::Value *Id =
5464 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5465 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5466 ObjCTypes.Int8PtrTy));
5467 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5468 Match, Next);
5469
5470 CGF.EmitBlock(Match);
5471 }
5472
5473 if (CatchBody) {
5474 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5475 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5476
5477 // Cleanups must call objc_end_catch.
5478 //
5479 // FIXME: It seems incorrect for objc_begin_catch to be inside
5480 // this context, but this matches gcc.
5481 CGF.PushCleanupBlock(MatchEnd);
5482 CGF.setInvokeDest(MatchHandler);
5483
5484 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005485 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005486
5487 // Bind the catch parameter if it exists.
5488 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005489 ExcObject =
5490 CGF.Builder.CreateBitCast(ExcObject,
5491 CGF.ConvertType(CatchParam->getType()));
5492 // CatchParam is a ParmVarDecl because of the grammar
5493 // construction used to handle this, but for codegen purposes
5494 // we treat this as a local decl.
5495 CGF.EmitLocalBlockVarDecl(*CatchParam);
5496 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005497 }
5498
5499 CGF.ObjCEHValueStack.push_back(ExcObject);
5500 CGF.EmitStmt(CatchBody);
5501 CGF.ObjCEHValueStack.pop_back();
5502
5503 CGF.EmitBranchThroughCleanup(FinallyEnd);
5504
5505 CGF.EmitBlock(MatchHandler);
5506
5507 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5508 // We are required to emit this call to satisfy LLVM, even
5509 // though we don't use the result.
5510 llvm::SmallVector<llvm::Value*, 8> Args;
5511 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005512 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005513 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5514 0));
5515 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5516 CGF.Builder.CreateStore(Exc, RethrowPtr);
5517 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5518
5519 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5520
5521 CGF.EmitBlock(MatchEnd);
5522
5523 // Unfortunately, we also have to generate another EH frame here
5524 // in case this throws.
5525 llvm::BasicBlock *MatchEndHandler =
5526 CGF.createBasicBlock("match.end.handler");
5527 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005528 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 Cont, MatchEndHandler,
5530 Args.begin(), Args.begin());
5531
5532 CGF.EmitBlock(Cont);
5533 if (Info.SwitchBlock)
5534 CGF.EmitBlock(Info.SwitchBlock);
5535 if (Info.EndBlock)
5536 CGF.EmitBlock(Info.EndBlock);
5537
5538 CGF.EmitBlock(MatchEndHandler);
5539 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5540 // We are required to emit this call to satisfy LLVM, even
5541 // though we don't use the result.
5542 Args.clear();
5543 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005544 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005545 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5546 0));
5547 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5548 CGF.Builder.CreateStore(Exc, RethrowPtr);
5549 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5550
5551 if (Next)
5552 CGF.EmitBlock(Next);
5553 } else {
5554 assert(!Next && "catchup should be last handler.");
5555
5556 CGF.Builder.CreateStore(Exc, RethrowPtr);
5557 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5558 }
5559 }
5560
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005561 // Pop the cleanup entry, the @finally is outside this cleanup
5562 // scope.
5563 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5564 CGF.setInvokeDest(PrevLandingPad);
5565
5566 CGF.EmitBlock(FinallyBlock);
5567
5568 if (isTry) {
5569 if (const ObjCAtFinallyStmt* FinallyStmt =
5570 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5571 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5572 } else {
5573 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5574 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005575 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005577
5578 if (Info.SwitchBlock)
5579 CGF.EmitBlock(Info.SwitchBlock);
5580 if (Info.EndBlock)
5581 CGF.EmitBlock(Info.EndBlock);
5582
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005583 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005584 CGF.EmitBranch(FinallyEnd);
5585
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005586 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005587 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005588 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005589 CGF.Builder.CreateUnreachable();
5590
5591 CGF.EmitBlock(FinallyEnd);
5592}
5593
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005594/// EmitThrowStmt - Generate code for a throw statement.
5595void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5596 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005597 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005598 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005599 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005600 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005601 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5602 "Unexpected rethrow outside @catch block.");
5603 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005604 }
5605
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005606 llvm::Value *ExceptionAsObject =
5607 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5608 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5609 if (InvokeDest) {
5610 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005611 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005612 Cont, InvokeDest,
5613 &ExceptionAsObject, &ExceptionAsObject + 1);
5614 CGF.EmitBlock(Cont);
5615 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005616 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005617 CGF.Builder.CreateUnreachable();
5618
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005619 // Clear the insertion point to indicate we are in unreachable code.
5620 CGF.Builder.ClearInsertionPoint();
5621}
Daniel Dunbare588b992009-03-01 04:46:24 +00005622
5623llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005624CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5625 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005626 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005627
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005628 // If we don't need a definition, return the entry if found or check
5629 // if we use an external reference.
5630 if (!ForDefinition) {
5631 if (Entry)
5632 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005633
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005634 // If this type (or a super class) has the __objc_exception__
5635 // attribute, emit an external reference.
5636 if (hasObjCExceptionAttribute(ID))
5637 return Entry =
5638 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5639 llvm::GlobalValue::ExternalLinkage,
5640 0,
5641 (std::string("OBJC_EHTYPE_$_") +
5642 ID->getIdentifier()->getName()),
5643 &CGM.getModule());
5644 }
5645
5646 // Otherwise we need to either make a new entry or fill in the
5647 // initializer.
5648 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005649 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005650 std::string VTableName = "objc_ehtype_vtable";
5651 llvm::GlobalVariable *VTableGV =
5652 CGM.getModule().getGlobalVariable(VTableName);
5653 if (!VTableGV)
5654 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5655 llvm::GlobalValue::ExternalLinkage,
5656 0, VTableName, &CGM.getModule());
5657
5658 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5659
5660 std::vector<llvm::Constant*> Values(3);
5661 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5662 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005663 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005664 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5665
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005666 if (Entry) {
5667 Entry->setInitializer(Init);
5668 } else {
5669 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5670 llvm::GlobalValue::WeakAnyLinkage,
5671 Init,
5672 (std::string("OBJC_EHTYPE_$_") +
5673 ID->getIdentifier()->getName()),
5674 &CGM.getModule());
5675 }
5676
Daniel Dunbar04d40782009-04-14 06:00:08 +00005677 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005678 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005679 Entry->setAlignment(8);
5680
5681 if (ForDefinition) {
5682 Entry->setSection("__DATA,__objc_const");
5683 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5684 } else {
5685 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5686 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005687
5688 return Entry;
5689}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005690
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005691/* *** */
5692
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005693CodeGen::CGObjCRuntime *
5694CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005695 return new CGObjCMac(CGM);
5696}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005697
5698CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005699CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005700 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005701}