blob: 6caaad6ffe14a9a2c34764a29c475e33176920fd [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;
732 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000733
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000734 /// LazySymbols - Symbols to generate a lazy reference for. See
735 /// DefinedSymbols and FinishModule().
736 std::set<IdentifierInfo*> LazySymbols;
737
738 /// DefinedSymbols - External symbols which are defined by this
739 /// module. The symbols in this list and LazySymbols are used to add
740 /// special linker symbols which ensure that Objective-C modules are
741 /// linked properly.
742 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000743
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000744 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000745 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000746
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000747 /// MethodVarNames - uniqued method variable names.
748 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000749
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000750 /// MethodVarTypes - uniqued method type signatures. We have to use
751 /// a StringMap here because have no other unique reference.
752 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000753
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000754 /// MethodDefinitions - map of methods which have been defined in
755 /// this translation unit.
756 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000757
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000758 /// PropertyNames - uniqued method variable names.
759 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000760
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000761 /// ClassReferences - uniqued class references.
762 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000763
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000764 /// SelectorReferences - uniqued selector references.
765 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000766
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000767 /// Protocols - Protocols for which an objc_protocol structure has
768 /// been emitted. Forward declarations are handled by creating an
769 /// empty structure whose initializer is filled in when/if defined.
770 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000771
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000772 /// DefinedProtocols - Protocols which have actually been
773 /// defined. We should not need this, see FIXME in GenerateProtocol.
774 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000775
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000776 /// DefinedClasses - List of defined classes.
777 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000778
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000779 /// DefinedCategories - List of defined categories.
780 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000781
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000782 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000783 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000784 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000785
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000786 /// GetNameForMethod - Return a name for the given method.
787 /// \param[out] NameOut - The return value.
788 void GetNameForMethod(const ObjCMethodDecl *OMD,
789 const ObjCContainerDecl *CD,
790 std::string &NameOut);
791
792 /// GetMethodVarName - Return a unique constant for the given
793 /// selector's name. The return value has type char *.
794 llvm::Constant *GetMethodVarName(Selector Sel);
795 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
796 llvm::Constant *GetMethodVarName(const std::string &Name);
797
798 /// GetMethodVarType - Return a unique constant for the given
799 /// selector's name. The return value has type char *.
800
801 // FIXME: This is a horrible name.
802 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000803 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000804
805 /// GetPropertyName - Return a unique constant for the given
806 /// name. The return value has type char *.
807 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
808
809 // FIXME: This can be dropped once string functions are unified.
810 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
811 const Decl *Container);
812
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000813 /// GetClassName - Return a unique constant for the given selector's
814 /// name. The return value has type char *.
815 llvm::Constant *GetClassName(IdentifierInfo *Ident);
816
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000817 /// BuildIvarLayout - Builds ivar layout bitmap for the class
818 /// implementation for the __strong or __weak case.
819 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000820 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
821 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000822
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000823 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
824 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000825 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000826 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000827 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000828 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000829
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000830 /// GetIvarLayoutName - Returns a unique constant for the given
831 /// ivar layout bitmap.
832 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
833 const ObjCCommonTypesHelper &ObjCTypes);
834
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000835 /// EmitPropertyList - Emit the given property list. The return
836 /// value has type PropertyListPtrTy.
837 llvm::Constant *EmitPropertyList(const std::string &Name,
838 const Decl *Container,
839 const ObjCContainerDecl *OCD,
840 const ObjCCommonTypesHelper &ObjCTypes);
841
Fariborz Jahanianda320092009-01-29 19:24:30 +0000842 /// GetProtocolRef - Return a reference to the internal protocol
843 /// description, creating an empty one if it has not been
844 /// defined. The return value has type ProtocolPtrTy.
845 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000846
Chris Lattnercd0ee142009-03-31 08:33:16 +0000847 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000848 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
849 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000850 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000851
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000852 /// CreateMetadataVar - Create a global variable with internal
853 /// linkage for use by the Objective-C runtime.
854 ///
855 /// This is a convenience wrapper which not only creates the
856 /// variable, but also sets the section and alignment and adds the
857 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000858 ///
859 /// \param Name - The variable name.
860 /// \param Init - The variable initializer; this is also used to
861 /// define the type of the variable.
862 /// \param Section - The section the variable should go into, or 0.
863 /// \param Align - The alignment for the variable, or 0.
864 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000865 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000866 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
867 llvm::Constant *Init,
868 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000869 unsigned Align,
870 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000871
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000872 /// GetNamedIvarList - Return the list of ivars in the interface
873 /// itself (not including super classes and not including unnamed
874 /// bitfields).
875 ///
876 /// For the non-fragile ABI, this also includes synthesized property
877 /// ivars.
878 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
879 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
880
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000881public:
882 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
883 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000884
Steve Naroff33fdb732009-03-31 16:53:37 +0000885 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000886
887 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
888 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000889
890 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
891
892 /// GetOrEmitProtocol - Get the protocol object for the given
893 /// declaration, emitting it if necessary. The return value has type
894 /// ProtocolPtrTy.
895 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
896
897 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
898 /// object for the given declaration, emitting it if needed. These
899 /// forward references will be filled in with empty bodies if no
900 /// definition is seen. The return value has type ProtocolPtrTy.
901 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000902};
903
904class CGObjCMac : public CGObjCCommonMac {
905private:
906 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000907 /// EmitImageInfo - Emit the image info marker used to encode some module
908 /// level information.
909 void EmitImageInfo();
910
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000911 /// EmitModuleInfo - Another marker encoding module level
912 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000913 void EmitModuleInfo();
914
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000915 /// EmitModuleSymols - Emit module symbols, the list of defined
916 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000917 llvm::Constant *EmitModuleSymbols();
918
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000919 /// FinishModule - Write out global data structures at the end of
920 /// processing a translation unit.
921 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000922
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000923 /// EmitClassExtension - Generate the class extension structure used
924 /// to store the weak ivar layout and properties. The return value
925 /// has type ClassExtensionPtrTy.
926 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
927
928 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
929 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000930 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000931 const ObjCInterfaceDecl *ID);
932
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000933 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000934 QualType ResultType,
935 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000936 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000937 QualType Arg0Ty,
938 bool IsSuper,
939 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000940
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000941 /// EmitIvarList - Emit the ivar list for the given
942 /// implementation. If ForClass is true the list of class ivars
943 /// (i.e. metaclass ivars) is emitted, otherwise the list of
944 /// interface ivars will be emitted. The return value has type
945 /// IvarListPtrTy.
946 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000947 bool ForClass);
948
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000949 /// EmitMetaClass - Emit a forward reference to the class structure
950 /// for the metaclass of the given interface. The return value has
951 /// type ClassPtrTy.
952 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
953
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000954 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000955 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000956 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
957 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000958 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000959 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000960
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000961 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000962
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000963 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000964
965 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000966 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000967 llvm::Constant *EmitMethodList(const std::string &Name,
968 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000969 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000970
971 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000972 /// method declarations.
973 /// - TypeName: The name for the type containing the methods.
974 /// - IsProtocol: True iff these methods are for a protocol.
975 /// - ClassMethds: True iff these are class methods.
976 /// - Required: When true, only "required" methods are
977 /// listed. Similarly, when false only "optional" methods are
978 /// listed. For classes this should always be true.
979 /// - begin, end: The method list to output.
980 ///
981 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000982 llvm::Constant *EmitMethodDescList(const std::string &Name,
983 const char *Section,
984 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000985
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000986 /// GetOrEmitProtocol - Get the protocol object for the given
987 /// declaration, emitting it if necessary. The return value has type
988 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000989 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000990
991 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
992 /// object for the given declaration, emitting it if needed. These
993 /// forward references will be filled in with empty bodies if no
994 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000995 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000996
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000997 /// EmitProtocolExtension - Generate the protocol extension
998 /// structure used to store optional instance and class methods, and
999 /// protocol properties. The return value has type
1000 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001001 llvm::Constant *
1002 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1003 const ConstantVector &OptInstanceMethods,
1004 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001005
1006 /// EmitProtocolList - Generate the list of referenced
1007 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001008 llvm::Constant *EmitProtocolList(const std::string &Name,
1009 ObjCProtocolDecl::protocol_iterator begin,
1010 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001011
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001012 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1013 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001014 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001015
Fariborz Jahanianda320092009-01-29 19:24:30 +00001016 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001018
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001019 virtual llvm::Function *ModuleInitFunction();
1020
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001021 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001022 QualType ResultType,
1023 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001024 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001025 bool IsClassMessage,
1026 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001027
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001028 virtual CodeGen::RValue
1029 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001030 QualType ResultType,
1031 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001032 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001033 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001034 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001035 bool IsClassMessage,
1036 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001037
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001038 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001039 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001040
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001041 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001042
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001043 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001044
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001045 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001046
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001047 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001048 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001049
Chris Lattner74391b42009-03-22 21:03:39 +00001050 virtual llvm::Constant *GetPropertyGetFunction();
1051 virtual llvm::Constant *GetPropertySetFunction();
1052 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001053
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001054 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1055 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001056 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1057 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001058 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001059 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001060 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1061 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001062 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1063 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001064 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1065 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001066 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1067 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001068
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001069 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1070 QualType ObjectTy,
1071 llvm::Value *BaseValue,
1072 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001073 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001074 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001075 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001076 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001077};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001078
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001079class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001080private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001081 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001082 llvm::GlobalVariable* ObjCEmptyCacheVar;
1083 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001084
Daniel Dunbar11394522009-04-18 08:51:00 +00001085 /// SuperClassReferences - uniqued super class references.
1086 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1087
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001088 /// MetaClassReferences - uniqued meta class references.
1089 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001090
1091 /// EHTypeReferences - uniqued class ehtype references.
1092 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001093
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001094 /// FinishNonFragileABIModule - Write out global data structures at the end of
1095 /// processing a translation unit.
1096 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001097
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001098 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1099 unsigned InstanceStart,
1100 unsigned InstanceSize,
1101 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001102 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1103 llvm::Constant *IsAGV,
1104 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001105 llvm::Constant *ClassRoGV,
1106 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001107
1108 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1109
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001110 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1111
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001112 /// EmitMethodList - Emit the method list for the given
1113 /// implementation. The return value has type MethodListnfABITy.
1114 llvm::Constant *EmitMethodList(const std::string &Name,
1115 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001116 const ConstantVector &Methods);
1117 /// EmitIvarList - Emit the ivar list for the given
1118 /// implementation. If ForClass is true the list of class ivars
1119 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1120 /// interface ivars will be emitted. The return value has type
1121 /// IvarListnfABIPtrTy.
1122 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001123
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001124 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001125 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001126 unsigned long int offset);
1127
Fariborz Jahanianda320092009-01-29 19:24:30 +00001128 /// GetOrEmitProtocol - Get the protocol object for the given
1129 /// declaration, emitting it if necessary. The return value has type
1130 /// ProtocolPtrTy.
1131 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1132
1133 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1134 /// object for the given declaration, emitting it if needed. These
1135 /// forward references will be filled in with empty bodies if no
1136 /// definition is seen. The return value has type ProtocolPtrTy.
1137 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1138
1139 /// EmitProtocolList - Generate the list of referenced
1140 /// protocols. The return value has type ProtocolListPtrTy.
1141 llvm::Constant *EmitProtocolList(const std::string &Name,
1142 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001143 ObjCProtocolDecl::protocol_iterator end);
1144
1145 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1146 QualType ResultType,
1147 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001148 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001149 QualType Arg0Ty,
1150 bool IsSuper,
1151 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001152
1153 /// GetClassGlobal - Return the global variable for the Objective-C
1154 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001155 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1156
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001157 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001158 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001159 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001160 const ObjCInterfaceDecl *ID);
1161
1162 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1163 /// for the given super class reference.
1164 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1165 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001166
1167 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1168 /// meta-data
1169 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1170 const ObjCInterfaceDecl *ID);
1171
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001172 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1173 /// the given ivar.
1174 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001175 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001176 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001177 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001178
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001179 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1180 /// for the given selector.
1181 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001182
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001183 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001184 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001185 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1186 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001187
1188 const char *getMetaclassSymbolPrefix() const {
1189 return "OBJC_METACLASS_$_";
1190 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001191
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001192 const char *getClassSymbolPrefix() const {
1193 return "OBJC_CLASS_$_";
1194 }
1195
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001196 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1197 uint32_t &InstanceStart,
1198 uint32_t &InstanceSize);
1199
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001200public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001201 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001202 // FIXME. All stubs for now!
1203 virtual llvm::Function *ModuleInitFunction();
1204
1205 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1206 QualType ResultType,
1207 Selector Sel,
1208 llvm::Value *Receiver,
1209 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001210 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001211
1212 virtual CodeGen::RValue
1213 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1214 QualType ResultType,
1215 Selector Sel,
1216 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001217 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001218 llvm::Value *Receiver,
1219 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001220 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001221
1222 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001223 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001224
1225 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001226 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001227
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001228 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001229
1230 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001231 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001232 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001233
Chris Lattner74391b42009-03-22 21:03:39 +00001234 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001235 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001236 }
Chris Lattner74391b42009-03-22 21:03:39 +00001237 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001238 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001239 }
Chris Lattner74391b42009-03-22 21:03:39 +00001240 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001241 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001242 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001243
1244 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001245 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001246 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001247 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001248 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001249 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001250 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001251 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001252 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001253 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001254 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001255 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001256 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001257 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001258 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1259 QualType ObjectTy,
1260 llvm::Value *BaseValue,
1261 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001262 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001263 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001264 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001265 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001266};
1267
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001268} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001269
1270/* *** Helper Functions *** */
1271
1272/// getConstantGEP() - Help routine to construct simple GEPs.
1273static llvm::Constant *getConstantGEP(llvm::Constant *C,
1274 unsigned idx0,
1275 unsigned idx1) {
1276 llvm::Value *Idxs[] = {
1277 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1278 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1279 };
1280 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1281}
1282
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001283/// hasObjCExceptionAttribute - Return true if this class or any super
1284/// class has the __objc_exception__ attribute.
1285static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001286 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001287 return true;
1288 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1289 return hasObjCExceptionAttribute(Super);
1290 return false;
1291}
1292
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001293/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001294
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001295CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1296 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001297{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001298 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001299 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001300}
1301
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001302/// GetClass - Return a reference to the class for the given interface
1303/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001304llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001305 const ObjCInterfaceDecl *ID) {
1306 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001307}
1308
1309/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001310llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001311 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001312}
1313
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001314/// Generate a constant CFString object.
1315/*
1316 struct __builtin_CFString {
1317 const int *isa; // point to __CFConstantStringClassReference
1318 int flags;
1319 const char *str;
1320 long length;
1321 };
1322*/
1323
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001324llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001325 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001326 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001327}
1328
1329/// Generates a message send where the super is the receiver. This is
1330/// a message send to self with special delivery semantics indicating
1331/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001332CodeGen::RValue
1333CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001334 QualType ResultType,
1335 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001336 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001337 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001338 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001339 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001340 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001341 // Create and init a super structure; this is a (receiver, class)
1342 // pair we will pass to objc_msgSendSuper.
1343 llvm::Value *ObjCSuper =
1344 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1345 llvm::Value *ReceiverAsObject =
1346 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1347 CGF.Builder.CreateStore(ReceiverAsObject,
1348 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001349
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001350 // If this is a class message the metaclass is passed as the target.
1351 llvm::Value *Target;
1352 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001353 if (isCategoryImpl) {
1354 // Message sent to 'super' in a class method defined in a category
1355 // implementation requires an odd treatment.
1356 // If we are in a class method, we must retrieve the
1357 // _metaclass_ for the current class, pointed at by
1358 // the class's "isa" pointer. The following assumes that
1359 // isa" is the first ivar in a class (which it must be).
1360 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1361 Target = CGF.Builder.CreateStructGEP(Target, 0);
1362 Target = CGF.Builder.CreateLoad(Target);
1363 }
1364 else {
1365 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1366 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1367 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1368 Target = Super;
1369 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001370 } else {
1371 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1372 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001373 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1374 // and ObjCTypes types.
1375 const llvm::Type *ClassTy =
1376 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001377 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001378 CGF.Builder.CreateStore(Target,
1379 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1380
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001381 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001382 ObjCSuper, ObjCTypes.SuperPtrCTy,
1383 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001384}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001385
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001386/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001387CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001388 QualType ResultType,
1389 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001390 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001391 bool IsClassMessage,
1392 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001393 llvm::Value *Arg0 =
1394 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001395 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001396 Arg0, CGF.getContext().getObjCIdType(),
1397 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001398}
1399
1400CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001401 QualType ResultType,
1402 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001403 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001404 QualType Arg0Ty,
1405 bool IsSuper,
1406 const CallArgList &CallArgs) {
1407 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001408 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1409 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1410 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001411 CGF.getContext().getObjCSelType()));
1412 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001413
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001414 CodeGenTypes &Types = CGM.getTypes();
1415 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1416 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001417
1418 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001419 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001420 Fn = ObjCTypes.getSendStretFn(IsSuper);
1421 } else if (ResultType->isFloatingType()) {
1422 // FIXME: Sadly, this is wrong. This actually depends on the
1423 // architecture. This happens to be right for x86-32 though.
1424 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1425 } else {
1426 Fn = ObjCTypes.getSendFn(IsSuper);
1427 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001428 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001429 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001430}
1431
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001432llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001433 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001434 // FIXME: I don't understand why gcc generates this, or where it is
1435 // resolved. Investigate. Its also wasteful to look this up over and
1436 // over.
1437 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1438
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001439 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1440 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001441}
1442
Fariborz Jahanianda320092009-01-29 19:24:30 +00001443void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001444 // FIXME: We shouldn't need this, the protocol decl should contain
1445 // enough information to tell us whether this was a declaration or a
1446 // definition.
1447 DefinedProtocols.insert(PD->getIdentifier());
1448
1449 // If we have generated a forward reference to this protocol, emit
1450 // it now. Otherwise do nothing, the protocol objects are lazily
1451 // emitted.
1452 if (Protocols.count(PD->getIdentifier()))
1453 GetOrEmitProtocol(PD);
1454}
1455
Fariborz Jahanianda320092009-01-29 19:24:30 +00001456llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001457 if (DefinedProtocols.count(PD->getIdentifier()))
1458 return GetOrEmitProtocol(PD);
1459 return GetOrEmitProtocolRef(PD);
1460}
1461
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001462/*
1463 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1464 struct _objc_protocol {
1465 struct _objc_protocol_extension *isa;
1466 char *protocol_name;
1467 struct _objc_protocol_list *protocol_list;
1468 struct _objc__method_prototype_list *instance_methods;
1469 struct _objc__method_prototype_list *class_methods
1470 };
1471
1472 See EmitProtocolExtension().
1473*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001474llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1475 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1476
1477 // Early exit if a defining object has already been generated.
1478 if (Entry && Entry->hasInitializer())
1479 return Entry;
1480
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001481 // FIXME: I don't understand why gcc generates this, or where it is
1482 // resolved. Investigate. Its also wasteful to look this up over and
1483 // over.
1484 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1485
Chris Lattner8ec03f52008-11-24 03:54:41 +00001486 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001487
1488 // Construct method lists.
1489 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1490 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001491 for (ObjCProtocolDecl::instmeth_iterator
1492 i = PD->instmeth_begin(CGM.getContext()),
1493 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001494 ObjCMethodDecl *MD = *i;
1495 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1496 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1497 OptInstanceMethods.push_back(C);
1498 } else {
1499 InstanceMethods.push_back(C);
1500 }
1501 }
1502
Douglas Gregor6ab35242009-04-09 21:40:53 +00001503 for (ObjCProtocolDecl::classmeth_iterator
1504 i = PD->classmeth_begin(CGM.getContext()),
1505 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001506 ObjCMethodDecl *MD = *i;
1507 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1508 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1509 OptClassMethods.push_back(C);
1510 } else {
1511 ClassMethods.push_back(C);
1512 }
1513 }
1514
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001515 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001516 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001517 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001518 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001519 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001520 PD->protocol_begin(),
1521 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001522 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1524 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001525 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1526 InstanceMethods);
1527 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001528 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1529 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001530 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1531 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001532 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1533 Values);
1534
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001535 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001536 // Already created, fix the linkage and update the initializer.
1537 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001538 Entry->setInitializer(Init);
1539 } else {
1540 Entry =
1541 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1542 llvm::GlobalValue::InternalLinkage,
1543 Init,
1544 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1545 &CGM.getModule());
1546 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001547 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001548 UsedGlobals.push_back(Entry);
1549 // FIXME: Is this necessary? Why only for protocol?
1550 Entry->setAlignment(4);
1551 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001552
1553 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001554}
1555
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001556llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001557 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1558
1559 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001560 // We use the initializer as a marker of whether this is a forward
1561 // reference or not. At module finalization we add the empty
1562 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001563 Entry =
1564 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001565 llvm::GlobalValue::ExternalLinkage,
1566 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001567 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001568 &CGM.getModule());
1569 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001570 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001571 UsedGlobals.push_back(Entry);
1572 // FIXME: Is this necessary? Why only for protocol?
1573 Entry->setAlignment(4);
1574 }
1575
1576 return Entry;
1577}
1578
1579/*
1580 struct _objc_protocol_extension {
1581 uint32_t size;
1582 struct objc_method_description_list *optional_instance_methods;
1583 struct objc_method_description_list *optional_class_methods;
1584 struct objc_property_list *instance_properties;
1585 };
1586*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001587llvm::Constant *
1588CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1589 const ConstantVector &OptInstanceMethods,
1590 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001591 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001592 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001593 std::vector<llvm::Constant*> Values(4);
1594 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001595 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001596 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1597 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001598 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1599 OptInstanceMethods);
1600 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001601 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1602 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001603 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1604 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001605 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1606 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001607 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001608
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001609 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001610 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1611 Values[3]->isNullValue())
1612 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1613
1614 llvm::Constant *Init =
1615 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001616
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001617 // No special section, but goes in llvm.used
1618 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1619 Init,
1620 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001621}
1622
1623/*
1624 struct objc_protocol_list {
1625 struct objc_protocol_list *next;
1626 long count;
1627 Protocol *list[];
1628 };
1629*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001630llvm::Constant *
1631CGObjCMac::EmitProtocolList(const std::string &Name,
1632 ObjCProtocolDecl::protocol_iterator begin,
1633 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001634 std::vector<llvm::Constant*> ProtocolRefs;
1635
Daniel Dunbardbc933702008-08-21 21:57:41 +00001636 for (; begin != end; ++begin)
1637 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001638
1639 // Just return null for empty protocol lists
1640 if (ProtocolRefs.empty())
1641 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1642
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001643 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001644 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1645
1646 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001647 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001648 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1649 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1650 Values[2] =
1651 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1652 ProtocolRefs.size()),
1653 ProtocolRefs);
1654
1655 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1656 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001657 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001658 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001659 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1660}
1661
1662/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001663 struct _objc_property {
1664 const char * const name;
1665 const char * const attributes;
1666 };
1667
1668 struct _objc_property_list {
1669 uint32_t entsize; // sizeof (struct _objc_property)
1670 uint32_t prop_count;
1671 struct _objc_property[prop_count];
1672 };
1673*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001674llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1675 const Decl *Container,
1676 const ObjCContainerDecl *OCD,
1677 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001678 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001679 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1680 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001681 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001682 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001683 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001684 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1685 Prop));
1686 }
1687
1688 // Return null for empty list.
1689 if (Properties.empty())
1690 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1691
1692 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001693 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001694 std::vector<llvm::Constant*> Values(3);
1695 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1696 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1697 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1698 Properties.size());
1699 Values[2] = llvm::ConstantArray::get(AT, Properties);
1700 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1701
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001702 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001703 CreateMetadataVar(Name, Init,
1704 (ObjCABI == 2) ? "__DATA, __objc_const" :
1705 "__OBJC,__property,regular,no_dead_strip",
1706 (ObjCABI == 2) ? 8 : 4,
1707 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001708 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001709}
1710
1711/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001712 struct objc_method_description_list {
1713 int count;
1714 struct objc_method_description list[];
1715 };
1716*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001717llvm::Constant *
1718CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1719 std::vector<llvm::Constant*> Desc(2);
1720 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1721 ObjCTypes.SelectorPtrTy);
1722 Desc[1] = GetMethodVarType(MD);
1723 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1724 Desc);
1725}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001726
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001727llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1728 const char *Section,
1729 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001730 // Return null for empty list.
1731 if (Methods.empty())
1732 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1733
1734 std::vector<llvm::Constant*> Values(2);
1735 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1736 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1737 Methods.size());
1738 Values[1] = llvm::ConstantArray::get(AT, Methods);
1739 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1740
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001741 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001742 return llvm::ConstantExpr::getBitCast(GV,
1743 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001744}
1745
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001746/*
1747 struct _objc_category {
1748 char *category_name;
1749 char *class_name;
1750 struct _objc_method_list *instance_methods;
1751 struct _objc_method_list *class_methods;
1752 struct _objc_protocol_list *protocols;
1753 uint32_t size; // <rdar://4585769>
1754 struct _objc_property_list *instance_properties;
1755 };
1756 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001757void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001758 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001759
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001760 // FIXME: This is poor design, the OCD should have a pointer to the
1761 // category decl. Additionally, note that Category can be null for
1762 // the @implementation w/o an @interface case. Sema should just
1763 // create one for us as it does for @implementation so everyone else
1764 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001765 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001766 const ObjCCategoryDecl *Category =
1767 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001768 std::string ExtName(Interface->getNameAsString() + "_" +
1769 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001770
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001771 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001772 for (ObjCCategoryImplDecl::instmeth_iterator
1773 i = OCD->instmeth_begin(CGM.getContext()),
1774 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001775 // Instance methods should always be defined.
1776 InstanceMethods.push_back(GetMethodConstant(*i));
1777 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001778 for (ObjCCategoryImplDecl::classmeth_iterator
1779 i = OCD->classmeth_begin(CGM.getContext()),
1780 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001781 // Class methods should always be defined.
1782 ClassMethods.push_back(GetMethodConstant(*i));
1783 }
1784
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001785 std::vector<llvm::Constant*> Values(7);
1786 Values[0] = GetClassName(OCD->getIdentifier());
1787 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001788 Values[2] =
1789 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1790 ExtName,
1791 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001792 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001793 Values[3] =
1794 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001795 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001796 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001797 if (Category) {
1798 Values[4] =
1799 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1800 Category->protocol_begin(),
1801 Category->protocol_end());
1802 } else {
1803 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1804 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001805 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001806
1807 // If there is no category @interface then there can be no properties.
1808 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001809 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001810 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001811 } else {
1812 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1813 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001814
1815 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1816 Values);
1817
1818 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001819 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1820 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001821 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001822 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001823}
1824
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001825// FIXME: Get from somewhere?
1826enum ClassFlags {
1827 eClassFlags_Factory = 0x00001,
1828 eClassFlags_Meta = 0x00002,
1829 // <rdr://5142207>
1830 eClassFlags_HasCXXStructors = 0x02000,
1831 eClassFlags_Hidden = 0x20000,
1832 eClassFlags_ABI2_Hidden = 0x00010,
1833 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1834};
1835
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001836/*
1837 struct _objc_class {
1838 Class isa;
1839 Class super_class;
1840 const char *name;
1841 long version;
1842 long info;
1843 long instance_size;
1844 struct _objc_ivar_list *ivars;
1845 struct _objc_method_list *methods;
1846 struct _objc_cache *cache;
1847 struct _objc_protocol_list *protocols;
1848 // Objective-C 1.0 extensions (<rdr://4585769>)
1849 const char *ivar_layout;
1850 struct _objc_class_ext *ext;
1851 };
1852
1853 See EmitClassExtension();
1854 */
1855void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001856 DefinedSymbols.insert(ID->getIdentifier());
1857
Chris Lattner8ec03f52008-11-24 03:54:41 +00001858 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001859 // FIXME: Gross
1860 ObjCInterfaceDecl *Interface =
1861 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001862 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001863 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001864 Interface->protocol_begin(),
1865 Interface->protocol_end());
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00001866 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001867 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001868 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001869
1870 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001871 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001872 Flags |= eClassFlags_Hidden;
1873
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001874 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001875 for (ObjCImplementationDecl::instmeth_iterator
1876 i = ID->instmeth_begin(CGM.getContext()),
1877 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001878 // Instance methods should always be defined.
1879 InstanceMethods.push_back(GetMethodConstant(*i));
1880 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001881 for (ObjCImplementationDecl::classmeth_iterator
1882 i = ID->classmeth_begin(CGM.getContext()),
1883 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001884 // Class methods should always be defined.
1885 ClassMethods.push_back(GetMethodConstant(*i));
1886 }
1887
Douglas Gregor653f1b12009-04-23 01:02:12 +00001888 for (ObjCImplementationDecl::propimpl_iterator
1889 i = ID->propimpl_begin(CGM.getContext()),
1890 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001891 ObjCPropertyImplDecl *PID = *i;
1892
1893 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1894 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1895
1896 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1897 if (llvm::Constant *C = GetMethodConstant(MD))
1898 InstanceMethods.push_back(C);
1899 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1900 if (llvm::Constant *C = GetMethodConstant(MD))
1901 InstanceMethods.push_back(C);
1902 }
1903 }
1904
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001905 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001906 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001907 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001908 // Record a reference to the super class.
1909 LazySymbols.insert(Super->getIdentifier());
1910
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001911 Values[ 1] =
1912 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1913 ObjCTypes.ClassPtrTy);
1914 } else {
1915 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1916 }
1917 Values[ 2] = GetClassName(ID->getIdentifier());
1918 // Version is always 0.
1919 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1920 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1921 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001922 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001923 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001924 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001925 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001926 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001927 // cache is always NULL.
1928 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1929 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001930 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001931 Values[11] = EmitClassExtension(ID);
1932 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1933 Values);
1934
1935 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001936 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1937 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001938 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001939 DefinedClasses.push_back(GV);
1940}
1941
1942llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1943 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001944 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001945 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001946 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001947 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001948
Daniel Dunbar04d40782009-04-14 06:00:08 +00001949 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001950 Flags |= eClassFlags_Hidden;
1951
1952 std::vector<llvm::Constant*> Values(12);
1953 // The isa for the metaclass is the root of the hierarchy.
1954 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1955 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1956 Root = Super;
1957 Values[ 0] =
1958 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1959 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001960 // The super class for the metaclass is emitted as the name of the
1961 // super class. The runtime fixes this up to point to the
1962 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001963 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1964 Values[ 1] =
1965 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1966 ObjCTypes.ClassPtrTy);
1967 } else {
1968 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1969 }
1970 Values[ 2] = GetClassName(ID->getIdentifier());
1971 // Version is always 0.
1972 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1973 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1974 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001975 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001976 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001977 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001978 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001979 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001980 // cache is always NULL.
1981 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1982 Values[ 9] = Protocols;
1983 // ivar_layout for metaclass is always NULL.
1984 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1985 // The class extension is always unused for metaclasses.
1986 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1987 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1988 Values);
1989
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001990 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001991 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001992
1993 // Check for a forward reference.
1994 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1995 if (GV) {
1996 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1997 "Forward metaclass reference has incorrect type.");
1998 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1999 GV->setInitializer(Init);
2000 } else {
2001 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2002 llvm::GlobalValue::InternalLinkage,
2003 Init, Name,
2004 &CGM.getModule());
2005 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002006 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002007 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002009
2010 return GV;
2011}
2012
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002013llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002014 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002015
2016 // FIXME: Should we look these up somewhere other than the
2017 // module. Its a bit silly since we only generate these while
2018 // processing an implementation, so exactly one pointer would work
2019 // if know when we entered/exitted an implementation block.
2020
2021 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002022 // Previously, metaclass with internal linkage may have been defined.
2023 // pass 'true' as 2nd argument so it is returned.
2024 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002025 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2026 "Forward metaclass reference has incorrect type.");
2027 return GV;
2028 } else {
2029 // Generate as an external reference to keep a consistent
2030 // module. This will be patched up when we emit the metaclass.
2031 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2032 llvm::GlobalValue::ExternalLinkage,
2033 0,
2034 Name,
2035 &CGM.getModule());
2036 }
2037}
2038
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002039/*
2040 struct objc_class_ext {
2041 uint32_t size;
2042 const char *weak_ivar_layout;
2043 struct _objc_property_list *properties;
2044 };
2045*/
2046llvm::Constant *
2047CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2048 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002049 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002050
2051 std::vector<llvm::Constant*> Values(3);
2052 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002053 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002054 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002055 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002056
2057 // Return null if no extension bits are used.
2058 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2059 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2060
2061 llvm::Constant *Init =
2062 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002063 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002064 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2065 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002066}
2067
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002068/// getInterfaceDeclForIvar - Get the interface declaration node where
2069/// this ivar is declared in.
2070/// FIXME. Ideally, this info should be in the ivar node. But currently
2071/// it is not and prevailing wisdom is that ASTs should not have more
2072/// info than is absolutely needed, even though this info reflects the
2073/// source language.
2074///
2075static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2076 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002077 const ObjCIvarDecl *IVD,
2078 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002079 if (!OI)
2080 return 0;
2081 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2082 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2083 E = OI->ivar_end(); I != E; ++I)
2084 if ((*I)->getIdentifier() == IVD->getIdentifier())
2085 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002086 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002087 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2088 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002089 ObjCPropertyDecl *PDecl = (*I);
2090 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2091 if (IV->getIdentifier() == IVD->getIdentifier())
2092 return OI;
2093 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002094 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002095}
2096
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002097/*
2098 struct objc_ivar {
2099 char *ivar_name;
2100 char *ivar_type;
2101 int ivar_offset;
2102 };
2103
2104 struct objc_ivar_list {
2105 int ivar_count;
2106 struct objc_ivar list[count];
2107 };
2108 */
2109llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002110 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002111 std::vector<llvm::Constant*> Ivars, Ivar(3);
2112
2113 // When emitting the root class GCC emits ivar entries for the
2114 // actual class structure. It is not clear if we need to follow this
2115 // behavior; for now lets try and get away with not doing it. If so,
2116 // the cleanest solution would be to make up an ObjCInterfaceDecl
2117 // for the class.
2118 if (ForClass)
2119 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002120
2121 ObjCInterfaceDecl *OID =
2122 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002123
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002124 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2125 GetNamedIvarList(OID, OIvars);
2126
2127 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2128 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002129 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2130 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002131 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002132 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002133 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002134 }
2135
2136 // Return null for empty list.
2137 if (Ivars.empty())
2138 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2139
2140 std::vector<llvm::Constant*> Values(2);
2141 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2142 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2143 Ivars.size());
2144 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2145 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2146
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002147 llvm::GlobalVariable *GV;
2148 if (ForClass)
2149 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002150 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2151 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002152 else
2153 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2154 + ID->getNameAsString(),
2155 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002156 4, true);
2157 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002158}
2159
2160/*
2161 struct objc_method {
2162 SEL method_name;
2163 char *method_types;
2164 void *method;
2165 };
2166
2167 struct objc_method_list {
2168 struct objc_method_list *obsolete;
2169 int count;
2170 struct objc_method methods_list[count];
2171 };
2172*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002173
2174/// GetMethodConstant - Return a struct objc_method constant for the
2175/// given method if it has been defined. The result is null if the
2176/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002177llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002178 // FIXME: Use DenseMap::lookup
2179 llvm::Function *Fn = MethodDefinitions[MD];
2180 if (!Fn)
2181 return 0;
2182
2183 std::vector<llvm::Constant*> Method(3);
2184 Method[0] =
2185 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2186 ObjCTypes.SelectorPtrTy);
2187 Method[1] = GetMethodVarType(MD);
2188 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2189 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2190}
2191
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002192llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2193 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002194 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002195 // Return null for empty list.
2196 if (Methods.empty())
2197 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2198
2199 std::vector<llvm::Constant*> Values(3);
2200 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2201 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2202 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2203 Methods.size());
2204 Values[2] = llvm::ConstantArray::get(AT, Methods);
2205 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2206
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002207 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002208 return llvm::ConstantExpr::getBitCast(GV,
2209 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002210}
2211
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002212llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002213 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002214 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002215 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002216
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002217 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002218 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002219 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002220 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002221 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002222 llvm::GlobalValue::InternalLinkage,
2223 Name,
2224 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002225 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002226
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002227 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002228}
2229
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002230/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002231uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2232 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002233 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002234 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002235 if (!OI)
2236 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002237 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002238}
2239
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002240llvm::GlobalVariable *
2241CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2242 llvm::Constant *Init,
2243 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002244 unsigned Align,
2245 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002246 const llvm::Type *Ty = Init->getType();
2247 llvm::GlobalVariable *GV =
2248 new llvm::GlobalVariable(Ty, false,
2249 llvm::GlobalValue::InternalLinkage,
2250 Init,
2251 Name,
2252 &CGM.getModule());
2253 if (Section)
2254 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002255 if (Align)
2256 GV->setAlignment(Align);
2257 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002258 UsedGlobals.push_back(GV);
2259 return GV;
2260}
2261
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002262llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002263 // Abuse this interface function as a place to finalize.
2264 FinishModule();
2265
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002266 return NULL;
2267}
2268
Chris Lattner74391b42009-03-22 21:03:39 +00002269llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002270 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002271}
2272
Chris Lattner74391b42009-03-22 21:03:39 +00002273llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002274 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002275}
2276
Chris Lattner74391b42009-03-22 21:03:39 +00002277llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002278 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002279}
2280
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002281/*
2282
2283Objective-C setjmp-longjmp (sjlj) Exception Handling
2284--
2285
2286The basic framework for a @try-catch-finally is as follows:
2287{
2288 objc_exception_data d;
2289 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002290 bool _call_try_exit = true;
2291
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002292 objc_exception_try_enter(&d);
2293 if (!setjmp(d.jmp_buf)) {
2294 ... try body ...
2295 } else {
2296 // exception path
2297 id _caught = objc_exception_extract(&d);
2298
2299 // enter new try scope for handlers
2300 if (!setjmp(d.jmp_buf)) {
2301 ... match exception and execute catch blocks ...
2302
2303 // fell off end, rethrow.
2304 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002305 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002306 } else {
2307 // exception in catch block
2308 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002309 _call_try_exit = false;
2310 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002311 }
2312 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002313 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002314
2315finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002316 if (_call_try_exit)
2317 objc_exception_try_exit(&d);
2318
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002319 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002320 ... dispatch to finally destination ...
2321
2322finally_rethrow:
2323 objc_exception_throw(_rethrow);
2324
2325finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002326}
2327
2328This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002329uses _rethrow to determine if objc_exception_try_exit should be called
2330and if the object should be rethrown. This breaks in the face of
2331throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002332
2333We specialize this framework for a few particular circumstances:
2334
2335 - If there are no catch blocks, then we avoid emitting the second
2336 exception handling context.
2337
2338 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2339 e)) we avoid emitting the code to rethrow an uncaught exception.
2340
2341 - FIXME: If there is no @finally block we can do a few more
2342 simplifications.
2343
2344Rethrows and Jumps-Through-Finally
2345--
2346
2347Support for implicit rethrows and jumping through the finally block is
2348handled by storing the current exception-handling context in
2349ObjCEHStack.
2350
Daniel Dunbar898d5082008-09-30 01:06:03 +00002351In order to implement proper @finally semantics, we support one basic
2352mechanism for jumping through the finally block to an arbitrary
2353destination. Constructs which generate exits from a @try or @catch
2354block use this mechanism to implement the proper semantics by chaining
2355jumps, as necessary.
2356
2357This mechanism works like the one used for indirect goto: we
2358arbitrarily assign an ID to each destination and store the ID for the
2359destination in a variable prior to entering the finally block. At the
2360end of the finally block we simply create a switch to the proper
2361destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002362
2363Code gen for @synchronized(expr) stmt;
2364Effectively generating code for:
2365objc_sync_enter(expr);
2366@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002367*/
2368
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002369void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2370 const Stmt &S) {
2371 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002372 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002373 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002374 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002375 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2376 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2377 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002378
2379 // For @synchronized, call objc_sync_enter(sync.expr). The
2380 // evaluation of the expression must occur before we enter the
2381 // @synchronized. We can safely avoid a temp here because jumps into
2382 // @synchronized are illegal & this will dominate uses.
2383 llvm::Value *SyncArg = 0;
2384 if (!isTry) {
2385 SyncArg =
2386 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2387 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002388 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002389 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002390
2391 // Push an EH context entry, used for handling rethrows and jumps
2392 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002393 CGF.PushCleanupBlock(FinallyBlock);
2394
Anders Carlsson273558f2009-02-07 21:37:21 +00002395 CGF.ObjCEHValueStack.push_back(0);
2396
Daniel Dunbar898d5082008-09-30 01:06:03 +00002397 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002398 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2399 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002400 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2401 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002402 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2403 "_call_try_exit");
2404 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2405
Anders Carlsson80f25672008-09-09 17:59:25 +00002406 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002407 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002408 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2409 "jmpbufarray");
2410 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002411 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002412 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002413
Daniel Dunbar55e87422008-11-11 02:29:29 +00002414 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2415 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002416 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002417 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002418
2419 // Emit the @try block.
2420 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002421 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2422 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002423 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002424
2425 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002426 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002427
2428 // Retrieve the exception object. We may emit multiple blocks but
2429 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002430 llvm::Value *Caught =
2431 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2432 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002433 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002434 if (!isTry)
2435 {
2436 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002437 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002438 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002439 }
2440 else if (const ObjCAtCatchStmt* CatchStmt =
2441 cast<ObjCAtTryStmt>(S).getCatchStmts())
2442 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002443 // Enter a new exception try block (in case a @catch block throws
2444 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002445 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002446
Chris Lattner34b02a12009-04-22 02:26:14 +00002447 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002448 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002449 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002450
Daniel Dunbar55e87422008-11-11 02:29:29 +00002451 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2452 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002453 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002454
2455 CGF.EmitBlock(CatchBlock);
2456
Daniel Dunbar55e40722008-09-27 07:03:52 +00002457 // Handle catch list. As a special case we check if everything is
2458 // matched and avoid generating code for falling off the end if
2459 // so.
2460 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002461 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002462 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002463
Steve Naroff7ba138a2009-03-03 19:52:17 +00002464 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002465 const PointerType *PT = 0;
2466
Anders Carlsson80f25672008-09-09 17:59:25 +00002467 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002468 if (!CatchParam) {
2469 AllMatched = true;
2470 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002471 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002472
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002473 // catch(id e) always matches.
2474 // FIXME: For the time being we also match id<X>; this should
2475 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002476 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002477 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002478 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002479 }
2480
Daniel Dunbar55e40722008-09-27 07:03:52 +00002481 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002482 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002483 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002484 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002485 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002486 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002487
Anders Carlssondde0a942008-09-11 09:15:33 +00002488 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002489 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002490 break;
2491 }
2492
Daniel Dunbar129271a2008-09-27 07:36:24 +00002493 assert(PT && "Unexpected non-pointer type in @catch");
2494 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002495 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002496 assert(ObjCType && "Catch parameter must have Objective-C type!");
2497
2498 // Check if the @catch block matches the exception object.
2499 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2500
Chris Lattner34b02a12009-04-22 02:26:14 +00002501 llvm::Value *Match =
2502 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2503 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002504
Daniel Dunbar55e87422008-11-11 02:29:29 +00002505 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002506
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002507 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002508 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002509
2510 // Emit the @catch block.
2511 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002512 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002513 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002514
2515 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002516 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002517 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002518 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002519
2520 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002521 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002522
2523 CGF.EmitBlock(NextCatchBlock);
2524 }
2525
Daniel Dunbar55e40722008-09-27 07:03:52 +00002526 if (!AllMatched) {
2527 // None of the handlers caught the exception, so store it to be
2528 // rethrown at the end of the @finally block.
2529 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002530 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002531 }
2532
2533 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002534 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002535 CGF.Builder.CreateStore(
2536 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2537 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002538 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002539 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002540 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002541 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002542 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002543 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002544 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002545 }
2546
Daniel Dunbar898d5082008-09-30 01:06:03 +00002547 // Pop the exception-handling stack entry. It is important to do
2548 // this now, because the code in the @finally block is not in this
2549 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002550 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2551
Anders Carlsson273558f2009-02-07 21:37:21 +00002552 CGF.ObjCEHValueStack.pop_back();
2553
Anders Carlsson80f25672008-09-09 17:59:25 +00002554 // Emit the @finally block.
2555 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002556 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2557
2558 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2559
2560 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002561 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002562
2563 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002564 if (isTry) {
2565 if (const ObjCAtFinallyStmt* FinallyStmt =
2566 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2567 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002568 } else {
2569 // Emit objc_sync_exit(expr); as finally's sole statement for
2570 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002571 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002572 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002573
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002574 // Emit the switch block
2575 if (Info.SwitchBlock)
2576 CGF.EmitBlock(Info.SwitchBlock);
2577 if (Info.EndBlock)
2578 CGF.EmitBlock(Info.EndBlock);
2579
Daniel Dunbar898d5082008-09-30 01:06:03 +00002580 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002581 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002582 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002583 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002584
2585 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002586}
2587
2588void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002589 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002590 llvm::Value *ExceptionAsObject;
2591
2592 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2593 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2594 ExceptionAsObject =
2595 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2596 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002597 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002598 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002599 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002600 }
2601
Chris Lattnerbbccd612009-04-22 02:38:11 +00002602 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002603 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002604
2605 // Clear the insertion point to indicate we are in unreachable code.
2606 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002607}
2608
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002609/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002610/// object: objc_read_weak (id *src)
2611///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002612llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002613 llvm::Value *AddrWeakObj)
2614{
Eli Friedman8339b352009-03-07 03:57:15 +00002615 const llvm::Type* DestTy =
2616 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002617 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002618 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002619 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002620 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002621 return read_weak;
2622}
2623
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002624/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2625/// objc_assign_weak (id src, id *dst)
2626///
2627void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2628 llvm::Value *src, llvm::Value *dst)
2629{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002630 const llvm::Type * SrcTy = src->getType();
2631 if (!isa<llvm::PointerType>(SrcTy)) {
2632 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2633 assert(Size <= 8 && "does not support size > 8");
2634 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2635 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002636 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2637 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002638 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2639 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002640 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002641 src, dst, "weakassign");
2642 return;
2643}
2644
Fariborz Jahanian58626502008-11-19 00:59:10 +00002645/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2646/// objc_assign_global (id src, id *dst)
2647///
2648void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2649 llvm::Value *src, llvm::Value *dst)
2650{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002651 const llvm::Type * SrcTy = src->getType();
2652 if (!isa<llvm::PointerType>(SrcTy)) {
2653 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2654 assert(Size <= 8 && "does not support size > 8");
2655 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2656 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002657 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2658 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002659 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2660 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002661 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002662 src, dst, "globalassign");
2663 return;
2664}
2665
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002666/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2667/// objc_assign_ivar (id src, id *dst)
2668///
2669void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2670 llvm::Value *src, llvm::Value *dst)
2671{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002672 const llvm::Type * SrcTy = src->getType();
2673 if (!isa<llvm::PointerType>(SrcTy)) {
2674 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2675 assert(Size <= 8 && "does not support size > 8");
2676 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2677 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002678 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2679 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002680 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2681 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002682 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002683 src, dst, "assignivar");
2684 return;
2685}
2686
Fariborz Jahanian58626502008-11-19 00:59:10 +00002687/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2688/// objc_assign_strongCast (id src, id *dst)
2689///
2690void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2691 llvm::Value *src, llvm::Value *dst)
2692{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002693 const llvm::Type * SrcTy = src->getType();
2694 if (!isa<llvm::PointerType>(SrcTy)) {
2695 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2696 assert(Size <= 8 && "does not support size > 8");
2697 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2698 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002699 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2700 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002701 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2702 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002703 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002704 src, dst, "weakassign");
2705 return;
2706}
2707
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002708/// EmitObjCValueForIvar - Code Gen for ivar reference.
2709///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002710LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2711 QualType ObjectTy,
2712 llvm::Value *BaseValue,
2713 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002714 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002715 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002716 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2717 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002718}
2719
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002720llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002721 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002722 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002723 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002724 return llvm::ConstantInt::get(
2725 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2726 Offset);
2727}
2728
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002729/* *** Private Interface *** */
2730
2731/// EmitImageInfo - Emit the image info marker used to encode some module
2732/// level information.
2733///
2734/// See: <rdr://4810609&4810587&4810587>
2735/// struct IMAGE_INFO {
2736/// unsigned version;
2737/// unsigned flags;
2738/// };
2739enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002740 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2741 // this implies.
2742 eImageInfo_GarbageCollected = (1 << 1),
2743 eImageInfo_GCOnly = (1 << 2),
2744 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2745
2746 // A flag indicating that the module has no instances of an
2747 // @synthesize of a superclass variable. <rdar://problem/6803242>
2748 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002749};
2750
2751void CGObjCMac::EmitImageInfo() {
2752 unsigned version = 0; // Version is unused?
2753 unsigned flags = 0;
2754
2755 // FIXME: Fix and continue?
2756 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2757 flags |= eImageInfo_GarbageCollected;
2758 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2759 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002760
2761 // We never allow @synthesize of a superclass property.
2762 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002763
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002764 // Emitted as int[2];
2765 llvm::Constant *values[2] = {
2766 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2767 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2768 };
2769 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002770
2771 const char *Section;
2772 if (ObjCABI == 1)
2773 Section = "__OBJC, __image_info,regular";
2774 else
2775 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002776 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002777 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2778 llvm::ConstantArray::get(AT, values, 2),
2779 Section,
2780 0,
2781 true);
2782 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002783}
2784
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002785
2786// struct objc_module {
2787// unsigned long version;
2788// unsigned long size;
2789// const char *name;
2790// Symtab symtab;
2791// };
2792
2793// FIXME: Get from somewhere
2794static const int ModuleVersion = 7;
2795
2796void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002797 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002798
2799 std::vector<llvm::Constant*> Values(4);
2800 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2801 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002802 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002803 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002804 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002805 CreateMetadataVar("\01L_OBJC_MODULES",
2806 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2807 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002808 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002809}
2810
2811llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002812 unsigned NumClasses = DefinedClasses.size();
2813 unsigned NumCategories = DefinedCategories.size();
2814
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002815 // Return null if no symbols were defined.
2816 if (!NumClasses && !NumCategories)
2817 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2818
2819 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002820 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2821 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2822 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2823 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2824
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002825 // The runtime expects exactly the list of defined classes followed
2826 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002827 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002828 for (unsigned i=0; i<NumClasses; i++)
2829 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2830 ObjCTypes.Int8PtrTy);
2831 for (unsigned i=0; i<NumCategories; i++)
2832 Symbols[NumClasses + i] =
2833 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2834 ObjCTypes.Int8PtrTy);
2835
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002836 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002837 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002838 NumClasses + NumCategories),
2839 Symbols);
2840
2841 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2842
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002843 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002844 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2845 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002846 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002847 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2848}
2849
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002850llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002851 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002852 LazySymbols.insert(ID->getIdentifier());
2853
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002854 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2855
2856 if (!Entry) {
2857 llvm::Constant *Casted =
2858 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2859 ObjCTypes.ClassPtrTy);
2860 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002861 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2862 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002863 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002864 }
2865
2866 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002867}
2868
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002869llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002870 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2871
2872 if (!Entry) {
2873 llvm::Constant *Casted =
2874 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2875 ObjCTypes.SelectorPtrTy);
2876 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002877 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2878 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002879 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002880 }
2881
2882 return Builder.CreateLoad(Entry, false, "tmp");
2883}
2884
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002885llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002886 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002887
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002888 if (!Entry)
2889 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2890 llvm::ConstantArray::get(Ident->getName()),
2891 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002892 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002893
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002894 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002895}
2896
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002897/// GetIvarLayoutName - Returns a unique constant for the given
2898/// ivar layout bitmap.
2899llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2900 const ObjCCommonTypesHelper &ObjCTypes) {
2901 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2902}
2903
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002904void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2905 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002906 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002907 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002908 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002909 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002910 bool IsUnion = (RD && RD->isUnion());
2911 uint64_t MaxUnionIvarSize = 0;
2912 uint64_t MaxSkippedUnionIvarSize = 0;
2913 FieldDecl *MaxField = 0;
2914 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002915 FieldDecl *LastFieldBitfield = 0;
2916
Chris Lattnerf1690852009-03-31 08:48:01 +00002917 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002918 if (RecFields.empty())
2919 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002920 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002921 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002922 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2923 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2924
2925 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2926
2927 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002928 FieldDecl *Field = RecFields[i];
2929 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002930 if (!Field->getIdentifier() || Field->isBitField()) {
2931 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002932 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002933 }
2934 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002935 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002936 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002937 if (FQT->isUnionType())
2938 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002939 else
2940 assert(FQT->isRecordType() &&
2941 "only union/record is supported for ivar layout bitmap");
2942
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002943 const RecordType *RT = FQT->getAsRecordType();
2944 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002945 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002946 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2947 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002948 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2949 const llvm::StructLayout *RecLayout =
2950 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2951
2952 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002953 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002954 ForStrongLayout, HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002955 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002956 continue;
2957 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002958
2959 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002960 const ConstantArrayType *CArray =
2961 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002962 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002963 assert(CArray && "only array with know element size is supported");
2964 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002965 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2966 const ConstantArrayType *CArray =
2967 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002968 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002969 FQT = CArray->getElementType();
2970 }
2971
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002972 assert(!FQT->isUnionType() &&
2973 "layout for array of unions not supported");
2974 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002975 int OldIndex = IvarsInfo.size() - 1;
2976 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002977
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002978 // FIXME - Use a common routine with the above!
2979 const RecordType *RT = FQT->getAsRecordType();
2980 const RecordDecl *RD = RT->getDecl();
2981 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002982 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2983 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002984 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2985 const llvm::StructLayout *RecLayout =
2986 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002987
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002988 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002989 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002990 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002991 ForStrongLayout, HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002992 TmpRecFields.clear();
2993
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002994 // Replicate layout information for each array element. Note that
2995 // one element is already done.
2996 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002997 for (int FirstIndex = IvarsInfo.size() - 1,
2998 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002999 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003000 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3001 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003002 GC_IVAR gcivar;
3003 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3004 gcivar.ivar_size = IvarsInfo[i].ivar_size;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003005 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003006 }
3007
Chris Lattnerf1690852009-03-31 08:48:01 +00003008 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003009 GC_IVAR skivar;
3010 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3011 skivar.ivar_size = SkipIvars[i].ivar_size;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003012 SkipIvars.push_back(skivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003013 }
3014 }
3015 continue;
3016 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003017 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003018 // At this point, we are done with Record/Union and array there of.
3019 // For other arrays we are down to its element type.
3020 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3021 do {
3022 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3023 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3024 break;
3025 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003026 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003027 GCAttr = QualType::Strong;
3028 break;
3029 }
3030 else if (const PointerType *PT = FQT->getAsPointerType()) {
3031 FQT = PT->getPointeeType();
3032 }
3033 else {
3034 break;
3035 }
3036 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003037
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003038 if ((ForStrongLayout && GCAttr == QualType::Strong)
3039 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3040 if (IsUnion)
3041 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003042 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3043 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003044 if (UnionIvarSize > MaxUnionIvarSize)
3045 {
3046 MaxUnionIvarSize = UnionIvarSize;
3047 MaxField = Field;
3048 }
3049 }
3050 else
3051 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003052 GC_IVAR gcivar;
3053 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3054 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3055 WordSizeInBits;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003056 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003057 }
3058 }
3059 else if ((ForStrongLayout &&
3060 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3061 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3062 if (IsUnion)
3063 {
3064 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3065 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3066 {
3067 MaxSkippedUnionIvarSize = UnionIvarSize;
3068 MaxSkippedField = Field;
3069 }
3070 }
3071 else
3072 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003073 GC_IVAR skivar;
3074 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3075 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003076 ByteSizeInBits;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003077 SkipIvars.push_back(skivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003078 }
3079 }
3080 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003081 if (LastFieldBitfield) {
3082 // Last field was a bitfield. Must update skip info.
3083 GC_IVAR skivar;
3084 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3085 LastFieldBitfield);
3086 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3087 uint64_t BitFieldSize =
3088 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3089 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3090 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003091 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003092 }
3093
Chris Lattnerf1690852009-03-31 08:48:01 +00003094 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003095 GC_IVAR gcivar;
3096 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3097 gcivar.ivar_size = MaxUnionIvarSize;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003098 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003099 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003100
3101 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003102 GC_IVAR skivar;
3103 skivar.ivar_bytepos = BytePos +
3104 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3105 skivar.ivar_size = MaxSkippedUnionIvarSize;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003106 SkipIvars.push_back(skivar);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003107 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003108}
3109
3110/// BuildIvarLayout - Builds ivar layout bitmap for the class
3111/// implementation for the __strong or __weak case.
3112/// The layout map displays which words in ivar list must be skipped
3113/// and which must be scanned by GC (see below). String is built of bytes.
3114/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3115/// of words to skip and right nibble is count of words to scan. So, each
3116/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3117/// represented by a 0x00 byte which also ends the string.
3118/// 1. when ForStrongLayout is true, following ivars are scanned:
3119/// - id, Class
3120/// - object *
3121/// - __strong anything
3122///
3123/// 2. When ForStrongLayout is false, following ivars are scanned:
3124/// - __weak anything
3125///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003126llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003127 const ObjCImplementationDecl *OMD,
3128 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003129 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003130
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003131 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003132 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3133 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3134 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003135
Chris Lattnerf1690852009-03-31 08:48:01 +00003136 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003137 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003138 CGM.getContext().CollectObjCIvars(OI, RecFields);
3139 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003140 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003141
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003142 SkipIvars.clear();
3143 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003144
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00003145 const llvm::StructLayout *Layout =
3146 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003147 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, hasUnion);
3148 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003149 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003150
3151 // Sort on byte position in case we encounterred a union nested in
3152 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003153 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003154 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003155 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003156 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003157
3158 // Build the string of skip/scan nibbles
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003159 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003160 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003161 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003162 if (IvarsInfo[0].ivar_bytepos == 0) {
3163 WordsToSkip = 0;
3164 WordsToScan = IvarsInfo[0].ivar_size;
3165 }
3166 else {
3167 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3168 WordsToScan = IvarsInfo[0].ivar_size;
3169 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003170 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003171 {
3172 unsigned int TailPrevGCObjC =
3173 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3174 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3175 {
3176 // consecutive 'scanned' object pointers.
3177 WordsToScan += IvarsInfo[i].ivar_size;
3178 }
3179 else
3180 {
3181 // Skip over 'gc'able object pointer which lay over each other.
3182 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3183 continue;
3184 // Must skip over 1 or more words. We save current skip/scan values
3185 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003186 SKIP_SCAN SkScan;
3187 SkScan.skip = WordsToSkip;
3188 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003189 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003190
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003191 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003192 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3193 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003194 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003195 WordsToSkip = 0;
3196 WordsToScan = IvarsInfo[i].ivar_size;
3197 }
3198 }
3199 if (WordsToScan > 0)
3200 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003201 SKIP_SCAN SkScan;
3202 SkScan.skip = WordsToSkip;
3203 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003204 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003205 }
3206
3207 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003208 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003209 {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003210 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003211 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003212 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3213 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003214 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003215 IvarsInfo[LastIndex].ivar_bytepos +
3216 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003217 BytesSkipped = (LastByteSkipped > LastByteScanned);
3218 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3219 if (BytesSkipped)
3220 {
3221 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003222 SKIP_SCAN SkScan;
3223 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3224 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003225 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003226 }
3227 }
3228 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3229 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003230 int SkipScan = SkipScanIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003231 for (int i = 0; i <= SkipScan; i++)
3232 {
3233 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3234 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3235 // 0xM0 followed by 0x0N detected.
3236 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3237 for (int j = i+1; j < SkipScan; j++)
3238 SkipScanIvars[j] = SkipScanIvars[j+1];
3239 --SkipScan;
3240 }
3241 }
3242
3243 // Generate the string.
3244 std::string BitMap;
3245 for (int i = 0; i <= SkipScan; i++)
3246 {
3247 unsigned char byte;
3248 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3249 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3250 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3251 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3252
3253 if (skip_small > 0 || skip_big > 0)
3254 BytesSkipped = true;
3255 // first skip big.
3256 for (unsigned int ix = 0; ix < skip_big; ix++)
3257 BitMap += (unsigned char)(0xf0);
3258
3259 // next (skip small, scan)
3260 if (skip_small)
3261 {
3262 byte = skip_small << 4;
3263 if (scan_big > 0)
3264 {
3265 byte |= 0xf;
3266 --scan_big;
3267 }
3268 else if (scan_small)
3269 {
3270 byte |= scan_small;
3271 scan_small = 0;
3272 }
3273 BitMap += byte;
3274 }
3275 // next scan big
3276 for (unsigned int ix = 0; ix < scan_big; ix++)
3277 BitMap += (unsigned char)(0x0f);
3278 // last scan small
3279 if (scan_small)
3280 {
3281 byte = scan_small;
3282 BitMap += byte;
3283 }
3284 }
3285 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003286 unsigned char zero = 0;
3287 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003288
3289 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3290 printf("\n%s ivar layout for class '%s': ",
3291 ForStrongLayout ? "strong" : "weak",
3292 OMD->getClassInterface()->getNameAsCString());
3293 const unsigned char *s = (unsigned char*)BitMap.c_str();
3294 for (unsigned i = 0; i < BitMap.size(); i++)
3295 if (!(s[i] & 0xf0))
3296 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3297 else
3298 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3299 printf("\n");
3300 }
3301
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003302 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3303 // final layout.
3304 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003305 return llvm::Constant::getNullValue(PtrTy);
3306 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3307 llvm::ConstantArray::get(BitMap.c_str()),
3308 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003309 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003310 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003311}
3312
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003313llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003314 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3315
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003316 // FIXME: Avoid std::string copying.
3317 if (!Entry)
3318 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3319 llvm::ConstantArray::get(Sel.getAsString()),
3320 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003321 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003322
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003323 return getConstantGEP(Entry, 0, 0);
3324}
3325
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003326// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003327llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003328 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3329}
3330
3331// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003332llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003333 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3334}
3335
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003336llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003337 std::string TypeStr;
3338 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3339
3340 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003341
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003342 if (!Entry)
3343 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3344 llvm::ConstantArray::get(TypeStr),
3345 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003346 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003347
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003348 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003349}
3350
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003351llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003352 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003353 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3354 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003355
3356 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3357
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003358 if (!Entry)
3359 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3360 llvm::ConstantArray::get(TypeStr),
3361 "__TEXT,__cstring,cstring_literals",
3362 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003363
3364 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003365}
3366
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003367// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003368llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003369 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3370
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003371 if (!Entry)
3372 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3373 llvm::ConstantArray::get(Ident->getName()),
3374 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003375 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003376
3377 return getConstantGEP(Entry, 0, 0);
3378}
3379
3380// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003381// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003382llvm::Constant *
3383 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3384 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003385 std::string TypeStr;
3386 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003387 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3388}
3389
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003390void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3391 const ObjCContainerDecl *CD,
3392 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003393 NameOut = '\01';
3394 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003395 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003396 assert (CD && "Missing container decl in GetNameForMethod");
3397 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003398 if (const ObjCCategoryImplDecl *CID =
3399 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3400 NameOut += '(';
3401 NameOut += CID->getNameAsString();
3402 NameOut+= ')';
3403 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003404 NameOut += ' ';
3405 NameOut += D->getSelector().getAsString();
3406 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003407}
3408
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003409void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003410 EmitModuleInfo();
3411
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003412 // Emit the dummy bodies for any protocols which were referenced but
3413 // never defined.
3414 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3415 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3416 if (i->second->hasInitializer())
3417 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003418
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003419 std::vector<llvm::Constant*> Values(5);
3420 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3421 Values[1] = GetClassName(i->first);
3422 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3423 Values[3] = Values[4] =
3424 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3425 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3426 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3427 Values));
3428 }
3429
3430 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003431 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003432 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003433 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003434 }
3435
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003436 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003437 llvm::GlobalValue *GV =
3438 new llvm::GlobalVariable(AT, false,
3439 llvm::GlobalValue::AppendingLinkage,
3440 llvm::ConstantArray::get(AT, Used),
3441 "llvm.used",
3442 &CGM.getModule());
3443
3444 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003445
3446 // Add assembler directives to add lazy undefined symbol references
3447 // for classes which are referenced but not defined. This is
3448 // important for correct linker interaction.
3449
3450 // FIXME: Uh, this isn't particularly portable.
3451 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003452
3453 if (!CGM.getModule().getModuleInlineAsm().empty())
3454 s << "\n";
3455
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003456 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3457 e = LazySymbols.end(); i != e; ++i) {
3458 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3459 }
3460 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3461 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003462 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003463 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3464 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003465
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003466 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003467}
3468
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003469CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003470 : CGObjCCommonMac(cgm),
3471 ObjCTypes(cgm)
3472{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003473 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003474 ObjCABI = 2;
3475}
3476
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003477/* *** */
3478
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003479ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3480: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003481{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003482 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3483 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003484
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003485 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003486 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003487 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003488 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003489 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3490
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003491 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003492 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003493 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003494
3495 // FIXME: It would be nice to unify this with the opaque type, so
3496 // that the IR comes out a bit cleaner.
3497 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3498 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003499
3500 // I'm not sure I like this. The implicit coordination is a bit
3501 // gross. We should solve this in a reasonable fashion because this
3502 // is a pretty common task (match some runtime data structure with
3503 // an LLVM data structure).
3504
3505 // FIXME: This is leaked.
3506 // FIXME: Merge with rewriter code?
3507
3508 // struct _objc_super {
3509 // id self;
3510 // Class cls;
3511 // }
3512 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3513 SourceLocation(),
3514 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003515 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3516 Ctx.getObjCIdType(), 0, false));
3517 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3518 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003519 RD->completeDefinition(Ctx);
3520
3521 SuperCTy = Ctx.getTagDeclType(RD);
3522 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3523
3524 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003525 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3526
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003527 // struct _prop_t {
3528 // char *name;
3529 // char *attributes;
3530 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003531 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003532 CGM.getModule().addTypeName("struct._prop_t",
3533 PropertyTy);
3534
3535 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003536 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003537 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003538 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003539 // }
3540 PropertyListTy = llvm::StructType::get(IntTy,
3541 IntTy,
3542 llvm::ArrayType::get(PropertyTy, 0),
3543 NULL);
3544 CGM.getModule().addTypeName("struct._prop_list_t",
3545 PropertyListTy);
3546 // struct _prop_list_t *
3547 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3548
3549 // struct _objc_method {
3550 // SEL _cmd;
3551 // char *method_type;
3552 // char *_imp;
3553 // }
3554 MethodTy = llvm::StructType::get(SelectorPtrTy,
3555 Int8PtrTy,
3556 Int8PtrTy,
3557 NULL);
3558 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003559
3560 // struct _objc_cache *
3561 CacheTy = llvm::OpaqueType::get();
3562 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3563 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003564}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003565
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003566ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3567 : ObjCCommonTypesHelper(cgm)
3568{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003569 // struct _objc_method_description {
3570 // SEL name;
3571 // char *types;
3572 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003573 MethodDescriptionTy =
3574 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003575 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003576 NULL);
3577 CGM.getModule().addTypeName("struct._objc_method_description",
3578 MethodDescriptionTy);
3579
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003580 // struct _objc_method_description_list {
3581 // int count;
3582 // struct _objc_method_description[1];
3583 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003584 MethodDescriptionListTy =
3585 llvm::StructType::get(IntTy,
3586 llvm::ArrayType::get(MethodDescriptionTy, 0),
3587 NULL);
3588 CGM.getModule().addTypeName("struct._objc_method_description_list",
3589 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003590
3591 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003592 MethodDescriptionListPtrTy =
3593 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3594
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003595 // Protocol description structures
3596
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003597 // struct _objc_protocol_extension {
3598 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3599 // struct _objc_method_description_list *optional_instance_methods;
3600 // struct _objc_method_description_list *optional_class_methods;
3601 // struct _objc_property_list *instance_properties;
3602 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003603 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003604 llvm::StructType::get(IntTy,
3605 MethodDescriptionListPtrTy,
3606 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003607 PropertyListPtrTy,
3608 NULL);
3609 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3610 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003611
3612 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003613 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3614
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003615 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003616
3617 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3618 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3619
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003620 const llvm::Type *T =
3621 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3622 LongTy,
3623 llvm::ArrayType::get(ProtocolTyHolder, 0),
3624 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003625 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3626
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003627 // struct _objc_protocol {
3628 // struct _objc_protocol_extension *isa;
3629 // char *protocol_name;
3630 // struct _objc_protocol **_objc_protocol_list;
3631 // struct _objc_method_description_list *instance_methods;
3632 // struct _objc_method_description_list *class_methods;
3633 // }
3634 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003635 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003636 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3637 MethodDescriptionListPtrTy,
3638 MethodDescriptionListPtrTy,
3639 NULL);
3640 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3641
3642 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3643 CGM.getModule().addTypeName("struct._objc_protocol_list",
3644 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003645 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003646 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3647
3648 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003649 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003650 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003651
3652 // Class description structures
3653
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003654 // struct _objc_ivar {
3655 // char *ivar_name;
3656 // char *ivar_type;
3657 // int ivar_offset;
3658 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003659 IvarTy = llvm::StructType::get(Int8PtrTy,
3660 Int8PtrTy,
3661 IntTy,
3662 NULL);
3663 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3664
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003665 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003666 IvarListTy = llvm::OpaqueType::get();
3667 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3668 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3669
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003670 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003671 MethodListTy = llvm::OpaqueType::get();
3672 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3673 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3674
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003675 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003676 ClassExtensionTy =
3677 llvm::StructType::get(IntTy,
3678 Int8PtrTy,
3679 PropertyListPtrTy,
3680 NULL);
3681 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3682 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3683
3684 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3685
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003686 // struct _objc_class {
3687 // Class isa;
3688 // Class super_class;
3689 // char *name;
3690 // long version;
3691 // long info;
3692 // long instance_size;
3693 // struct _objc_ivar_list *ivars;
3694 // struct _objc_method_list *methods;
3695 // struct _objc_cache *cache;
3696 // struct _objc_protocol_list *protocols;
3697 // char *ivar_layout;
3698 // struct _objc_class_ext *ext;
3699 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003700 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3701 llvm::PointerType::getUnqual(ClassTyHolder),
3702 Int8PtrTy,
3703 LongTy,
3704 LongTy,
3705 LongTy,
3706 IvarListPtrTy,
3707 MethodListPtrTy,
3708 CachePtrTy,
3709 ProtocolListPtrTy,
3710 Int8PtrTy,
3711 ClassExtensionPtrTy,
3712 NULL);
3713 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3714
3715 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3716 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3717 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3718
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003719 // struct _objc_category {
3720 // char *category_name;
3721 // char *class_name;
3722 // struct _objc_method_list *instance_method;
3723 // struct _objc_method_list *class_method;
3724 // uint32_t size; // sizeof(struct _objc_category)
3725 // struct _objc_property_list *instance_properties;// category's @property
3726 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003727 CategoryTy = llvm::StructType::get(Int8PtrTy,
3728 Int8PtrTy,
3729 MethodListPtrTy,
3730 MethodListPtrTy,
3731 ProtocolListPtrTy,
3732 IntTy,
3733 PropertyListPtrTy,
3734 NULL);
3735 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3736
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003737 // Global metadata structures
3738
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003739 // struct _objc_symtab {
3740 // long sel_ref_cnt;
3741 // SEL *refs;
3742 // short cls_def_cnt;
3743 // short cat_def_cnt;
3744 // char *defs[cls_def_cnt + cat_def_cnt];
3745 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003746 SymtabTy = llvm::StructType::get(LongTy,
3747 SelectorPtrTy,
3748 ShortTy,
3749 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003750 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003751 NULL);
3752 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3753 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3754
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003755 // struct _objc_module {
3756 // long version;
3757 // long size; // sizeof(struct _objc_module)
3758 // char *name;
3759 // struct _objc_symtab* symtab;
3760 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003761 ModuleTy =
3762 llvm::StructType::get(LongTy,
3763 LongTy,
3764 Int8PtrTy,
3765 SymtabPtrTy,
3766 NULL);
3767 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003768
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003769
Anders Carlsson124526b2008-09-09 10:10:21 +00003770 // FIXME: This is the size of the setjmp buffer and should be
3771 // target specific. 18 is what's used on 32-bit X86.
3772 uint64_t SetJmpBufferSize = 18;
3773
3774 // Exceptions
3775 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003776 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003777
3778 ExceptionDataTy =
3779 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3780 SetJmpBufferSize),
3781 StackPtrTy, NULL);
3782 CGM.getModule().addTypeName("struct._objc_exception_data",
3783 ExceptionDataTy);
3784
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003785}
3786
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003787ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003788: ObjCCommonTypesHelper(cgm)
3789{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003790 // struct _method_list_t {
3791 // uint32_t entsize; // sizeof(struct _objc_method)
3792 // uint32_t method_count;
3793 // struct _objc_method method_list[method_count];
3794 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003795 MethodListnfABITy = llvm::StructType::get(IntTy,
3796 IntTy,
3797 llvm::ArrayType::get(MethodTy, 0),
3798 NULL);
3799 CGM.getModule().addTypeName("struct.__method_list_t",
3800 MethodListnfABITy);
3801 // struct method_list_t *
3802 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003803
3804 // struct _protocol_t {
3805 // id isa; // NULL
3806 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003807 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003808 // const struct method_list_t * const instance_methods;
3809 // const struct method_list_t * const class_methods;
3810 // const struct method_list_t *optionalInstanceMethods;
3811 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003812 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003813 // const uint32_t size; // sizeof(struct _protocol_t)
3814 // const uint32_t flags; // = 0
3815 // }
3816
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003817 // Holder for struct _protocol_list_t *
3818 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3819
3820 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3821 Int8PtrTy,
3822 llvm::PointerType::getUnqual(
3823 ProtocolListTyHolder),
3824 MethodListnfABIPtrTy,
3825 MethodListnfABIPtrTy,
3826 MethodListnfABIPtrTy,
3827 MethodListnfABIPtrTy,
3828 PropertyListPtrTy,
3829 IntTy,
3830 IntTy,
3831 NULL);
3832 CGM.getModule().addTypeName("struct._protocol_t",
3833 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003834
3835 // struct _protocol_t*
3836 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003837
Fariborz Jahanianda320092009-01-29 19:24:30 +00003838 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003839 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003840 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003841 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003842 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3843 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003844 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003845 NULL);
3846 CGM.getModule().addTypeName("struct._objc_protocol_list",
3847 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003848 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3849 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003850
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003851 // struct _objc_protocol_list*
3852 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003853
3854 // struct _ivar_t {
3855 // unsigned long int *offset; // pointer to ivar offset location
3856 // char *name;
3857 // char *type;
3858 // uint32_t alignment;
3859 // uint32_t size;
3860 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003861 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3862 Int8PtrTy,
3863 Int8PtrTy,
3864 IntTy,
3865 IntTy,
3866 NULL);
3867 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3868
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003869 // struct _ivar_list_t {
3870 // uint32 entsize; // sizeof(struct _ivar_t)
3871 // uint32 count;
3872 // struct _iver_t list[count];
3873 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003874 IvarListnfABITy = llvm::StructType::get(IntTy,
3875 IntTy,
3876 llvm::ArrayType::get(
3877 IvarnfABITy, 0),
3878 NULL);
3879 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3880
3881 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003882
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003883 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003884 // uint32_t const flags;
3885 // uint32_t const instanceStart;
3886 // uint32_t const instanceSize;
3887 // uint32_t const reserved; // only when building for 64bit targets
3888 // const uint8_t * const ivarLayout;
3889 // const char *const name;
3890 // const struct _method_list_t * const baseMethods;
3891 // const struct _objc_protocol_list *const baseProtocols;
3892 // const struct _ivar_list_t *const ivars;
3893 // const uint8_t * const weakIvarLayout;
3894 // const struct _prop_list_t * const properties;
3895 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003896
3897 // FIXME. Add 'reserved' field in 64bit abi mode!
3898 ClassRonfABITy = llvm::StructType::get(IntTy,
3899 IntTy,
3900 IntTy,
3901 Int8PtrTy,
3902 Int8PtrTy,
3903 MethodListnfABIPtrTy,
3904 ProtocolListnfABIPtrTy,
3905 IvarListnfABIPtrTy,
3906 Int8PtrTy,
3907 PropertyListPtrTy,
3908 NULL);
3909 CGM.getModule().addTypeName("struct._class_ro_t",
3910 ClassRonfABITy);
3911
3912 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3913 std::vector<const llvm::Type*> Params;
3914 Params.push_back(ObjectPtrTy);
3915 Params.push_back(SelectorPtrTy);
3916 ImpnfABITy = llvm::PointerType::getUnqual(
3917 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3918
3919 // struct _class_t {
3920 // struct _class_t *isa;
3921 // struct _class_t * const superclass;
3922 // void *cache;
3923 // IMP *vtable;
3924 // struct class_ro_t *ro;
3925 // }
3926
3927 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3928 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3929 llvm::PointerType::getUnqual(ClassTyHolder),
3930 CachePtrTy,
3931 llvm::PointerType::getUnqual(ImpnfABITy),
3932 llvm::PointerType::getUnqual(
3933 ClassRonfABITy),
3934 NULL);
3935 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3936
3937 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3938 ClassnfABITy);
3939
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003940 // LLVM for struct _class_t *
3941 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3942
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003943 // struct _category_t {
3944 // const char * const name;
3945 // struct _class_t *const cls;
3946 // const struct _method_list_t * const instance_methods;
3947 // const struct _method_list_t * const class_methods;
3948 // const struct _protocol_list_t * const protocols;
3949 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003950 // }
3951 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003952 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003953 MethodListnfABIPtrTy,
3954 MethodListnfABIPtrTy,
3955 ProtocolListnfABIPtrTy,
3956 PropertyListPtrTy,
3957 NULL);
3958 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003959
3960 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003961 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3962 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003963
3964 // MessageRefTy - LLVM for:
3965 // struct _message_ref_t {
3966 // IMP messenger;
3967 // SEL name;
3968 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003969
3970 // First the clang type for struct _message_ref_t
3971 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3972 SourceLocation(),
3973 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003974 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3975 Ctx.VoidPtrTy, 0, false));
3976 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3977 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003978 RD->completeDefinition(Ctx);
3979
3980 MessageRefCTy = Ctx.getTagDeclType(RD);
3981 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3982 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003983
3984 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3985 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3986
3987 // SuperMessageRefTy - LLVM for:
3988 // struct _super_message_ref_t {
3989 // SUPER_IMP messenger;
3990 // SEL name;
3991 // };
3992 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3993 SelectorPtrTy,
3994 NULL);
3995 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3996
3997 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3998 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3999
Daniel Dunbare588b992009-03-01 04:46:24 +00004000
4001 // struct objc_typeinfo {
4002 // const void** vtable; // objc_ehtype_vtable + 2
4003 // const char* name; // c++ typeinfo string
4004 // Class cls;
4005 // };
4006 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4007 Int8PtrTy,
4008 ClassnfABIPtrTy,
4009 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004010 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004011 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004012}
4013
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004014llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4015 FinishNonFragileABIModule();
4016
4017 return NULL;
4018}
4019
4020void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4021 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004022
4023 // Build list of all implemented classe addresses in array
4024 // L_OBJC_LABEL_CLASS_$.
4025 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4026 // list of 'nonlazy' implementations (defined as those with a +load{}
4027 // method!!).
4028 unsigned NumClasses = DefinedClasses.size();
4029 if (NumClasses) {
4030 std::vector<llvm::Constant*> Symbols(NumClasses);
4031 for (unsigned i=0; i<NumClasses; i++)
4032 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4033 ObjCTypes.Int8PtrTy);
4034 llvm::Constant* Init =
4035 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4036 NumClasses),
4037 Symbols);
4038
4039 llvm::GlobalVariable *GV =
4040 new llvm::GlobalVariable(Init->getType(), false,
4041 llvm::GlobalValue::InternalLinkage,
4042 Init,
4043 "\01L_OBJC_LABEL_CLASS_$",
4044 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004045 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004046 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4047 UsedGlobals.push_back(GV);
4048 }
4049
4050 // Build list of all implemented category addresses in array
4051 // L_OBJC_LABEL_CATEGORY_$.
4052 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4053 // list of 'nonlazy' category implementations (defined as those with a +load{}
4054 // method!!).
4055 unsigned NumCategory = DefinedCategories.size();
4056 if (NumCategory) {
4057 std::vector<llvm::Constant*> Symbols(NumCategory);
4058 for (unsigned i=0; i<NumCategory; i++)
4059 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4060 ObjCTypes.Int8PtrTy);
4061 llvm::Constant* Init =
4062 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4063 NumCategory),
4064 Symbols);
4065
4066 llvm::GlobalVariable *GV =
4067 new llvm::GlobalVariable(Init->getType(), false,
4068 llvm::GlobalValue::InternalLinkage,
4069 Init,
4070 "\01L_OBJC_LABEL_CATEGORY_$",
4071 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004072 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004073 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4074 UsedGlobals.push_back(GV);
4075 }
4076
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004077 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4078 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4079 std::vector<llvm::Constant*> Values(2);
4080 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004081 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004082 // FIXME: Fix and continue?
4083 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4084 flags |= eImageInfo_GarbageCollected;
4085 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4086 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004087 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004088 llvm::Constant* Init = llvm::ConstantArray::get(
4089 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4090 Values);
4091 llvm::GlobalVariable *IMGV =
4092 new llvm::GlobalVariable(Init->getType(), false,
4093 llvm::GlobalValue::InternalLinkage,
4094 Init,
4095 "\01L_OBJC_IMAGE_INFO",
4096 &CGM.getModule());
4097 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004098 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004099 UsedGlobals.push_back(IMGV);
4100
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004101 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004102
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004103 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4104 e = UsedGlobals.end(); i != e; ++i) {
4105 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4106 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004107
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004108 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4109 llvm::GlobalValue *GV =
4110 new llvm::GlobalVariable(AT, false,
4111 llvm::GlobalValue::AppendingLinkage,
4112 llvm::ConstantArray::get(AT, Used),
4113 "llvm.used",
4114 &CGM.getModule());
4115
4116 GV->setSection("llvm.metadata");
4117
4118}
4119
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004120// Metadata flags
4121enum MetaDataDlags {
4122 CLS = 0x0,
4123 CLS_META = 0x1,
4124 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004125 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004126 CLS_EXCEPTION = 0x20
4127};
4128/// BuildClassRoTInitializer - generate meta-data for:
4129/// struct _class_ro_t {
4130/// uint32_t const flags;
4131/// uint32_t const instanceStart;
4132/// uint32_t const instanceSize;
4133/// uint32_t const reserved; // only when building for 64bit targets
4134/// const uint8_t * const ivarLayout;
4135/// const char *const name;
4136/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004137/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004138/// const struct _ivar_list_t *const ivars;
4139/// const uint8_t * const weakIvarLayout;
4140/// const struct _prop_list_t * const properties;
4141/// }
4142///
4143llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4144 unsigned flags,
4145 unsigned InstanceStart,
4146 unsigned InstanceSize,
4147 const ObjCImplementationDecl *ID) {
4148 std::string ClassName = ID->getNameAsString();
4149 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4150 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4151 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4152 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4153 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004154 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4155 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004156 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004157 // const struct _method_list_t * const baseMethods;
4158 std::vector<llvm::Constant*> Methods;
4159 std::string MethodListName("\01l_OBJC_$_");
4160 if (flags & CLS_META) {
4161 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004162 for (ObjCImplementationDecl::classmeth_iterator
4163 i = ID->classmeth_begin(CGM.getContext()),
4164 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004165 // Class methods should always be defined.
4166 Methods.push_back(GetMethodConstant(*i));
4167 }
4168 } else {
4169 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004170 for (ObjCImplementationDecl::instmeth_iterator
4171 i = ID->instmeth_begin(CGM.getContext()),
4172 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004173 // Instance methods should always be defined.
4174 Methods.push_back(GetMethodConstant(*i));
4175 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004176 for (ObjCImplementationDecl::propimpl_iterator
4177 i = ID->propimpl_begin(CGM.getContext()),
4178 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004179 ObjCPropertyImplDecl *PID = *i;
4180
4181 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4182 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4183
4184 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4185 if (llvm::Constant *C = GetMethodConstant(MD))
4186 Methods.push_back(C);
4187 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4188 if (llvm::Constant *C = GetMethodConstant(MD))
4189 Methods.push_back(C);
4190 }
4191 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004192 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004193 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004194 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004195
4196 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4197 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4198 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4199 + OID->getNameAsString(),
4200 OID->protocol_begin(),
4201 OID->protocol_end());
4202
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004203 if (flags & CLS_META)
4204 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4205 else
4206 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004207 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4208 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004209 if (flags & CLS_META)
4210 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4211 else
4212 Values[ 9] =
4213 EmitPropertyList(
4214 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4215 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004216 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4217 Values);
4218 llvm::GlobalVariable *CLASS_RO_GV =
4219 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4220 llvm::GlobalValue::InternalLinkage,
4221 Init,
4222 (flags & CLS_META) ?
4223 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4224 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4225 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004226 CLASS_RO_GV->setAlignment(
4227 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004228 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004229 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004230
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004231}
4232
4233/// BuildClassMetaData - This routine defines that to-level meta-data
4234/// for the given ClassName for:
4235/// struct _class_t {
4236/// struct _class_t *isa;
4237/// struct _class_t * const superclass;
4238/// void *cache;
4239/// IMP *vtable;
4240/// struct class_ro_t *ro;
4241/// }
4242///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004243llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4244 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004245 llvm::Constant *IsAGV,
4246 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004247 llvm::Constant *ClassRoGV,
4248 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004249 std::vector<llvm::Constant*> Values(5);
4250 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004251 Values[1] = SuperClassGV
4252 ? SuperClassGV
4253 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004254 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4255 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4256 Values[4] = ClassRoGV; // &CLASS_RO_GV
4257 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4258 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004259 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4260 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004261 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004262 GV->setAlignment(
4263 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004264 if (HiddenVisibility)
4265 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004266 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004267}
4268
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004269void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4270 uint32_t &InstanceStart,
4271 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004272 // Find first and last (non-padding) ivars in this interface.
4273
4274 // FIXME: Use iterator.
4275 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4276 GetNamedIvarList(OID, OIvars);
4277
4278 if (OIvars.empty()) {
4279 InstanceStart = InstanceSize = 0;
4280 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004281 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004282
4283 const ObjCIvarDecl *First = OIvars.front();
4284 const ObjCIvarDecl *Last = OIvars.back();
4285
4286 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4287 const llvm::Type *FieldTy =
4288 CGM.getTypes().ConvertTypeForMem(Last->getType());
4289 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004290// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4291// with gcc-4.2). We postpone this for now.
4292#if 0
4293 if (Last->isBitField()) {
4294 Expr *BitWidth = Last->getBitWidth();
4295 uint64_t BitFieldSize =
4296 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
4297 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4298 }
4299#endif
Daniel Dunbar97776872009-04-22 07:32:20 +00004300 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004301}
4302
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004303void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4304 std::string ClassName = ID->getNameAsString();
4305 if (!ObjCEmptyCacheVar) {
4306 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004307 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004308 false,
4309 llvm::GlobalValue::ExternalLinkage,
4310 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004311 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004312 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004313
4314 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004315 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004316 false,
4317 llvm::GlobalValue::ExternalLinkage,
4318 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004319 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004320 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004321 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004322 assert(ID->getClassInterface() &&
4323 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004324 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004325 uint32_t InstanceStart =
4326 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4327 uint32_t InstanceSize = InstanceStart;
4328 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004329 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4330 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004331
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004332 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004333
Daniel Dunbar04d40782009-04-14 06:00:08 +00004334 bool classIsHidden =
4335 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004336 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004337 flags |= OBJC2_CLS_HIDDEN;
4338 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004339 // class is root
4340 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004341 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004342 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004343 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004344 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004345 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4346 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4347 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004348 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004349 // work on super class metadata symbol.
4350 std::string SuperClassName =
4351 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004352 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004353 }
4354 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4355 InstanceStart,
4356 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004357 std::string TClassName = ObjCMetaClassName + ClassName;
4358 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004359 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4360 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004361
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004362 // Metadata for the class
4363 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004364 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004365 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004366
4367 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4368 flags |= CLS_EXCEPTION;
4369
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004370 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004371 flags |= CLS_ROOT;
4372 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004373 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004374 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004375 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004376 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004377 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004378 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004379 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004380 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004381 InstanceStart,
4382 InstanceSize,
4383 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004384
4385 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004386 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004387 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4388 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004389 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004390
4391 // Force the definition of the EHType if necessary.
4392 if (flags & CLS_EXCEPTION)
4393 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004394}
4395
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004396/// GenerateProtocolRef - This routine is called to generate code for
4397/// a protocol reference expression; as in:
4398/// @code
4399/// @protocol(Proto1);
4400/// @endcode
4401/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4402/// which will hold address of the protocol meta-data.
4403///
4404llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4405 const ObjCProtocolDecl *PD) {
4406
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004407 // This routine is called for @protocol only. So, we must build definition
4408 // of protocol's meta-data (not a reference to it!)
4409 //
4410 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004411 ObjCTypes.ExternalProtocolPtrTy);
4412
4413 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4414 ProtocolName += PD->getNameAsCString();
4415
4416 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4417 if (PTGV)
4418 return Builder.CreateLoad(PTGV, false, "tmp");
4419 PTGV = new llvm::GlobalVariable(
4420 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004421 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004422 Init,
4423 ProtocolName,
4424 &CGM.getModule());
4425 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4426 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4427 UsedGlobals.push_back(PTGV);
4428 return Builder.CreateLoad(PTGV, false, "tmp");
4429}
4430
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004431/// GenerateCategory - Build metadata for a category implementation.
4432/// struct _category_t {
4433/// const char * const name;
4434/// struct _class_t *const cls;
4435/// const struct _method_list_t * const instance_methods;
4436/// const struct _method_list_t * const class_methods;
4437/// const struct _protocol_list_t * const protocols;
4438/// const struct _prop_list_t * const properties;
4439/// }
4440///
4441void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4442{
4443 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004444 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4445 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004446 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004447 std::string ExtClassName(getClassSymbolPrefix() +
4448 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004449
4450 std::vector<llvm::Constant*> Values(6);
4451 Values[0] = GetClassName(OCD->getIdentifier());
4452 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004453 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004454 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004455 std::vector<llvm::Constant*> Methods;
4456 std::string MethodListName(Prefix);
4457 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4458 "_$_" + OCD->getNameAsString();
4459
Douglas Gregor653f1b12009-04-23 01:02:12 +00004460 for (ObjCCategoryImplDecl::instmeth_iterator
4461 i = OCD->instmeth_begin(CGM.getContext()),
4462 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004463 // Instance methods should always be defined.
4464 Methods.push_back(GetMethodConstant(*i));
4465 }
4466
4467 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004468 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004469 Methods);
4470
4471 MethodListName = Prefix;
4472 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4473 OCD->getNameAsString();
4474 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004475 for (ObjCCategoryImplDecl::classmeth_iterator
4476 i = OCD->classmeth_begin(CGM.getContext()),
4477 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004478 // Class methods should always be defined.
4479 Methods.push_back(GetMethodConstant(*i));
4480 }
4481
4482 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004483 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004484 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004485 const ObjCCategoryDecl *Category =
4486 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004487 if (Category) {
4488 std::string ExtName(Interface->getNameAsString() + "_$_" +
4489 OCD->getNameAsString());
4490 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4491 + Interface->getNameAsString() + "_$_"
4492 + Category->getNameAsString(),
4493 Category->protocol_begin(),
4494 Category->protocol_end());
4495 Values[5] =
4496 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4497 OCD, Category, ObjCTypes);
4498 }
4499 else {
4500 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4501 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4502 }
4503
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004504 llvm::Constant *Init =
4505 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4506 Values);
4507 llvm::GlobalVariable *GCATV
4508 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4509 false,
4510 llvm::GlobalValue::InternalLinkage,
4511 Init,
4512 ExtCatName,
4513 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004514 GCATV->setAlignment(
4515 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004516 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004517 UsedGlobals.push_back(GCATV);
4518 DefinedCategories.push_back(GCATV);
4519}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004520
4521/// GetMethodConstant - Return a struct objc_method constant for the
4522/// given method if it has been defined. The result is null if the
4523/// method has not been defined. The return value has type MethodPtrTy.
4524llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4525 const ObjCMethodDecl *MD) {
4526 // FIXME: Use DenseMap::lookup
4527 llvm::Function *Fn = MethodDefinitions[MD];
4528 if (!Fn)
4529 return 0;
4530
4531 std::vector<llvm::Constant*> Method(3);
4532 Method[0] =
4533 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4534 ObjCTypes.SelectorPtrTy);
4535 Method[1] = GetMethodVarType(MD);
4536 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4537 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4538}
4539
4540/// EmitMethodList - Build meta-data for method declarations
4541/// struct _method_list_t {
4542/// uint32_t entsize; // sizeof(struct _objc_method)
4543/// uint32_t method_count;
4544/// struct _objc_method method_list[method_count];
4545/// }
4546///
4547llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4548 const std::string &Name,
4549 const char *Section,
4550 const ConstantVector &Methods) {
4551 // Return null for empty list.
4552 if (Methods.empty())
4553 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4554
4555 std::vector<llvm::Constant*> Values(3);
4556 // sizeof(struct _objc_method)
4557 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4558 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4559 // method_count
4560 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4561 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4562 Methods.size());
4563 Values[2] = llvm::ConstantArray::get(AT, Methods);
4564 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4565
4566 llvm::GlobalVariable *GV =
4567 new llvm::GlobalVariable(Init->getType(), false,
4568 llvm::GlobalValue::InternalLinkage,
4569 Init,
4570 Name,
4571 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004572 GV->setAlignment(
4573 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004574 GV->setSection(Section);
4575 UsedGlobals.push_back(GV);
4576 return llvm::ConstantExpr::getBitCast(GV,
4577 ObjCTypes.MethodListnfABIPtrTy);
4578}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004579
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004580/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4581/// the given ivar.
4582///
4583llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004584 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004585 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004586 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004587 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4588 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004589 llvm::GlobalVariable *IvarOffsetGV =
4590 CGM.getModule().getGlobalVariable(Name);
4591 if (!IvarOffsetGV)
4592 IvarOffsetGV =
4593 new llvm::GlobalVariable(ObjCTypes.LongTy,
4594 false,
4595 llvm::GlobalValue::ExternalLinkage,
4596 0,
4597 Name,
4598 &CGM.getModule());
4599 return IvarOffsetGV;
4600}
4601
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004602llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004603 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004604 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004605 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004606 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4607 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4608 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004609 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004610 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004611
4612 // FIXME: This matches gcc, but shouldn't the visibility be set on
4613 // the use as well (i.e., in ObjCIvarOffsetVariable).
4614 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4615 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4616 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004617 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004618 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004619 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004620 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004621 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004622}
4623
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004624/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004625/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004626/// IvarListnfABIPtrTy.
4627/// struct _ivar_t {
4628/// unsigned long int *offset; // pointer to ivar offset location
4629/// char *name;
4630/// char *type;
4631/// uint32_t alignment;
4632/// uint32_t size;
4633/// }
4634/// struct _ivar_list_t {
4635/// uint32 entsize; // sizeof(struct _ivar_t)
4636/// uint32 count;
4637/// struct _iver_t list[count];
4638/// }
4639///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004640
4641void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4642 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4643 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4644 E = OID->ivar_end(); I != E; ++I) {
4645 // Ignore unnamed bit-fields.
4646 if (!(*I)->getDeclName())
4647 continue;
4648
4649 Res.push_back(*I);
4650 }
4651
4652 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4653 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4654 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4655 Res.push_back(IV);
4656}
4657
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004658llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4659 const ObjCImplementationDecl *ID) {
4660
4661 std::vector<llvm::Constant*> Ivars, Ivar(5);
4662
4663 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4664 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4665
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004666 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004667
Daniel Dunbar91636d62009-04-20 00:33:43 +00004668 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004669 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004670 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004671
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004672 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4673 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004674 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004675 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004676 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4677 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004678 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004679 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004680 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4681 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004682 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004683 Align = llvm::Log2_32(Align);
4684 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004685 // NOTE. Size of a bitfield does not match gcc's, because of the
4686 // way bitfields are treated special in each. But I am told that
4687 // 'size' for bitfield ivars is ignored by the runtime so it does
4688 // not matter. If it matters, there is enough info to get the
4689 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004690 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4691 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4692 }
4693 // Return null for empty list.
4694 if (Ivars.empty())
4695 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4696 std::vector<llvm::Constant*> Values(3);
4697 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4698 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4699 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4700 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4701 Ivars.size());
4702 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4703 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4704 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4705 llvm::GlobalVariable *GV =
4706 new llvm::GlobalVariable(Init->getType(), false,
4707 llvm::GlobalValue::InternalLinkage,
4708 Init,
4709 Prefix + OID->getNameAsString(),
4710 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004711 GV->setAlignment(
4712 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004713 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004714
4715 UsedGlobals.push_back(GV);
4716 return llvm::ConstantExpr::getBitCast(GV,
4717 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004718}
4719
4720llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4721 const ObjCProtocolDecl *PD) {
4722 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4723
4724 if (!Entry) {
4725 // We use the initializer as a marker of whether this is a forward
4726 // reference or not. At module finalization we add the empty
4727 // contents for protocols which were referenced but never defined.
4728 Entry =
4729 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4730 llvm::GlobalValue::ExternalLinkage,
4731 0,
4732 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4733 &CGM.getModule());
4734 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4735 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004736 }
4737
4738 return Entry;
4739}
4740
4741/// GetOrEmitProtocol - Generate the protocol meta-data:
4742/// @code
4743/// struct _protocol_t {
4744/// id isa; // NULL
4745/// const char * const protocol_name;
4746/// const struct _protocol_list_t * protocol_list; // super protocols
4747/// const struct method_list_t * const instance_methods;
4748/// const struct method_list_t * const class_methods;
4749/// const struct method_list_t *optionalInstanceMethods;
4750/// const struct method_list_t *optionalClassMethods;
4751/// const struct _prop_list_t * properties;
4752/// const uint32_t size; // sizeof(struct _protocol_t)
4753/// const uint32_t flags; // = 0
4754/// }
4755/// @endcode
4756///
4757
4758llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4759 const ObjCProtocolDecl *PD) {
4760 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4761
4762 // Early exit if a defining object has already been generated.
4763 if (Entry && Entry->hasInitializer())
4764 return Entry;
4765
4766 const char *ProtocolName = PD->getNameAsCString();
4767
4768 // Construct method lists.
4769 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4770 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004771 for (ObjCProtocolDecl::instmeth_iterator
4772 i = PD->instmeth_begin(CGM.getContext()),
4773 e = PD->instmeth_end(CGM.getContext());
4774 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004775 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004776 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004777 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4778 OptInstanceMethods.push_back(C);
4779 } else {
4780 InstanceMethods.push_back(C);
4781 }
4782 }
4783
Douglas Gregor6ab35242009-04-09 21:40:53 +00004784 for (ObjCProtocolDecl::classmeth_iterator
4785 i = PD->classmeth_begin(CGM.getContext()),
4786 e = PD->classmeth_end(CGM.getContext());
4787 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004788 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004789 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004790 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4791 OptClassMethods.push_back(C);
4792 } else {
4793 ClassMethods.push_back(C);
4794 }
4795 }
4796
4797 std::vector<llvm::Constant*> Values(10);
4798 // isa is NULL
4799 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4800 Values[1] = GetClassName(PD->getIdentifier());
4801 Values[2] = EmitProtocolList(
4802 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4803 PD->protocol_begin(),
4804 PD->protocol_end());
4805
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004806 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004807 + PD->getNameAsString(),
4808 "__DATA, __objc_const",
4809 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004810 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004811 + PD->getNameAsString(),
4812 "__DATA, __objc_const",
4813 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004814 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 + PD->getNameAsString(),
4816 "__DATA, __objc_const",
4817 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004818 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004819 + PD->getNameAsString(),
4820 "__DATA, __objc_const",
4821 OptClassMethods);
4822 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4823 0, PD, ObjCTypes);
4824 uint32_t Size =
4825 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4826 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4827 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4828 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4829 Values);
4830
4831 if (Entry) {
4832 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004833 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004834 Entry->setInitializer(Init);
4835 } else {
4836 Entry =
4837 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004838 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004839 Init,
4840 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4841 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004842 Entry->setAlignment(
4843 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004844 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004845 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004846 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4847
4848 // Use this protocol meta-data to build protocol list table in section
4849 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004850 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004851 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004852 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004853 Entry,
4854 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4855 +ProtocolName,
4856 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004857 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004858 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004859 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004860 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4861 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004862 return Entry;
4863}
4864
4865/// EmitProtocolList - Generate protocol list meta-data:
4866/// @code
4867/// struct _protocol_list_t {
4868/// long protocol_count; // Note, this is 32/64 bit
4869/// struct _protocol_t[protocol_count];
4870/// }
4871/// @endcode
4872///
4873llvm::Constant *
4874CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4875 ObjCProtocolDecl::protocol_iterator begin,
4876 ObjCProtocolDecl::protocol_iterator end) {
4877 std::vector<llvm::Constant*> ProtocolRefs;
4878
Fariborz Jahanianda320092009-01-29 19:24:30 +00004879 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004880 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004881 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4882
Daniel Dunbar948e2582009-02-15 07:36:20 +00004883 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004884 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4885 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004886 return llvm::ConstantExpr::getBitCast(GV,
4887 ObjCTypes.ProtocolListnfABIPtrTy);
4888
4889 for (; begin != end; ++begin)
4890 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4891
Fariborz Jahanianda320092009-01-29 19:24:30 +00004892 // This list is null terminated.
4893 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004894 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004895
4896 std::vector<llvm::Constant*> Values(2);
4897 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4898 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004899 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004900 ProtocolRefs.size()),
4901 ProtocolRefs);
4902
4903 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4904 GV = new llvm::GlobalVariable(Init->getType(), false,
4905 llvm::GlobalValue::InternalLinkage,
4906 Init,
4907 Name,
4908 &CGM.getModule());
4909 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004910 GV->setAlignment(
4911 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004912 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004913 return llvm::ConstantExpr::getBitCast(GV,
4914 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004915}
4916
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004917/// GetMethodDescriptionConstant - This routine build following meta-data:
4918/// struct _objc_method {
4919/// SEL _cmd;
4920/// char *method_type;
4921/// char *_imp;
4922/// }
4923
4924llvm::Constant *
4925CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4926 std::vector<llvm::Constant*> Desc(3);
4927 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4928 ObjCTypes.SelectorPtrTy);
4929 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004930 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004931 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4932 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4933}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004934
4935/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4936/// This code gen. amounts to generating code for:
4937/// @code
4938/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4939/// @encode
4940///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004941LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004942 CodeGen::CodeGenFunction &CGF,
4943 QualType ObjectTy,
4944 llvm::Value *BaseValue,
4945 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004946 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004947 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004948 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4949 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004950}
4951
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004952llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4953 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004954 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004955 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004956 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4957 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004958}
4959
Fariborz Jahanian46551122009-02-04 00:22:57 +00004960CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4961 CodeGen::CodeGenFunction &CGF,
4962 QualType ResultType,
4963 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004964 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004965 QualType Arg0Ty,
4966 bool IsSuper,
4967 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004968 // FIXME. Even though IsSuper is passes. This function doese not
4969 // handle calls to 'super' receivers.
4970 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004971 llvm::Value *Arg0 = Receiver;
4972 if (!IsSuper)
4973 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004974
4975 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004976 // FIXME. This is too much work to get the ABI-specific result type
4977 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4979 llvm::SmallVector<QualType, 16>());
4980 llvm::Constant *Fn;
4981 std::string Name("\01l_");
4982 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004983#if 0
4984 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004985 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004986 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004987 // FIXME. Is there a better way of getting these names.
4988 // They are available in RuntimeFunctions vector pair.
4989 Name += "objc_msgSendId_stret_fixup";
4990 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004991 else
4992#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004993 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004994 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004995 Name += "objc_msgSendSuper2_stret_fixup";
4996 }
4997 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004998 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004999 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005000 Name += "objc_msgSend_stret_fixup";
5001 }
5002 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005003 else if (ResultType->isFloatingType() &&
5004 // Selection of frret API only happens in 32bit nonfragile ABI.
5005 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005006 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005007 Name += "objc_msgSend_fpret_fixup";
5008 }
5009 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005010#if 0
5011// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005012 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005013 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005014 Name += "objc_msgSendId_fixup";
5015 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005016 else
5017#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005018 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005019 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005020 Name += "objc_msgSendSuper2_fixup";
5021 }
5022 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005023 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005024 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005025 Name += "objc_msgSend_fixup";
5026 }
5027 }
5028 Name += '_';
5029 std::string SelName(Sel.getAsString());
5030 // Replace all ':' in selector name with '_' ouch!
5031 for(unsigned i = 0; i < SelName.size(); i++)
5032 if (SelName[i] == ':')
5033 SelName[i] = '_';
5034 Name += SelName;
5035 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5036 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005037 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005038 std::vector<llvm::Constant*> Values(2);
5039 Values[0] = Fn;
5040 Values[1] = GetMethodVarName(Sel);
5041 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5042 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005043 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005044 Init,
5045 Name,
5046 &CGM.getModule());
5047 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005048 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005049 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005050 }
5051 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005052
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 CallArgList ActualArgs;
5054 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5055 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5056 ObjCTypes.MessageRefCPtrTy));
5057 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005058 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5059 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5060 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005061 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005062 Callee = CGF.Builder.CreateBitCast(Callee,
5063 llvm::PointerType::getUnqual(FTy));
5064 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005065}
5066
5067/// Generate code for a message send expression in the nonfragile abi.
5068CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5069 CodeGen::CodeGenFunction &CGF,
5070 QualType ResultType,
5071 Selector Sel,
5072 llvm::Value *Receiver,
5073 bool IsClassMessage,
5074 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005075 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005076 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005077 false, CallArgs);
5078}
5079
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005080llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005081CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005082 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5083
Daniel Dunbardfff2302009-03-02 05:18:14 +00005084 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005085 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5086 llvm::GlobalValue::ExternalLinkage,
5087 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005088 }
5089
5090 return GV;
5091}
5092
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005093llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005094 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005095 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5096
5097 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005098 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005099 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005100 Entry =
5101 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5102 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005103 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005104 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005105 &CGM.getModule());
5106 Entry->setAlignment(
5107 CGM.getTargetData().getPrefTypeAlignment(
5108 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005109 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5110 UsedGlobals.push_back(Entry);
5111 }
5112
5113 return Builder.CreateLoad(Entry, false, "tmp");
5114}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005115
Daniel Dunbar11394522009-04-18 08:51:00 +00005116llvm::Value *
5117CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5118 const ObjCInterfaceDecl *ID) {
5119 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5120
5121 if (!Entry) {
5122 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5123 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5124 Entry =
5125 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5126 llvm::GlobalValue::InternalLinkage,
5127 ClassGV,
5128 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5129 &CGM.getModule());
5130 Entry->setAlignment(
5131 CGM.getTargetData().getPrefTypeAlignment(
5132 ObjCTypes.ClassnfABIPtrTy));
5133 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005134 UsedGlobals.push_back(Entry);
5135 }
5136
5137 return Builder.CreateLoad(Entry, false, "tmp");
5138}
5139
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005140/// EmitMetaClassRef - Return a Value * of the address of _class_t
5141/// meta-data
5142///
5143llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5144 const ObjCInterfaceDecl *ID) {
5145 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5146 if (Entry)
5147 return Builder.CreateLoad(Entry, false, "tmp");
5148
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005149 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005150 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005151 Entry =
5152 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5153 llvm::GlobalValue::InternalLinkage,
5154 MetaClassGV,
5155 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5156 &CGM.getModule());
5157 Entry->setAlignment(
5158 CGM.getTargetData().getPrefTypeAlignment(
5159 ObjCTypes.ClassnfABIPtrTy));
5160
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005161 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005162 UsedGlobals.push_back(Entry);
5163
5164 return Builder.CreateLoad(Entry, false, "tmp");
5165}
5166
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005167/// GetClass - Return a reference to the class for the given interface
5168/// decl.
5169llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5170 const ObjCInterfaceDecl *ID) {
5171 return EmitClassRef(Builder, ID);
5172}
5173
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005174/// Generates a message send where the super is the receiver. This is
5175/// a message send to self with special delivery semantics indicating
5176/// which class's method should be called.
5177CodeGen::RValue
5178CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5179 QualType ResultType,
5180 Selector Sel,
5181 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005182 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005183 llvm::Value *Receiver,
5184 bool IsClassMessage,
5185 const CodeGen::CallArgList &CallArgs) {
5186 // ...
5187 // Create and init a super structure; this is a (receiver, class)
5188 // pair we will pass to objc_msgSendSuper.
5189 llvm::Value *ObjCSuper =
5190 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5191
5192 llvm::Value *ReceiverAsObject =
5193 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5194 CGF.Builder.CreateStore(ReceiverAsObject,
5195 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5196
5197 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005198 llvm::Value *Target;
5199 if (IsClassMessage) {
5200 if (isCategoryImpl) {
5201 // Message sent to "super' in a class method defined in
5202 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005203 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005204 Target = CGF.Builder.CreateStructGEP(Target, 0);
5205 Target = CGF.Builder.CreateLoad(Target);
5206 }
5207 else
5208 Target = EmitMetaClassRef(CGF.Builder, Class);
5209 }
5210 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005211 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005212
5213 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5214 // and ObjCTypes types.
5215 const llvm::Type *ClassTy =
5216 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5217 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5218 CGF.Builder.CreateStore(Target,
5219 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5220
5221 return EmitMessageSend(CGF, ResultType, Sel,
5222 ObjCSuper, ObjCTypes.SuperPtrCTy,
5223 true, CallArgs);
5224}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005225
5226llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5227 Selector Sel) {
5228 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5229
5230 if (!Entry) {
5231 llvm::Constant *Casted =
5232 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5233 ObjCTypes.SelectorPtrTy);
5234 Entry =
5235 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5236 llvm::GlobalValue::InternalLinkage,
5237 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5238 &CGM.getModule());
5239 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5240 UsedGlobals.push_back(Entry);
5241 }
5242
5243 return Builder.CreateLoad(Entry, false, "tmp");
5244}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005245/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5246/// objc_assign_ivar (id src, id *dst)
5247///
5248void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5249 llvm::Value *src, llvm::Value *dst)
5250{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005251 const llvm::Type * SrcTy = src->getType();
5252 if (!isa<llvm::PointerType>(SrcTy)) {
5253 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5254 assert(Size <= 8 && "does not support size > 8");
5255 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5256 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005257 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5258 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005259 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5260 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005261 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005262 src, dst, "assignivar");
5263 return;
5264}
5265
5266/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5267/// objc_assign_strongCast (id src, id *dst)
5268///
5269void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5270 CodeGen::CodeGenFunction &CGF,
5271 llvm::Value *src, llvm::Value *dst)
5272{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005273 const llvm::Type * SrcTy = src->getType();
5274 if (!isa<llvm::PointerType>(SrcTy)) {
5275 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5276 assert(Size <= 8 && "does not support size > 8");
5277 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5278 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005279 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5280 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005281 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5282 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005283 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005284 src, dst, "weakassign");
5285 return;
5286}
5287
5288/// EmitObjCWeakRead - Code gen for loading value of a __weak
5289/// object: objc_read_weak (id *src)
5290///
5291llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5292 CodeGen::CodeGenFunction &CGF,
5293 llvm::Value *AddrWeakObj)
5294{
Eli Friedman8339b352009-03-07 03:57:15 +00005295 const llvm::Type* DestTy =
5296 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005297 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005298 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005299 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005300 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005301 return read_weak;
5302}
5303
5304/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5305/// objc_assign_weak (id src, id *dst)
5306///
5307void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5308 llvm::Value *src, llvm::Value *dst)
5309{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005310 const llvm::Type * SrcTy = src->getType();
5311 if (!isa<llvm::PointerType>(SrcTy)) {
5312 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5313 assert(Size <= 8 && "does not support size > 8");
5314 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5315 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005316 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5317 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005318 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5319 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005320 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005321 src, dst, "weakassign");
5322 return;
5323}
5324
5325/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5326/// objc_assign_global (id src, id *dst)
5327///
5328void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5329 llvm::Value *src, llvm::Value *dst)
5330{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005331 const llvm::Type * SrcTy = src->getType();
5332 if (!isa<llvm::PointerType>(SrcTy)) {
5333 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5334 assert(Size <= 8 && "does not support size > 8");
5335 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5336 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005337 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5338 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005339 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5340 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005341 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005342 src, dst, "globalassign");
5343 return;
5344}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005345
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005346void
5347CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5348 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005349 bool isTry = isa<ObjCAtTryStmt>(S);
5350 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5351 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005352 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005353 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005354 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005355 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5356
5357 // For @synchronized, call objc_sync_enter(sync.expr). The
5358 // evaluation of the expression must occur before we enter the
5359 // @synchronized. We can safely avoid a temp here because jumps into
5360 // @synchronized are illegal & this will dominate uses.
5361 llvm::Value *SyncArg = 0;
5362 if (!isTry) {
5363 SyncArg =
5364 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5365 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005366 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005367 }
5368
5369 // Push an EH context entry, used for handling rethrows and jumps
5370 // through finally.
5371 CGF.PushCleanupBlock(FinallyBlock);
5372
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005373 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005374
5375 CGF.EmitBlock(TryBlock);
5376 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5377 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5378 CGF.EmitBranchThroughCleanup(FinallyEnd);
5379
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005380 // Emit the exception handler.
5381
5382 CGF.EmitBlock(TryHandler);
5383
5384 llvm::Value *llvm_eh_exception =
5385 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5386 llvm::Value *llvm_eh_selector_i64 =
5387 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5388 llvm::Value *llvm_eh_typeid_for_i64 =
5389 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5390 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5391 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5392
5393 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5394 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005395 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005396
5397 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005398 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005399 bool HasCatchAll = false;
5400 if (isTry) {
5401 if (const ObjCAtCatchStmt* CatchStmt =
5402 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5403 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005404 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005405 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005406
5407 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005408 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005409 // Use i8* null here to signal this is a catch all, not a cleanup.
5410 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5411 SelectorArgs.push_back(Null);
5412 HasCatchAll = true;
5413 break;
5414 }
5415
Daniel Dunbarede8de92009-03-06 00:01:21 +00005416 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5417 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005418 llvm::Value *IDEHType =
5419 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5420 if (!IDEHType)
5421 IDEHType =
5422 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5423 llvm::GlobalValue::ExternalLinkage,
5424 0, "OBJC_EHTYPE_id", &CGM.getModule());
5425 SelectorArgs.push_back(IDEHType);
5426 HasCatchAll = true;
5427 break;
5428 }
5429
5430 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005431 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005432 assert(PT && "Invalid @catch type.");
5433 const ObjCInterfaceType *IT =
5434 PT->getPointeeType()->getAsObjCInterfaceType();
5435 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005436 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005437 SelectorArgs.push_back(EHType);
5438 }
5439 }
5440 }
5441
5442 // We use a cleanup unless there was already a catch all.
5443 if (!HasCatchAll) {
5444 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005445 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446 }
5447
5448 llvm::Value *Selector =
5449 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5450 SelectorArgs.begin(), SelectorArgs.end(),
5451 "selector");
5452 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005453 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005454 const Stmt *CatchBody = Handlers[i].second;
5455
5456 llvm::BasicBlock *Next = 0;
5457
5458 // The last handler always matches.
5459 if (i + 1 != e) {
5460 assert(CatchParam && "Only last handler can be a catch all.");
5461
5462 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5463 Next = CGF.createBasicBlock("catch.next");
5464 llvm::Value *Id =
5465 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5466 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5467 ObjCTypes.Int8PtrTy));
5468 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5469 Match, Next);
5470
5471 CGF.EmitBlock(Match);
5472 }
5473
5474 if (CatchBody) {
5475 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5476 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5477
5478 // Cleanups must call objc_end_catch.
5479 //
5480 // FIXME: It seems incorrect for objc_begin_catch to be inside
5481 // this context, but this matches gcc.
5482 CGF.PushCleanupBlock(MatchEnd);
5483 CGF.setInvokeDest(MatchHandler);
5484
5485 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005486 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005487
5488 // Bind the catch parameter if it exists.
5489 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005490 ExcObject =
5491 CGF.Builder.CreateBitCast(ExcObject,
5492 CGF.ConvertType(CatchParam->getType()));
5493 // CatchParam is a ParmVarDecl because of the grammar
5494 // construction used to handle this, but for codegen purposes
5495 // we treat this as a local decl.
5496 CGF.EmitLocalBlockVarDecl(*CatchParam);
5497 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005498 }
5499
5500 CGF.ObjCEHValueStack.push_back(ExcObject);
5501 CGF.EmitStmt(CatchBody);
5502 CGF.ObjCEHValueStack.pop_back();
5503
5504 CGF.EmitBranchThroughCleanup(FinallyEnd);
5505
5506 CGF.EmitBlock(MatchHandler);
5507
5508 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5509 // We are required to emit this call to satisfy LLVM, even
5510 // though we don't use the result.
5511 llvm::SmallVector<llvm::Value*, 8> Args;
5512 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005513 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005514 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5515 0));
5516 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5517 CGF.Builder.CreateStore(Exc, RethrowPtr);
5518 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5519
5520 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5521
5522 CGF.EmitBlock(MatchEnd);
5523
5524 // Unfortunately, we also have to generate another EH frame here
5525 // in case this throws.
5526 llvm::BasicBlock *MatchEndHandler =
5527 CGF.createBasicBlock("match.end.handler");
5528 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005529 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005530 Cont, MatchEndHandler,
5531 Args.begin(), Args.begin());
5532
5533 CGF.EmitBlock(Cont);
5534 if (Info.SwitchBlock)
5535 CGF.EmitBlock(Info.SwitchBlock);
5536 if (Info.EndBlock)
5537 CGF.EmitBlock(Info.EndBlock);
5538
5539 CGF.EmitBlock(MatchEndHandler);
5540 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5541 // We are required to emit this call to satisfy LLVM, even
5542 // though we don't use the result.
5543 Args.clear();
5544 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005545 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005546 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5547 0));
5548 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5549 CGF.Builder.CreateStore(Exc, RethrowPtr);
5550 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5551
5552 if (Next)
5553 CGF.EmitBlock(Next);
5554 } else {
5555 assert(!Next && "catchup should be last handler.");
5556
5557 CGF.Builder.CreateStore(Exc, RethrowPtr);
5558 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5559 }
5560 }
5561
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005562 // Pop the cleanup entry, the @finally is outside this cleanup
5563 // scope.
5564 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5565 CGF.setInvokeDest(PrevLandingPad);
5566
5567 CGF.EmitBlock(FinallyBlock);
5568
5569 if (isTry) {
5570 if (const ObjCAtFinallyStmt* FinallyStmt =
5571 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5572 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5573 } else {
5574 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5575 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005576 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005577 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005578
5579 if (Info.SwitchBlock)
5580 CGF.EmitBlock(Info.SwitchBlock);
5581 if (Info.EndBlock)
5582 CGF.EmitBlock(Info.EndBlock);
5583
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005584 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005585 CGF.EmitBranch(FinallyEnd);
5586
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005587 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005588 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005589 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005590 CGF.Builder.CreateUnreachable();
5591
5592 CGF.EmitBlock(FinallyEnd);
5593}
5594
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005595/// EmitThrowStmt - Generate code for a throw statement.
5596void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5597 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005598 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005599 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005600 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005601 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005602 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5603 "Unexpected rethrow outside @catch block.");
5604 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005605 }
5606
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005607 llvm::Value *ExceptionAsObject =
5608 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5609 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5610 if (InvokeDest) {
5611 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005612 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005613 Cont, InvokeDest,
5614 &ExceptionAsObject, &ExceptionAsObject + 1);
5615 CGF.EmitBlock(Cont);
5616 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005617 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005618 CGF.Builder.CreateUnreachable();
5619
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005620 // Clear the insertion point to indicate we are in unreachable code.
5621 CGF.Builder.ClearInsertionPoint();
5622}
Daniel Dunbare588b992009-03-01 04:46:24 +00005623
5624llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005625CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5626 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005627 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005628
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005629 // If we don't need a definition, return the entry if found or check
5630 // if we use an external reference.
5631 if (!ForDefinition) {
5632 if (Entry)
5633 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005634
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005635 // If this type (or a super class) has the __objc_exception__
5636 // attribute, emit an external reference.
5637 if (hasObjCExceptionAttribute(ID))
5638 return Entry =
5639 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5640 llvm::GlobalValue::ExternalLinkage,
5641 0,
5642 (std::string("OBJC_EHTYPE_$_") +
5643 ID->getIdentifier()->getName()),
5644 &CGM.getModule());
5645 }
5646
5647 // Otherwise we need to either make a new entry or fill in the
5648 // initializer.
5649 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005650 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005651 std::string VTableName = "objc_ehtype_vtable";
5652 llvm::GlobalVariable *VTableGV =
5653 CGM.getModule().getGlobalVariable(VTableName);
5654 if (!VTableGV)
5655 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5656 llvm::GlobalValue::ExternalLinkage,
5657 0, VTableName, &CGM.getModule());
5658
5659 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5660
5661 std::vector<llvm::Constant*> Values(3);
5662 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5663 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005664 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005665 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5666
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005667 if (Entry) {
5668 Entry->setInitializer(Init);
5669 } else {
5670 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5671 llvm::GlobalValue::WeakAnyLinkage,
5672 Init,
5673 (std::string("OBJC_EHTYPE_$_") +
5674 ID->getIdentifier()->getName()),
5675 &CGM.getModule());
5676 }
5677
Daniel Dunbar04d40782009-04-14 06:00:08 +00005678 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005679 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005680 Entry->setAlignment(8);
5681
5682 if (ForDefinition) {
5683 Entry->setSection("__DATA,__objc_const");
5684 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5685 } else {
5686 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5687 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005688
5689 return Entry;
5690}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005691
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005692/* *** */
5693
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005694CodeGen::CGObjCRuntime *
5695CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005696 return new CGObjCMac(CGM);
5697}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005698
5699CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005700CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005701 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005702}