blob: 7d1cea7e0e0afc9b8268c4cf8b50d3d634961538 [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
36uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
37 const ObjCInterfaceDecl *OID,
38 const ObjCIvarDecl *Ivar) {
39 assert(!OID->isForwardDecl() && "Invalid interface decl!");
40 QualType T = CGM.getContext().getObjCInterfaceType(OID);
41 const llvm::StructType *InterfaceTy =
42 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
43 const llvm::StructLayout *Layout =
44 CGM.getTargetData().getStructLayout(InterfaceTy);
45 const FieldDecl *Field =
46 OID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
47 if (!Field->isBitField())
48 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
49
50 // FIXME. Must be a better way of getting a bitfield base offset.
51 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
52 // FIXME: The "field no" for bitfields is something completely
53 // different; it is the offset in multiples of the base type size!
54 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
55 const llvm::Type *Ty =
56 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
57 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
58 return (Offset + BFI.Begin) / 8;
59}
60
61LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
62 const ObjCInterfaceDecl *OID,
63 llvm::Value *BaseValue,
64 const ObjCIvarDecl *Ivar,
65 unsigned CVRQualifiers,
66 llvm::Value *Offset) {
67 // FIXME: For now, we use an implementation based on just computing
68 // the offset and calculating things directly. For optimization
69 // purposes, it would be cleaner to use a GEP on the proper type
70 // since the structure layout is fixed; however for that we need to
71 // be able to walk the class chain for an Ivar.
72 const FieldDecl *Field =
73 OID->lookupFieldDeclForIvar(CGF.CGM.getContext(), Ivar);
74
75 // (char *) BaseValue
76 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
77 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
78 // (char*)BaseValue + Offset_symbol
79 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
80 // (type *)((char*)BaseValue + Offset_symbol)
81 const llvm::Type *IvarTy =
82 CGF.CGM.getTypes().ConvertTypeForMem(Ivar->getType());
83 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
84 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
85
86 if (Ivar->isBitField()) {
87 QualType FieldTy = Field->getType();
88 CodeGenTypes::BitFieldInfo bitFieldInfo =
89 CGF.CGM.getTypes().getBitFieldInfo(Field);
90 return LValue::MakeBitfield(V, bitFieldInfo.Begin % 8, bitFieldInfo.Size,
91 FieldTy->isSignedIntegerType(),
92 FieldTy.getCVRQualifiers()|CVRQualifiers);
93 }
94
95 LValue LV = LValue::MakeAddr(V,
96 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
97 CGF.CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
98 LValue::SetObjCIvar(LV, true);
99 return LV;
100}
101
102///
103
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000104namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000105
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000106 typedef std::vector<llvm::Constant*> ConstantVector;
107
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000108 // FIXME: We should find a nicer way to make the labels for
109 // metadata, string concatenation is lame.
110
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000111class ObjCCommonTypesHelper {
112protected:
113 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000114
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000115public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000116 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000117 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000118
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000119 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
120 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000121
122 /// PtrObjectPtrTy - LLVM type for id *
123 const llvm::Type *PtrObjectPtrTy;
124
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000125 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000126 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000127 /// ProtocolPtrTy - LLVM type for external protocol handles
128 /// (typeof(Protocol))
129 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000130
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000131 // SuperCTy - clang type for struct objc_super.
132 QualType SuperCTy;
133 // SuperPtrCTy - clang type for struct objc_super *.
134 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000135
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000136 /// SuperTy - LLVM type for struct objc_super.
137 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000138 /// SuperPtrTy - LLVM type for struct objc_super *.
139 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000140
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000141 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
142 /// in GCC parlance).
143 const llvm::StructType *PropertyTy;
144
145 /// PropertyListTy - LLVM type for struct objc_property_list
146 /// (_prop_list_t in GCC parlance).
147 const llvm::StructType *PropertyListTy;
148 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
149 const llvm::Type *PropertyListPtrTy;
150
151 // MethodTy - LLVM type for struct objc_method.
152 const llvm::StructType *MethodTy;
153
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000154 /// CacheTy - LLVM type for struct objc_cache.
155 const llvm::Type *CacheTy;
156 /// CachePtrTy - LLVM type for struct objc_cache *.
157 const llvm::Type *CachePtrTy;
158
Chris Lattner72db6c32009-04-22 02:44:54 +0000159 llvm::Constant *getGetPropertyFn() {
160 CodeGen::CodeGenTypes &Types = CGM.getTypes();
161 ASTContext &Ctx = CGM.getContext();
162 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
163 llvm::SmallVector<QualType,16> Params;
164 QualType IdType = Ctx.getObjCIdType();
165 QualType SelType = Ctx.getObjCSelType();
166 Params.push_back(IdType);
167 Params.push_back(SelType);
168 Params.push_back(Ctx.LongTy);
169 Params.push_back(Ctx.BoolTy);
170 const llvm::FunctionType *FTy =
171 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
172 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
173 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000174
Chris Lattner72db6c32009-04-22 02:44:54 +0000175 llvm::Constant *getSetPropertyFn() {
176 CodeGen::CodeGenTypes &Types = CGM.getTypes();
177 ASTContext &Ctx = CGM.getContext();
178 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
179 llvm::SmallVector<QualType,16> Params;
180 QualType IdType = Ctx.getObjCIdType();
181 QualType SelType = Ctx.getObjCSelType();
182 Params.push_back(IdType);
183 Params.push_back(SelType);
184 Params.push_back(Ctx.LongTy);
185 Params.push_back(IdType);
186 Params.push_back(Ctx.BoolTy);
187 Params.push_back(Ctx.BoolTy);
188 const llvm::FunctionType *FTy =
189 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
190 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
191 }
192
193 llvm::Constant *getEnumerationMutationFn() {
194 // void objc_enumerationMutation (id)
195 std::vector<const llvm::Type*> Args;
196 Args.push_back(ObjectPtrTy);
197 llvm::FunctionType *FTy =
198 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
199 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
200 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000201
202 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000203 llvm::Constant *getGcReadWeakFn() {
204 // id objc_read_weak (id *)
205 std::vector<const llvm::Type*> Args;
206 Args.push_back(ObjectPtrTy->getPointerTo());
207 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
208 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
209 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000210
211 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000212 llvm::Constant *getGcAssignWeakFn() {
213 // id objc_assign_weak (id, id *)
214 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
215 Args.push_back(ObjectPtrTy->getPointerTo());
216 llvm::FunctionType *FTy =
217 llvm::FunctionType::get(ObjectPtrTy, Args, false);
218 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
219 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000220
221 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000222 llvm::Constant *getGcAssignGlobalFn() {
223 // id objc_assign_global(id, id *)
224 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
225 Args.push_back(ObjectPtrTy->getPointerTo());
226 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
227 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
228 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000229
230 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000231 llvm::Constant *getGcAssignIvarFn() {
232 // id objc_assign_ivar(id, id *)
233 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
234 Args.push_back(ObjectPtrTy->getPointerTo());
235 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
236 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
237 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000238
239 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000240 llvm::Constant *getGcAssignStrongCastFn() {
241 // id objc_assign_global(id, id *)
242 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
243 Args.push_back(ObjectPtrTy->getPointerTo());
244 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
245 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
246 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000247
248 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000249 llvm::Constant *getExceptionThrowFn() {
250 // void objc_exception_throw(id)
251 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
252 llvm::FunctionType *FTy =
253 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
254 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
255 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000256
Daniel Dunbar1c566672009-02-24 01:43:46 +0000257 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000258 llvm::Constant *getSyncEnterFn() {
259 // void objc_sync_enter (id)
260 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
261 llvm::FunctionType *FTy =
262 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
263 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
264 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000265
266 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000267 llvm::Constant *getSyncExitFn() {
268 // void objc_sync_exit (id)
269 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
270 llvm::FunctionType *FTy =
271 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
272 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
273 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000274
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000275 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
276 ~ObjCCommonTypesHelper(){}
277};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000278
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000279/// ObjCTypesHelper - Helper class that encapsulates lazy
280/// construction of varies types used during ObjC generation.
281class ObjCTypesHelper : public ObjCCommonTypesHelper {
282private:
283
Chris Lattner4176b0c2009-04-22 02:32:31 +0000284 llvm::Constant *getMessageSendFn() {
285 // id objc_msgSend (id, SEL, ...)
286 std::vector<const llvm::Type*> Params;
287 Params.push_back(ObjectPtrTy);
288 Params.push_back(SelectorPtrTy);
289 return
290 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
291 Params, true),
292 "objc_msgSend");
293 }
294
295 llvm::Constant *getMessageSendStretFn() {
296 // id objc_msgSend_stret (id, SEL, ...)
297 std::vector<const llvm::Type*> Params;
298 Params.push_back(ObjectPtrTy);
299 Params.push_back(SelectorPtrTy);
300 return
301 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
302 Params, true),
303 "objc_msgSend_stret");
304
305 }
306
307 llvm::Constant *getMessageSendFpretFn() {
308 // FIXME: This should be long double on x86_64?
309 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
310 std::vector<const llvm::Type*> Params;
311 Params.push_back(ObjectPtrTy);
312 Params.push_back(SelectorPtrTy);
313 return
314 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
315 Params,
316 true),
317 "objc_msgSend_fpret");
318
319 }
320
321 llvm::Constant *getMessageSendSuperFn() {
322 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
323 std::vector<const llvm::Type*> Params;
324 Params.push_back(SuperPtrTy);
325 Params.push_back(SelectorPtrTy);
326 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
327 Params, true),
328 "objc_msgSendSuper");
329 }
330 llvm::Constant *getMessageSendSuperStretFn() {
331 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
332 // SEL op, ...)
333 std::vector<const llvm::Type*> Params;
334 Params.push_back(Int8PtrTy);
335 Params.push_back(SuperPtrTy);
336 Params.push_back(SelectorPtrTy);
337 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
338 Params, true),
339 "objc_msgSendSuper_stret");
340 }
341
342 llvm::Constant *getMessageSendSuperFpretFn() {
343 // There is no objc_msgSendSuper_fpret? How can that work?
344 return getMessageSendSuperFn();
345 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000346
347public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000348 /// SymtabTy - LLVM type for struct objc_symtab.
349 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000350 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
351 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000352 /// ModuleTy - LLVM type for struct objc_module.
353 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000354
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000355 /// ProtocolTy - LLVM type for struct objc_protocol.
356 const llvm::StructType *ProtocolTy;
357 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
358 const llvm::Type *ProtocolPtrTy;
359 /// ProtocolExtensionTy - LLVM type for struct
360 /// objc_protocol_extension.
361 const llvm::StructType *ProtocolExtensionTy;
362 /// ProtocolExtensionTy - LLVM type for struct
363 /// objc_protocol_extension *.
364 const llvm::Type *ProtocolExtensionPtrTy;
365 /// MethodDescriptionTy - LLVM type for struct
366 /// objc_method_description.
367 const llvm::StructType *MethodDescriptionTy;
368 /// MethodDescriptionListTy - LLVM type for struct
369 /// objc_method_description_list.
370 const llvm::StructType *MethodDescriptionListTy;
371 /// MethodDescriptionListPtrTy - LLVM type for struct
372 /// objc_method_description_list *.
373 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000374 /// ProtocolListTy - LLVM type for struct objc_property_list.
375 const llvm::Type *ProtocolListTy;
376 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
377 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000378 /// CategoryTy - LLVM type for struct objc_category.
379 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000380 /// ClassTy - LLVM type for struct objc_class.
381 const llvm::StructType *ClassTy;
382 /// ClassPtrTy - LLVM type for struct objc_class *.
383 const llvm::Type *ClassPtrTy;
384 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
385 const llvm::StructType *ClassExtensionTy;
386 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
387 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 // IvarTy - LLVM type for struct objc_ivar.
389 const llvm::StructType *IvarTy;
390 /// IvarListTy - LLVM type for struct objc_ivar_list.
391 const llvm::Type *IvarListTy;
392 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
393 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 /// MethodListTy - LLVM type for struct objc_method_list.
395 const llvm::Type *MethodListTy;
396 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
397 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000398
399 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
400 const llvm::Type *ExceptionDataTy;
401
Anders Carlsson124526b2008-09-09 10:10:21 +0000402 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000403 llvm::Constant *getExceptionTryEnterFn() {
404 std::vector<const llvm::Type*> Params;
405 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
406 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
407 Params, false),
408 "objc_exception_try_enter");
409 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000410
411 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000412 llvm::Constant *getExceptionTryExitFn() {
413 std::vector<const llvm::Type*> Params;
414 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
415 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
416 Params, false),
417 "objc_exception_try_exit");
418 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000419
420 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000421 llvm::Constant *getExceptionExtractFn() {
422 std::vector<const llvm::Type*> Params;
423 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
424 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
425 Params, false),
426 "objc_exception_extract");
427
428 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000429
430 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000431 llvm::Constant *getExceptionMatchFn() {
432 std::vector<const llvm::Type*> Params;
433 Params.push_back(ClassPtrTy);
434 Params.push_back(ObjectPtrTy);
435 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
436 Params, false),
437 "objc_exception_match");
438
439 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000440
441 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000442 llvm::Constant *getSetJmpFn() {
443 std::vector<const llvm::Type*> Params;
444 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
445 return
446 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
447 Params, false),
448 "_setjmp");
449
450 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000451
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000452public:
453 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000454 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000455
456
Chris Lattner74391b42009-03-22 21:03:39 +0000457 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000458 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000459 }
460
Chris Lattner74391b42009-03-22 21:03:39 +0000461 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000462 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000463 }
464
Chris Lattner74391b42009-03-22 21:03:39 +0000465 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000466 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000467 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000468};
469
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000470/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000471/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000472class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000473public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000474
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000475 // MethodListnfABITy - LLVM for struct _method_list_t
476 const llvm::StructType *MethodListnfABITy;
477
478 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
479 const llvm::Type *MethodListnfABIPtrTy;
480
481 // ProtocolnfABITy = LLVM for struct _protocol_t
482 const llvm::StructType *ProtocolnfABITy;
483
Daniel Dunbar948e2582009-02-15 07:36:20 +0000484 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
485 const llvm::Type *ProtocolnfABIPtrTy;
486
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000487 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
488 const llvm::StructType *ProtocolListnfABITy;
489
490 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
491 const llvm::Type *ProtocolListnfABIPtrTy;
492
493 // ClassnfABITy - LLVM for struct _class_t
494 const llvm::StructType *ClassnfABITy;
495
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000496 // ClassnfABIPtrTy - LLVM for struct _class_t*
497 const llvm::Type *ClassnfABIPtrTy;
498
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000499 // IvarnfABITy - LLVM for struct _ivar_t
500 const llvm::StructType *IvarnfABITy;
501
502 // IvarListnfABITy - LLVM for struct _ivar_list_t
503 const llvm::StructType *IvarListnfABITy;
504
505 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
506 const llvm::Type *IvarListnfABIPtrTy;
507
508 // ClassRonfABITy - LLVM for struct _class_ro_t
509 const llvm::StructType *ClassRonfABITy;
510
511 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
512 const llvm::Type *ImpnfABITy;
513
514 // CategorynfABITy - LLVM for struct _category_t
515 const llvm::StructType *CategorynfABITy;
516
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000517 // New types for nonfragile abi messaging.
518
519 // MessageRefTy - LLVM for:
520 // struct _message_ref_t {
521 // IMP messenger;
522 // SEL name;
523 // };
524 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000525 // MessageRefCTy - clang type for struct _message_ref_t
526 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000527
528 // MessageRefPtrTy - LLVM for struct _message_ref_t*
529 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000530 // MessageRefCPtrTy - clang type for struct _message_ref_t*
531 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000532
Fariborz Jahanianef163782009-02-05 01:13:09 +0000533 // MessengerTy - Type of the messenger (shown as IMP above)
534 const llvm::FunctionType *MessengerTy;
535
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000536 // SuperMessageRefTy - LLVM for:
537 // struct _super_message_ref_t {
538 // SUPER_IMP messenger;
539 // SEL name;
540 // };
541 const llvm::StructType *SuperMessageRefTy;
542
543 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
544 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000545
Chris Lattner1c02f862009-04-22 02:53:24 +0000546 llvm::Constant *getMessageSendFixupFn() {
547 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
548 std::vector<const llvm::Type*> Params;
549 Params.push_back(ObjectPtrTy);
550 Params.push_back(MessageRefPtrTy);
551 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
552 Params, true),
553 "objc_msgSend_fixup");
554 }
555
556 llvm::Constant *getMessageSendFpretFixupFn() {
557 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
558 std::vector<const llvm::Type*> Params;
559 Params.push_back(ObjectPtrTy);
560 Params.push_back(MessageRefPtrTy);
561 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
562 Params, true),
563 "objc_msgSend_fpret_fixup");
564 }
565
566 llvm::Constant *getMessageSendStretFixupFn() {
567 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
568 std::vector<const llvm::Type*> Params;
569 Params.push_back(ObjectPtrTy);
570 Params.push_back(MessageRefPtrTy);
571 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
572 Params, true),
573 "objc_msgSend_stret_fixup");
574 }
575
576 llvm::Constant *getMessageSendIdFixupFn() {
577 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
578 std::vector<const llvm::Type*> Params;
579 Params.push_back(ObjectPtrTy);
580 Params.push_back(MessageRefPtrTy);
581 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
582 Params, true),
583 "objc_msgSendId_fixup");
584 }
585
586 llvm::Constant *getMessageSendIdStretFixupFn() {
587 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
588 std::vector<const llvm::Type*> Params;
589 Params.push_back(ObjectPtrTy);
590 Params.push_back(MessageRefPtrTy);
591 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
592 Params, true),
593 "objc_msgSendId_stret_fixup");
594 }
595 llvm::Constant *getMessageSendSuper2FixupFn() {
596 // id objc_msgSendSuper2_fixup (struct objc_super *,
597 // struct _super_message_ref_t*, ...)
598 std::vector<const llvm::Type*> Params;
599 Params.push_back(SuperPtrTy);
600 Params.push_back(SuperMessageRefPtrTy);
601 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
602 Params, true),
603 "objc_msgSendSuper2_fixup");
604 }
605
606 llvm::Constant *getMessageSendSuper2StretFixupFn() {
607 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
608 // struct _super_message_ref_t*, ...)
609 std::vector<const llvm::Type*> Params;
610 Params.push_back(SuperPtrTy);
611 Params.push_back(SuperMessageRefPtrTy);
612 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
613 Params, true),
614 "objc_msgSendSuper2_stret_fixup");
615 }
616
617
618
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000619 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
620 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000621 llvm::Value *getEHPersonalityPtr() {
622 llvm::Constant *Personality =
623 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
624 std::vector<const llvm::Type*>(),
625 true),
626 "__objc_personality_v0");
627 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
628 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000629
Chris Lattner8a569112009-04-22 02:15:23 +0000630 llvm::Constant *getUnwindResumeOrRethrowFn() {
631 std::vector<const llvm::Type*> Params;
632 Params.push_back(Int8PtrTy);
633 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
634 Params, false),
635 "_Unwind_Resume_or_Rethrow");
636 }
637
638 llvm::Constant *getObjCEndCatchFn() {
639 std::vector<const llvm::Type*> Params;
640 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
641 Params, false),
642 "objc_end_catch");
643
644 }
645
646 llvm::Constant *getObjCBeginCatchFn() {
647 std::vector<const llvm::Type*> Params;
648 Params.push_back(Int8PtrTy);
649 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
650 Params, false),
651 "objc_begin_catch");
652 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000653
654 const llvm::StructType *EHTypeTy;
655 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000656
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000657 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
658 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000659};
660
661class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000662public:
663 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000664 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000665 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000666 unsigned int ivar_bytepos;
667 unsigned int ivar_size;
668 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
669 };
670
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000671 class SKIP_SCAN {
672 public:
673 unsigned int skip;
674 unsigned int scan;
675 SKIP_SCAN() : skip(0), scan(0) {}
676 };
677
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000678protected:
679 CodeGen::CodeGenModule &CGM;
680 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000681 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000682
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000683 // gc ivar layout bitmap calculation helper caches.
684 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
685 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
686 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000687
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000688 /// LazySymbols - Symbols to generate a lazy reference for. See
689 /// DefinedSymbols and FinishModule().
690 std::set<IdentifierInfo*> LazySymbols;
691
692 /// DefinedSymbols - External symbols which are defined by this
693 /// module. The symbols in this list and LazySymbols are used to add
694 /// special linker symbols which ensure that Objective-C modules are
695 /// linked properly.
696 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000698 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000699 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000700
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000701 /// MethodVarNames - uniqued method variable names.
702 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000703
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000704 /// MethodVarTypes - uniqued method type signatures. We have to use
705 /// a StringMap here because have no other unique reference.
706 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000707
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000708 /// MethodDefinitions - map of methods which have been defined in
709 /// this translation unit.
710 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000711
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000712 /// PropertyNames - uniqued method variable names.
713 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000714
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000715 /// ClassReferences - uniqued class references.
716 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000717
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000718 /// SelectorReferences - uniqued selector references.
719 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000720
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000721 /// Protocols - Protocols for which an objc_protocol structure has
722 /// been emitted. Forward declarations are handled by creating an
723 /// empty structure whose initializer is filled in when/if defined.
724 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000725
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000726 /// DefinedProtocols - Protocols which have actually been
727 /// defined. We should not need this, see FIXME in GenerateProtocol.
728 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000729
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000730 /// DefinedClasses - List of defined classes.
731 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000732
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000733 /// DefinedCategories - List of defined categories.
734 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000735
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000736 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000737 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000738 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000739
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000740 /// GetNameForMethod - Return a name for the given method.
741 /// \param[out] NameOut - The return value.
742 void GetNameForMethod(const ObjCMethodDecl *OMD,
743 const ObjCContainerDecl *CD,
744 std::string &NameOut);
745
746 /// GetMethodVarName - Return a unique constant for the given
747 /// selector's name. The return value has type char *.
748 llvm::Constant *GetMethodVarName(Selector Sel);
749 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
750 llvm::Constant *GetMethodVarName(const std::string &Name);
751
752 /// GetMethodVarType - Return a unique constant for the given
753 /// selector's name. The return value has type char *.
754
755 // FIXME: This is a horrible name.
756 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000757 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000758
759 /// GetPropertyName - Return a unique constant for the given
760 /// name. The return value has type char *.
761 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
762
763 // FIXME: This can be dropped once string functions are unified.
764 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
765 const Decl *Container);
766
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000767 /// GetClassName - Return a unique constant for the given selector's
768 /// name. The return value has type char *.
769 llvm::Constant *GetClassName(IdentifierInfo *Ident);
770
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000771 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
772 /// interface declaration.
773 const llvm::StructLayout *GetInterfaceDeclStructLayout(
774 const ObjCInterfaceDecl *ID) const;
775
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000776 /// BuildIvarLayout - Builds ivar layout bitmap for the class
777 /// implementation for the __strong or __weak case.
778 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000779 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
780 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000781
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000782 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
783 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000784 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000785 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000786 unsigned int BytePos, bool ForStrongLayout,
787 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000788
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000789 /// GetIvarLayoutName - Returns a unique constant for the given
790 /// ivar layout bitmap.
791 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
792 const ObjCCommonTypesHelper &ObjCTypes);
793
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000794 /// EmitPropertyList - Emit the given property list. The return
795 /// value has type PropertyListPtrTy.
796 llvm::Constant *EmitPropertyList(const std::string &Name,
797 const Decl *Container,
798 const ObjCContainerDecl *OCD,
799 const ObjCCommonTypesHelper &ObjCTypes);
800
Fariborz Jahanianda320092009-01-29 19:24:30 +0000801 /// GetProtocolRef - Return a reference to the internal protocol
802 /// description, creating an empty one if it has not been
803 /// defined. The return value has type ProtocolPtrTy.
804 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000805
Chris Lattnercd0ee142009-03-31 08:33:16 +0000806 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000807 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
808 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000809 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000810
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000811 /// CreateMetadataVar - Create a global variable with internal
812 /// linkage for use by the Objective-C runtime.
813 ///
814 /// This is a convenience wrapper which not only creates the
815 /// variable, but also sets the section and alignment and adds the
816 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000817 ///
818 /// \param Name - The variable name.
819 /// \param Init - The variable initializer; this is also used to
820 /// define the type of the variable.
821 /// \param Section - The section the variable should go into, or 0.
822 /// \param Align - The alignment for the variable, or 0.
823 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000824 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000825 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
826 llvm::Constant *Init,
827 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000828 unsigned Align,
829 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000830
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000831 /// GetNamedIvarList - Return the list of ivars in the interface
832 /// itself (not including super classes and not including unnamed
833 /// bitfields).
834 ///
835 /// For the non-fragile ABI, this also includes synthesized property
836 /// ivars.
837 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
838 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
839
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000840public:
841 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
842 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000843
Steve Naroff33fdb732009-03-31 16:53:37 +0000844 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000845
846 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
847 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000848
849 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
850
851 /// GetOrEmitProtocol - Get the protocol object for the given
852 /// declaration, emitting it if necessary. The return value has type
853 /// ProtocolPtrTy.
854 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
855
856 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
857 /// object for the given declaration, emitting it if needed. These
858 /// forward references will be filled in with empty bodies if no
859 /// definition is seen. The return value has type ProtocolPtrTy.
860 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000861};
862
863class CGObjCMac : public CGObjCCommonMac {
864private:
865 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000866 /// EmitImageInfo - Emit the image info marker used to encode some module
867 /// level information.
868 void EmitImageInfo();
869
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000870 /// EmitModuleInfo - Another marker encoding module level
871 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000872 void EmitModuleInfo();
873
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000874 /// EmitModuleSymols - Emit module symbols, the list of defined
875 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000876 llvm::Constant *EmitModuleSymbols();
877
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000878 /// FinishModule - Write out global data structures at the end of
879 /// processing a translation unit.
880 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000881
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000882 /// EmitClassExtension - Generate the class extension structure used
883 /// to store the weak ivar layout and properties. The return value
884 /// has type ClassExtensionPtrTy.
885 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
886
887 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
888 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000889 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000890 const ObjCInterfaceDecl *ID);
891
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000892 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000893 QualType ResultType,
894 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000895 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000896 QualType Arg0Ty,
897 bool IsSuper,
898 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000899
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000900 /// EmitIvarList - Emit the ivar list for the given
901 /// implementation. If ForClass is true the list of class ivars
902 /// (i.e. metaclass ivars) is emitted, otherwise the list of
903 /// interface ivars will be emitted. The return value has type
904 /// IvarListPtrTy.
905 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000906 bool ForClass);
907
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000908 /// EmitMetaClass - Emit a forward reference to the class structure
909 /// for the metaclass of the given interface. The return value has
910 /// type ClassPtrTy.
911 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
912
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000913 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000914 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000915 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
916 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000917 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000918 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000919
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000920 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000921
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000922 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000923
924 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000925 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000926 llvm::Constant *EmitMethodList(const std::string &Name,
927 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000928 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000929
930 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000931 /// method declarations.
932 /// - TypeName: The name for the type containing the methods.
933 /// - IsProtocol: True iff these methods are for a protocol.
934 /// - ClassMethds: True iff these are class methods.
935 /// - Required: When true, only "required" methods are
936 /// listed. Similarly, when false only "optional" methods are
937 /// listed. For classes this should always be true.
938 /// - begin, end: The method list to output.
939 ///
940 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000941 llvm::Constant *EmitMethodDescList(const std::string &Name,
942 const char *Section,
943 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000944
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000945 /// GetOrEmitProtocol - Get the protocol object for the given
946 /// declaration, emitting it if necessary. The return value has type
947 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000948 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000949
950 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
951 /// object for the given declaration, emitting it if needed. These
952 /// forward references will be filled in with empty bodies if no
953 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000954 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000955
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000956 /// EmitProtocolExtension - Generate the protocol extension
957 /// structure used to store optional instance and class methods, and
958 /// protocol properties. The return value has type
959 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000960 llvm::Constant *
961 EmitProtocolExtension(const ObjCProtocolDecl *PD,
962 const ConstantVector &OptInstanceMethods,
963 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000964
965 /// EmitProtocolList - Generate the list of referenced
966 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000967 llvm::Constant *EmitProtocolList(const std::string &Name,
968 ObjCProtocolDecl::protocol_iterator begin,
969 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000970
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000971 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
972 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000973 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000974
Fariborz Jahanianda320092009-01-29 19:24:30 +0000975 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000976 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000977
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000978 virtual llvm::Function *ModuleInitFunction();
979
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000980 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000981 QualType ResultType,
982 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000983 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000984 bool IsClassMessage,
985 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000986
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000987 virtual CodeGen::RValue
988 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000989 QualType ResultType,
990 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000991 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000992 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000993 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000994 bool IsClassMessage,
995 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000996
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000997 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000998 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000999
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001000 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001001
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001002 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001003
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001004 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001005
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001006 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001007 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001008
Chris Lattner74391b42009-03-22 21:03:39 +00001009 virtual llvm::Constant *GetPropertyGetFunction();
1010 virtual llvm::Constant *GetPropertySetFunction();
1011 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001012
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001013 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1014 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001015 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1016 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001017 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001018 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001019 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1020 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001021 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1022 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001023 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1024 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001025 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1026 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001027
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001028 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1029 QualType ObjectTy,
1030 llvm::Value *BaseValue,
1031 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001032 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001033 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001034 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001035 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001036};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001037
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001038class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001039private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001040 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001041 llvm::GlobalVariable* ObjCEmptyCacheVar;
1042 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001043
Daniel Dunbar11394522009-04-18 08:51:00 +00001044 /// SuperClassReferences - uniqued super class references.
1045 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1046
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001047 /// MetaClassReferences - uniqued meta class references.
1048 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001049
1050 /// EHTypeReferences - uniqued class ehtype references.
1051 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001052
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001053 /// FinishNonFragileABIModule - Write out global data structures at the end of
1054 /// processing a translation unit.
1055 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001056
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001057 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1058 unsigned InstanceStart,
1059 unsigned InstanceSize,
1060 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001061 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1062 llvm::Constant *IsAGV,
1063 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001064 llvm::Constant *ClassRoGV,
1065 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001066
1067 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1068
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001069 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1070
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001071 /// EmitMethodList - Emit the method list for the given
1072 /// implementation. The return value has type MethodListnfABITy.
1073 llvm::Constant *EmitMethodList(const std::string &Name,
1074 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001075 const ConstantVector &Methods);
1076 /// EmitIvarList - Emit the ivar list for the given
1077 /// implementation. If ForClass is true the list of class ivars
1078 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1079 /// interface ivars will be emitted. The return value has type
1080 /// IvarListnfABIPtrTy.
1081 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001082
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001083 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001084 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001085 unsigned long int offset);
1086
Fariborz Jahanianda320092009-01-29 19:24:30 +00001087 /// GetOrEmitProtocol - Get the protocol object for the given
1088 /// declaration, emitting it if necessary. The return value has type
1089 /// ProtocolPtrTy.
1090 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1091
1092 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1093 /// object for the given declaration, emitting it if needed. These
1094 /// forward references will be filled in with empty bodies if no
1095 /// definition is seen. The return value has type ProtocolPtrTy.
1096 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1097
1098 /// EmitProtocolList - Generate the list of referenced
1099 /// protocols. The return value has type ProtocolListPtrTy.
1100 llvm::Constant *EmitProtocolList(const std::string &Name,
1101 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001102 ObjCProtocolDecl::protocol_iterator end);
1103
1104 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1105 QualType ResultType,
1106 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001107 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001108 QualType Arg0Ty,
1109 bool IsSuper,
1110 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001111
1112 /// GetClassGlobal - Return the global variable for the Objective-C
1113 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001114 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1115
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001116 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001117 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001118 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001119 const ObjCInterfaceDecl *ID);
1120
1121 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1122 /// for the given super class reference.
1123 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1124 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001125
1126 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1127 /// meta-data
1128 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1129 const ObjCInterfaceDecl *ID);
1130
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001131 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1132 /// the given ivar.
1133 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001134 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001135 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001136 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001137
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001138 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1139 /// for the given selector.
1140 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001141
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001142 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001143 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001144 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1145 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001146
1147 const char *getMetaclassSymbolPrefix() const {
1148 return "OBJC_METACLASS_$_";
1149 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001150
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001151 const char *getClassSymbolPrefix() const {
1152 return "OBJC_CLASS_$_";
1153 }
1154
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001155 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1156 uint32_t &InstanceStart,
1157 uint32_t &InstanceSize);
1158
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001159public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001160 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001161 // FIXME. All stubs for now!
1162 virtual llvm::Function *ModuleInitFunction();
1163
1164 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1165 QualType ResultType,
1166 Selector Sel,
1167 llvm::Value *Receiver,
1168 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001169 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001170
1171 virtual CodeGen::RValue
1172 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1173 QualType ResultType,
1174 Selector Sel,
1175 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001176 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001177 llvm::Value *Receiver,
1178 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001179 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001180
1181 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001182 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001183
1184 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001185 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001186
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001187 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001188
1189 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001190 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001191 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001192
Chris Lattner74391b42009-03-22 21:03:39 +00001193 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001194 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001195 }
Chris Lattner74391b42009-03-22 21:03:39 +00001196 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001197 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001198 }
Chris Lattner74391b42009-03-22 21:03:39 +00001199 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001200 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001201 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001202
1203 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001204 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001205 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001206 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001207 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001208 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001209 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001210 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001211 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001212 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001213 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001214 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001215 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001216 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001217 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1218 QualType ObjectTy,
1219 llvm::Value *BaseValue,
1220 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001221 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001222 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001223 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001224 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001225};
1226
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001227} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001228
1229/* *** Helper Functions *** */
1230
1231/// getConstantGEP() - Help routine to construct simple GEPs.
1232static llvm::Constant *getConstantGEP(llvm::Constant *C,
1233 unsigned idx0,
1234 unsigned idx1) {
1235 llvm::Value *Idxs[] = {
1236 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1237 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1238 };
1239 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1240}
1241
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001242/// hasObjCExceptionAttribute - Return true if this class or any super
1243/// class has the __objc_exception__ attribute.
1244static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001245 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001246 return true;
1247 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1248 return hasObjCExceptionAttribute(Super);
1249 return false;
1250}
1251
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001252/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001253
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001254CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1255 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001256{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001257 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001258 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001259}
1260
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001261/// GetClass - Return a reference to the class for the given interface
1262/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001263llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001264 const ObjCInterfaceDecl *ID) {
1265 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001266}
1267
1268/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001269llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001270 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001271}
1272
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001273/// Generate a constant CFString object.
1274/*
1275 struct __builtin_CFString {
1276 const int *isa; // point to __CFConstantStringClassReference
1277 int flags;
1278 const char *str;
1279 long length;
1280 };
1281*/
1282
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001283llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001284 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001285 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001286}
1287
1288/// Generates a message send where the super is the receiver. This is
1289/// a message send to self with special delivery semantics indicating
1290/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001291CodeGen::RValue
1292CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001293 QualType ResultType,
1294 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001295 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001296 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001297 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001298 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001299 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001300 // Create and init a super structure; this is a (receiver, class)
1301 // pair we will pass to objc_msgSendSuper.
1302 llvm::Value *ObjCSuper =
1303 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1304 llvm::Value *ReceiverAsObject =
1305 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1306 CGF.Builder.CreateStore(ReceiverAsObject,
1307 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001308
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001309 // If this is a class message the metaclass is passed as the target.
1310 llvm::Value *Target;
1311 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001312 if (isCategoryImpl) {
1313 // Message sent to 'super' in a class method defined in a category
1314 // implementation requires an odd treatment.
1315 // If we are in a class method, we must retrieve the
1316 // _metaclass_ for the current class, pointed at by
1317 // the class's "isa" pointer. The following assumes that
1318 // isa" is the first ivar in a class (which it must be).
1319 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1320 Target = CGF.Builder.CreateStructGEP(Target, 0);
1321 Target = CGF.Builder.CreateLoad(Target);
1322 }
1323 else {
1324 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1325 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1326 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1327 Target = Super;
1328 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001329 } else {
1330 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1331 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001332 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1333 // and ObjCTypes types.
1334 const llvm::Type *ClassTy =
1335 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001336 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001337 CGF.Builder.CreateStore(Target,
1338 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1339
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001340 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001341 ObjCSuper, ObjCTypes.SuperPtrCTy,
1342 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001343}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001344
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001345/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001346CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001347 QualType ResultType,
1348 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001349 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001350 bool IsClassMessage,
1351 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001352 llvm::Value *Arg0 =
1353 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001354 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001355 Arg0, CGF.getContext().getObjCIdType(),
1356 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001357}
1358
1359CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001360 QualType ResultType,
1361 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001362 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001363 QualType Arg0Ty,
1364 bool IsSuper,
1365 const CallArgList &CallArgs) {
1366 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001367 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1368 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1369 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001370 CGF.getContext().getObjCSelType()));
1371 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001372
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001373 CodeGenTypes &Types = CGM.getTypes();
1374 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1375 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001376
1377 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001378 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001379 Fn = ObjCTypes.getSendStretFn(IsSuper);
1380 } else if (ResultType->isFloatingType()) {
1381 // FIXME: Sadly, this is wrong. This actually depends on the
1382 // architecture. This happens to be right for x86-32 though.
1383 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1384 } else {
1385 Fn = ObjCTypes.getSendFn(IsSuper);
1386 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001387 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001388 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001389}
1390
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001391llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001392 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001393 // FIXME: I don't understand why gcc generates this, or where it is
1394 // resolved. Investigate. Its also wasteful to look this up over and
1395 // over.
1396 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1397
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001398 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1399 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001400}
1401
Fariborz Jahanianda320092009-01-29 19:24:30 +00001402void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001403 // FIXME: We shouldn't need this, the protocol decl should contain
1404 // enough information to tell us whether this was a declaration or a
1405 // definition.
1406 DefinedProtocols.insert(PD->getIdentifier());
1407
1408 // If we have generated a forward reference to this protocol, emit
1409 // it now. Otherwise do nothing, the protocol objects are lazily
1410 // emitted.
1411 if (Protocols.count(PD->getIdentifier()))
1412 GetOrEmitProtocol(PD);
1413}
1414
Fariborz Jahanianda320092009-01-29 19:24:30 +00001415llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001416 if (DefinedProtocols.count(PD->getIdentifier()))
1417 return GetOrEmitProtocol(PD);
1418 return GetOrEmitProtocolRef(PD);
1419}
1420
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001421/*
1422 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1423 struct _objc_protocol {
1424 struct _objc_protocol_extension *isa;
1425 char *protocol_name;
1426 struct _objc_protocol_list *protocol_list;
1427 struct _objc__method_prototype_list *instance_methods;
1428 struct _objc__method_prototype_list *class_methods
1429 };
1430
1431 See EmitProtocolExtension().
1432*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001433llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1434 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1435
1436 // Early exit if a defining object has already been generated.
1437 if (Entry && Entry->hasInitializer())
1438 return Entry;
1439
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001440 // FIXME: I don't understand why gcc generates this, or where it is
1441 // resolved. Investigate. Its also wasteful to look this up over and
1442 // over.
1443 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1444
Chris Lattner8ec03f52008-11-24 03:54:41 +00001445 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001446
1447 // Construct method lists.
1448 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1449 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001450 for (ObjCProtocolDecl::instmeth_iterator
1451 i = PD->instmeth_begin(CGM.getContext()),
1452 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001453 ObjCMethodDecl *MD = *i;
1454 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1455 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1456 OptInstanceMethods.push_back(C);
1457 } else {
1458 InstanceMethods.push_back(C);
1459 }
1460 }
1461
Douglas Gregor6ab35242009-04-09 21:40:53 +00001462 for (ObjCProtocolDecl::classmeth_iterator
1463 i = PD->classmeth_begin(CGM.getContext()),
1464 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001465 ObjCMethodDecl *MD = *i;
1466 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1467 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1468 OptClassMethods.push_back(C);
1469 } else {
1470 ClassMethods.push_back(C);
1471 }
1472 }
1473
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001474 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001475 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001476 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001477 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001478 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001479 PD->protocol_begin(),
1480 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001481 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001482 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1483 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001484 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1485 InstanceMethods);
1486 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001487 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1488 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001489 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1490 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001491 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1492 Values);
1493
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001494 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001495 // Already created, fix the linkage and update the initializer.
1496 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001497 Entry->setInitializer(Init);
1498 } else {
1499 Entry =
1500 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1501 llvm::GlobalValue::InternalLinkage,
1502 Init,
1503 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1504 &CGM.getModule());
1505 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001506 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001507 UsedGlobals.push_back(Entry);
1508 // FIXME: Is this necessary? Why only for protocol?
1509 Entry->setAlignment(4);
1510 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001511
1512 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001513}
1514
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001515llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001516 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1517
1518 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001519 // We use the initializer as a marker of whether this is a forward
1520 // reference or not. At module finalization we add the empty
1521 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001522 Entry =
1523 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001524 llvm::GlobalValue::ExternalLinkage,
1525 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001526 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001527 &CGM.getModule());
1528 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001529 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001530 UsedGlobals.push_back(Entry);
1531 // FIXME: Is this necessary? Why only for protocol?
1532 Entry->setAlignment(4);
1533 }
1534
1535 return Entry;
1536}
1537
1538/*
1539 struct _objc_protocol_extension {
1540 uint32_t size;
1541 struct objc_method_description_list *optional_instance_methods;
1542 struct objc_method_description_list *optional_class_methods;
1543 struct objc_property_list *instance_properties;
1544 };
1545*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001546llvm::Constant *
1547CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1548 const ConstantVector &OptInstanceMethods,
1549 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001550 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001551 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001552 std::vector<llvm::Constant*> Values(4);
1553 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001554 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001555 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1556 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001557 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1558 OptInstanceMethods);
1559 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001560 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1561 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001562 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1563 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001564 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1565 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001566 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001567
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001569 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1570 Values[3]->isNullValue())
1571 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1572
1573 llvm::Constant *Init =
1574 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001575
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001576 // No special section, but goes in llvm.used
1577 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1578 Init,
1579 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001580}
1581
1582/*
1583 struct objc_protocol_list {
1584 struct objc_protocol_list *next;
1585 long count;
1586 Protocol *list[];
1587 };
1588*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001589llvm::Constant *
1590CGObjCMac::EmitProtocolList(const std::string &Name,
1591 ObjCProtocolDecl::protocol_iterator begin,
1592 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001593 std::vector<llvm::Constant*> ProtocolRefs;
1594
Daniel Dunbardbc933702008-08-21 21:57:41 +00001595 for (; begin != end; ++begin)
1596 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001597
1598 // Just return null for empty protocol lists
1599 if (ProtocolRefs.empty())
1600 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1601
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001602 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001603 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1604
1605 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001606 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001607 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1608 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1609 Values[2] =
1610 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1611 ProtocolRefs.size()),
1612 ProtocolRefs);
1613
1614 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1615 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001616 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001617 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001618 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1619}
1620
1621/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001622 struct _objc_property {
1623 const char * const name;
1624 const char * const attributes;
1625 };
1626
1627 struct _objc_property_list {
1628 uint32_t entsize; // sizeof (struct _objc_property)
1629 uint32_t prop_count;
1630 struct _objc_property[prop_count];
1631 };
1632*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001633llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1634 const Decl *Container,
1635 const ObjCContainerDecl *OCD,
1636 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001637 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001638 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1639 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001640 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001641 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001642 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001643 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1644 Prop));
1645 }
1646
1647 // Return null for empty list.
1648 if (Properties.empty())
1649 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1650
1651 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001652 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001653 std::vector<llvm::Constant*> Values(3);
1654 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1655 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1656 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1657 Properties.size());
1658 Values[2] = llvm::ConstantArray::get(AT, Properties);
1659 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1660
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001661 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001662 CreateMetadataVar(Name, Init,
1663 (ObjCABI == 2) ? "__DATA, __objc_const" :
1664 "__OBJC,__property,regular,no_dead_strip",
1665 (ObjCABI == 2) ? 8 : 4,
1666 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001667 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001668}
1669
1670/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001671 struct objc_method_description_list {
1672 int count;
1673 struct objc_method_description list[];
1674 };
1675*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001676llvm::Constant *
1677CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1678 std::vector<llvm::Constant*> Desc(2);
1679 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1680 ObjCTypes.SelectorPtrTy);
1681 Desc[1] = GetMethodVarType(MD);
1682 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1683 Desc);
1684}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001685
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001686llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1687 const char *Section,
1688 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001689 // Return null for empty list.
1690 if (Methods.empty())
1691 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1692
1693 std::vector<llvm::Constant*> Values(2);
1694 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1695 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1696 Methods.size());
1697 Values[1] = llvm::ConstantArray::get(AT, Methods);
1698 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1699
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001700 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001701 return llvm::ConstantExpr::getBitCast(GV,
1702 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001703}
1704
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001705/*
1706 struct _objc_category {
1707 char *category_name;
1708 char *class_name;
1709 struct _objc_method_list *instance_methods;
1710 struct _objc_method_list *class_methods;
1711 struct _objc_protocol_list *protocols;
1712 uint32_t size; // <rdar://4585769>
1713 struct _objc_property_list *instance_properties;
1714 };
1715 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001716void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001717 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001718
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001719 // FIXME: This is poor design, the OCD should have a pointer to the
1720 // category decl. Additionally, note that Category can be null for
1721 // the @implementation w/o an @interface case. Sema should just
1722 // create one for us as it does for @implementation so everyone else
1723 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001724 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001725 const ObjCCategoryDecl *Category =
1726 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001727 std::string ExtName(Interface->getNameAsString() + "_" +
1728 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001729
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001730 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1731 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1732 e = OCD->instmeth_end(); i != e; ++i) {
1733 // Instance methods should always be defined.
1734 InstanceMethods.push_back(GetMethodConstant(*i));
1735 }
1736 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1737 e = OCD->classmeth_end(); i != e; ++i) {
1738 // Class methods should always be defined.
1739 ClassMethods.push_back(GetMethodConstant(*i));
1740 }
1741
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001742 std::vector<llvm::Constant*> Values(7);
1743 Values[0] = GetClassName(OCD->getIdentifier());
1744 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001745 Values[2] =
1746 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1747 ExtName,
1748 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001749 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001750 Values[3] =
1751 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001752 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001753 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001754 if (Category) {
1755 Values[4] =
1756 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1757 Category->protocol_begin(),
1758 Category->protocol_end());
1759 } else {
1760 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1761 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001762 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001763
1764 // If there is no category @interface then there can be no properties.
1765 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001766 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001767 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001768 } else {
1769 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1770 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001771
1772 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1773 Values);
1774
1775 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001776 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1777 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001778 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001779 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001780}
1781
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001782// FIXME: Get from somewhere?
1783enum ClassFlags {
1784 eClassFlags_Factory = 0x00001,
1785 eClassFlags_Meta = 0x00002,
1786 // <rdr://5142207>
1787 eClassFlags_HasCXXStructors = 0x02000,
1788 eClassFlags_Hidden = 0x20000,
1789 eClassFlags_ABI2_Hidden = 0x00010,
1790 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1791};
1792
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001793/*
1794 struct _objc_class {
1795 Class isa;
1796 Class super_class;
1797 const char *name;
1798 long version;
1799 long info;
1800 long instance_size;
1801 struct _objc_ivar_list *ivars;
1802 struct _objc_method_list *methods;
1803 struct _objc_cache *cache;
1804 struct _objc_protocol_list *protocols;
1805 // Objective-C 1.0 extensions (<rdr://4585769>)
1806 const char *ivar_layout;
1807 struct _objc_class_ext *ext;
1808 };
1809
1810 See EmitClassExtension();
1811 */
1812void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001813 DefinedSymbols.insert(ID->getIdentifier());
1814
Chris Lattner8ec03f52008-11-24 03:54:41 +00001815 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001816 // FIXME: Gross
1817 ObjCInterfaceDecl *Interface =
1818 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001819 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001820 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001821 Interface->protocol_begin(),
1822 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001823 const llvm::Type *InterfaceTy;
1824 if (Interface->isForwardDecl())
1825 InterfaceTy = llvm::StructType::get(NULL, NULL);
1826 else
1827 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001828 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001829 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001830 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001831
1832 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001833 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001834 Flags |= eClassFlags_Hidden;
1835
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001836 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1837 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1838 e = ID->instmeth_end(); i != e; ++i) {
1839 // Instance methods should always be defined.
1840 InstanceMethods.push_back(GetMethodConstant(*i));
1841 }
1842 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1843 e = ID->classmeth_end(); i != e; ++i) {
1844 // Class methods should always be defined.
1845 ClassMethods.push_back(GetMethodConstant(*i));
1846 }
1847
1848 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1849 e = ID->propimpl_end(); i != e; ++i) {
1850 ObjCPropertyImplDecl *PID = *i;
1851
1852 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1853 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1854
1855 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1856 if (llvm::Constant *C = GetMethodConstant(MD))
1857 InstanceMethods.push_back(C);
1858 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1859 if (llvm::Constant *C = GetMethodConstant(MD))
1860 InstanceMethods.push_back(C);
1861 }
1862 }
1863
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001864 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001865 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001866 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001867 // Record a reference to the super class.
1868 LazySymbols.insert(Super->getIdentifier());
1869
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001870 Values[ 1] =
1871 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1872 ObjCTypes.ClassPtrTy);
1873 } else {
1874 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1875 }
1876 Values[ 2] = GetClassName(ID->getIdentifier());
1877 // Version is always 0.
1878 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1879 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1880 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001881 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001882 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001883 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001884 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001885 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001886 // cache is always NULL.
1887 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1888 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001889 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001890 // Values[10] = BuildIvarLayout(ID, true);
1891 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001892 Values[11] = EmitClassExtension(ID);
1893 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1894 Values);
1895
1896 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001897 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1898 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001899 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001900 DefinedClasses.push_back(GV);
1901}
1902
1903llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1904 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001905 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001906 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001907 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001908 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001909
Daniel Dunbar04d40782009-04-14 06:00:08 +00001910 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001911 Flags |= eClassFlags_Hidden;
1912
1913 std::vector<llvm::Constant*> Values(12);
1914 // The isa for the metaclass is the root of the hierarchy.
1915 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1916 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1917 Root = Super;
1918 Values[ 0] =
1919 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1920 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001921 // The super class for the metaclass is emitted as the name of the
1922 // super class. The runtime fixes this up to point to the
1923 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001924 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1925 Values[ 1] =
1926 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1927 ObjCTypes.ClassPtrTy);
1928 } else {
1929 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1930 }
1931 Values[ 2] = GetClassName(ID->getIdentifier());
1932 // Version is always 0.
1933 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1934 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1935 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001936 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001937 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001938 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001939 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001940 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001941 // cache is always NULL.
1942 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1943 Values[ 9] = Protocols;
1944 // ivar_layout for metaclass is always NULL.
1945 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1946 // The class extension is always unused for metaclasses.
1947 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1948 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1949 Values);
1950
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001951 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001952 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001953
1954 // Check for a forward reference.
1955 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1956 if (GV) {
1957 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1958 "Forward metaclass reference has incorrect type.");
1959 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1960 GV->setInitializer(Init);
1961 } else {
1962 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1963 llvm::GlobalValue::InternalLinkage,
1964 Init, Name,
1965 &CGM.getModule());
1966 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001967 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001968 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001969 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001970
1971 return GV;
1972}
1973
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001974llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001975 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001976
1977 // FIXME: Should we look these up somewhere other than the
1978 // module. Its a bit silly since we only generate these while
1979 // processing an implementation, so exactly one pointer would work
1980 // if know when we entered/exitted an implementation block.
1981
1982 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001983 // Previously, metaclass with internal linkage may have been defined.
1984 // pass 'true' as 2nd argument so it is returned.
1985 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001986 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1987 "Forward metaclass reference has incorrect type.");
1988 return GV;
1989 } else {
1990 // Generate as an external reference to keep a consistent
1991 // module. This will be patched up when we emit the metaclass.
1992 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1993 llvm::GlobalValue::ExternalLinkage,
1994 0,
1995 Name,
1996 &CGM.getModule());
1997 }
1998}
1999
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000/*
2001 struct objc_class_ext {
2002 uint32_t size;
2003 const char *weak_ivar_layout;
2004 struct _objc_property_list *properties;
2005 };
2006*/
2007llvm::Constant *
2008CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2009 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002010 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002011
2012 std::vector<llvm::Constant*> Values(3);
2013 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002014 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002015 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002016 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002017 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002018 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002019
2020 // Return null if no extension bits are used.
2021 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2022 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2023
2024 llvm::Constant *Init =
2025 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002026 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002027 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2028 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002029}
2030
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002031/// getInterfaceDeclForIvar - Get the interface declaration node where
2032/// this ivar is declared in.
2033/// FIXME. Ideally, this info should be in the ivar node. But currently
2034/// it is not and prevailing wisdom is that ASTs should not have more
2035/// info than is absolutely needed, even though this info reflects the
2036/// source language.
2037///
2038static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2039 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002040 const ObjCIvarDecl *IVD,
2041 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002042 if (!OI)
2043 return 0;
2044 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2045 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2046 E = OI->ivar_end(); I != E; ++I)
2047 if ((*I)->getIdentifier() == IVD->getIdentifier())
2048 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002049 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002050 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2051 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002052 ObjCPropertyDecl *PDecl = (*I);
2053 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2054 if (IV->getIdentifier() == IVD->getIdentifier())
2055 return OI;
2056 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002057 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002058}
2059
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002060/*
2061 struct objc_ivar {
2062 char *ivar_name;
2063 char *ivar_type;
2064 int ivar_offset;
2065 };
2066
2067 struct objc_ivar_list {
2068 int ivar_count;
2069 struct objc_ivar list[count];
2070 };
2071 */
2072llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002073 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002074 std::vector<llvm::Constant*> Ivars, Ivar(3);
2075
2076 // When emitting the root class GCC emits ivar entries for the
2077 // actual class structure. It is not clear if we need to follow this
2078 // behavior; for now lets try and get away with not doing it. If so,
2079 // the cleanest solution would be to make up an ObjCInterfaceDecl
2080 // for the class.
2081 if (ForClass)
2082 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002083
2084 ObjCInterfaceDecl *OID =
2085 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002086
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002087 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2088 GetNamedIvarList(OID, OIvars);
2089
2090 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2091 ObjCIvarDecl *IVD = OIvars[i];
2092 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002093 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00002094 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002095 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002096 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002097 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002098 }
2099
2100 // Return null for empty list.
2101 if (Ivars.empty())
2102 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2103
2104 std::vector<llvm::Constant*> Values(2);
2105 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2106 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2107 Ivars.size());
2108 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2109 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2110
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002111 llvm::GlobalVariable *GV;
2112 if (ForClass)
2113 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002114 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2115 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002116 else
2117 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2118 + ID->getNameAsString(),
2119 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002120 4, true);
2121 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002122}
2123
2124/*
2125 struct objc_method {
2126 SEL method_name;
2127 char *method_types;
2128 void *method;
2129 };
2130
2131 struct objc_method_list {
2132 struct objc_method_list *obsolete;
2133 int count;
2134 struct objc_method methods_list[count];
2135 };
2136*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002137
2138/// GetMethodConstant - Return a struct objc_method constant for the
2139/// given method if it has been defined. The result is null if the
2140/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002141llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002142 // FIXME: Use DenseMap::lookup
2143 llvm::Function *Fn = MethodDefinitions[MD];
2144 if (!Fn)
2145 return 0;
2146
2147 std::vector<llvm::Constant*> Method(3);
2148 Method[0] =
2149 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2150 ObjCTypes.SelectorPtrTy);
2151 Method[1] = GetMethodVarType(MD);
2152 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2153 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2154}
2155
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002156llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2157 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002158 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002159 // Return null for empty list.
2160 if (Methods.empty())
2161 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2162
2163 std::vector<llvm::Constant*> Values(3);
2164 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2165 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2166 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2167 Methods.size());
2168 Values[2] = llvm::ConstantArray::get(AT, Methods);
2169 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2170
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002171 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002172 return llvm::ConstantExpr::getBitCast(GV,
2173 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002174}
2175
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002176llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002177 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002178 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002179 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002180
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002181 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002182 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002183 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002184 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002185 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002186 llvm::GlobalValue::InternalLinkage,
2187 Name,
2188 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002189 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002190
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002191 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002192}
2193
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002194/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002195uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2196 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002197 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002198 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002199 if (!OI)
2200 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002201 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002202}
2203
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002204llvm::GlobalVariable *
2205CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2206 llvm::Constant *Init,
2207 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002208 unsigned Align,
2209 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002210 const llvm::Type *Ty = Init->getType();
2211 llvm::GlobalVariable *GV =
2212 new llvm::GlobalVariable(Ty, false,
2213 llvm::GlobalValue::InternalLinkage,
2214 Init,
2215 Name,
2216 &CGM.getModule());
2217 if (Section)
2218 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002219 if (Align)
2220 GV->setAlignment(Align);
2221 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002222 UsedGlobals.push_back(GV);
2223 return GV;
2224}
2225
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002226llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002227 // Abuse this interface function as a place to finalize.
2228 FinishModule();
2229
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002230 return NULL;
2231}
2232
Chris Lattner74391b42009-03-22 21:03:39 +00002233llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002234 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002235}
2236
Chris Lattner74391b42009-03-22 21:03:39 +00002237llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002238 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002239}
2240
Chris Lattner74391b42009-03-22 21:03:39 +00002241llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002242 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002243}
2244
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002245/*
2246
2247Objective-C setjmp-longjmp (sjlj) Exception Handling
2248--
2249
2250The basic framework for a @try-catch-finally is as follows:
2251{
2252 objc_exception_data d;
2253 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002254 bool _call_try_exit = true;
2255
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002256 objc_exception_try_enter(&d);
2257 if (!setjmp(d.jmp_buf)) {
2258 ... try body ...
2259 } else {
2260 // exception path
2261 id _caught = objc_exception_extract(&d);
2262
2263 // enter new try scope for handlers
2264 if (!setjmp(d.jmp_buf)) {
2265 ... match exception and execute catch blocks ...
2266
2267 // fell off end, rethrow.
2268 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002269 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002270 } else {
2271 // exception in catch block
2272 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002273 _call_try_exit = false;
2274 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002275 }
2276 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002277 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002278
2279finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002280 if (_call_try_exit)
2281 objc_exception_try_exit(&d);
2282
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002283 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002284 ... dispatch to finally destination ...
2285
2286finally_rethrow:
2287 objc_exception_throw(_rethrow);
2288
2289finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002290}
2291
2292This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002293uses _rethrow to determine if objc_exception_try_exit should be called
2294and if the object should be rethrown. This breaks in the face of
2295throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002296
2297We specialize this framework for a few particular circumstances:
2298
2299 - If there are no catch blocks, then we avoid emitting the second
2300 exception handling context.
2301
2302 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2303 e)) we avoid emitting the code to rethrow an uncaught exception.
2304
2305 - FIXME: If there is no @finally block we can do a few more
2306 simplifications.
2307
2308Rethrows and Jumps-Through-Finally
2309--
2310
2311Support for implicit rethrows and jumping through the finally block is
2312handled by storing the current exception-handling context in
2313ObjCEHStack.
2314
Daniel Dunbar898d5082008-09-30 01:06:03 +00002315In order to implement proper @finally semantics, we support one basic
2316mechanism for jumping through the finally block to an arbitrary
2317destination. Constructs which generate exits from a @try or @catch
2318block use this mechanism to implement the proper semantics by chaining
2319jumps, as necessary.
2320
2321This mechanism works like the one used for indirect goto: we
2322arbitrarily assign an ID to each destination and store the ID for the
2323destination in a variable prior to entering the finally block. At the
2324end of the finally block we simply create a switch to the proper
2325destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002326
2327Code gen for @synchronized(expr) stmt;
2328Effectively generating code for:
2329objc_sync_enter(expr);
2330@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002331*/
2332
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002333void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2334 const Stmt &S) {
2335 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002336 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002337 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002338 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002339 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2340 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2341 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002342
2343 // For @synchronized, call objc_sync_enter(sync.expr). The
2344 // evaluation of the expression must occur before we enter the
2345 // @synchronized. We can safely avoid a temp here because jumps into
2346 // @synchronized are illegal & this will dominate uses.
2347 llvm::Value *SyncArg = 0;
2348 if (!isTry) {
2349 SyncArg =
2350 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2351 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002352 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002353 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002354
2355 // Push an EH context entry, used for handling rethrows and jumps
2356 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002357 CGF.PushCleanupBlock(FinallyBlock);
2358
Anders Carlsson273558f2009-02-07 21:37:21 +00002359 CGF.ObjCEHValueStack.push_back(0);
2360
Daniel Dunbar898d5082008-09-30 01:06:03 +00002361 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002362 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2363 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002364 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2365 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002366 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2367 "_call_try_exit");
2368 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2369
Anders Carlsson80f25672008-09-09 17:59:25 +00002370 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002371 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002372 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2373 "jmpbufarray");
2374 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002375 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002376 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002377
Daniel Dunbar55e87422008-11-11 02:29:29 +00002378 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2379 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002380 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002381 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002382
2383 // Emit the @try block.
2384 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002385 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2386 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002387 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002388
2389 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002390 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002391
2392 // Retrieve the exception object. We may emit multiple blocks but
2393 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002394 llvm::Value *Caught =
2395 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2396 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002397 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002398 if (!isTry)
2399 {
2400 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002401 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002402 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002403 }
2404 else if (const ObjCAtCatchStmt* CatchStmt =
2405 cast<ObjCAtTryStmt>(S).getCatchStmts())
2406 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002407 // Enter a new exception try block (in case a @catch block throws
2408 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002409 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002410
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 Dunbar91cd3202008-10-02 17:05:36 +00002413 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002414
Daniel Dunbar55e87422008-11-11 02:29:29 +00002415 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2416 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002417 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002418
2419 CGF.EmitBlock(CatchBlock);
2420
Daniel Dunbar55e40722008-09-27 07:03:52 +00002421 // Handle catch list. As a special case we check if everything is
2422 // matched and avoid generating code for falling off the end if
2423 // so.
2424 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002425 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002426 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002427
Steve Naroff7ba138a2009-03-03 19:52:17 +00002428 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002429 const PointerType *PT = 0;
2430
Anders Carlsson80f25672008-09-09 17:59:25 +00002431 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002432 if (!CatchParam) {
2433 AllMatched = true;
2434 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002435 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002436
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002437 // catch(id e) always matches.
2438 // FIXME: For the time being we also match id<X>; this should
2439 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002440 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002441 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002442 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002443 }
2444
Daniel Dunbar55e40722008-09-27 07:03:52 +00002445 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002446 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002447 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002448 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002449 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002450 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002451
Anders Carlssondde0a942008-09-11 09:15:33 +00002452 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002453 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002454 break;
2455 }
2456
Daniel Dunbar129271a2008-09-27 07:36:24 +00002457 assert(PT && "Unexpected non-pointer type in @catch");
2458 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002459 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002460 assert(ObjCType && "Catch parameter must have Objective-C type!");
2461
2462 // Check if the @catch block matches the exception object.
2463 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2464
Chris Lattner34b02a12009-04-22 02:26:14 +00002465 llvm::Value *Match =
2466 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2467 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002468
Daniel Dunbar55e87422008-11-11 02:29:29 +00002469 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002470
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002471 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002472 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002473
2474 // Emit the @catch block.
2475 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002476 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002477 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002478
2479 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002480 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002481 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002482 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002483
2484 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002485 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002486
2487 CGF.EmitBlock(NextCatchBlock);
2488 }
2489
Daniel Dunbar55e40722008-09-27 07:03:52 +00002490 if (!AllMatched) {
2491 // None of the handlers caught the exception, so store it to be
2492 // rethrown at the end of the @finally block.
2493 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002494 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002495 }
2496
2497 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002498 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002499 CGF.Builder.CreateStore(
2500 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2501 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002502 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002503 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002504 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002505 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002506 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002507 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002508 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002509 }
2510
Daniel Dunbar898d5082008-09-30 01:06:03 +00002511 // Pop the exception-handling stack entry. It is important to do
2512 // this now, because the code in the @finally block is not in this
2513 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002514 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2515
Anders Carlsson273558f2009-02-07 21:37:21 +00002516 CGF.ObjCEHValueStack.pop_back();
2517
Anders Carlsson80f25672008-09-09 17:59:25 +00002518 // Emit the @finally block.
2519 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002520 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2521
2522 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2523
2524 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002525 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002526
2527 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002528 if (isTry) {
2529 if (const ObjCAtFinallyStmt* FinallyStmt =
2530 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2531 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002532 } else {
2533 // Emit objc_sync_exit(expr); as finally's sole statement for
2534 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002535 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002536 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002537
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002538 // Emit the switch block
2539 if (Info.SwitchBlock)
2540 CGF.EmitBlock(Info.SwitchBlock);
2541 if (Info.EndBlock)
2542 CGF.EmitBlock(Info.EndBlock);
2543
Daniel Dunbar898d5082008-09-30 01:06:03 +00002544 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002545 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002546 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002547 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002548
2549 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002550}
2551
2552void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002553 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002554 llvm::Value *ExceptionAsObject;
2555
2556 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2557 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2558 ExceptionAsObject =
2559 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2560 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002561 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002562 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002563 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002564 }
2565
Chris Lattnerbbccd612009-04-22 02:38:11 +00002566 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002567 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002568
2569 // Clear the insertion point to indicate we are in unreachable code.
2570 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002571}
2572
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002573/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002574/// object: objc_read_weak (id *src)
2575///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002576llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002577 llvm::Value *AddrWeakObj)
2578{
Eli Friedman8339b352009-03-07 03:57:15 +00002579 const llvm::Type* DestTy =
2580 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002581 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002582 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002583 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002584 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002585 return read_weak;
2586}
2587
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002588/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2589/// objc_assign_weak (id src, id *dst)
2590///
2591void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2592 llvm::Value *src, llvm::Value *dst)
2593{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002594 const llvm::Type * SrcTy = src->getType();
2595 if (!isa<llvm::PointerType>(SrcTy)) {
2596 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2597 assert(Size <= 8 && "does not support size > 8");
2598 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2599 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002600 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2601 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002602 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2603 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002604 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002605 src, dst, "weakassign");
2606 return;
2607}
2608
Fariborz Jahanian58626502008-11-19 00:59:10 +00002609/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2610/// objc_assign_global (id src, id *dst)
2611///
2612void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2613 llvm::Value *src, llvm::Value *dst)
2614{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002615 const llvm::Type * SrcTy = src->getType();
2616 if (!isa<llvm::PointerType>(SrcTy)) {
2617 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2618 assert(Size <= 8 && "does not support size > 8");
2619 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2620 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002621 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2622 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002623 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2624 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002625 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002626 src, dst, "globalassign");
2627 return;
2628}
2629
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002630/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2631/// objc_assign_ivar (id src, id *dst)
2632///
2633void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2634 llvm::Value *src, llvm::Value *dst)
2635{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002636 const llvm::Type * SrcTy = src->getType();
2637 if (!isa<llvm::PointerType>(SrcTy)) {
2638 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2639 assert(Size <= 8 && "does not support size > 8");
2640 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2641 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002642 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2643 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002644 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2645 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002646 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002647 src, dst, "assignivar");
2648 return;
2649}
2650
Fariborz Jahanian58626502008-11-19 00:59:10 +00002651/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2652/// objc_assign_strongCast (id src, id *dst)
2653///
2654void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2655 llvm::Value *src, llvm::Value *dst)
2656{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002657 const llvm::Type * SrcTy = src->getType();
2658 if (!isa<llvm::PointerType>(SrcTy)) {
2659 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2660 assert(Size <= 8 && "does not support size > 8");
2661 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2662 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002663 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2664 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002665 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2666 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002667 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002668 src, dst, "weakassign");
2669 return;
2670}
2671
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002672/// EmitObjCValueForIvar - Code Gen for ivar reference.
2673///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002674LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2675 QualType ObjectTy,
2676 llvm::Value *BaseValue,
2677 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002678 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002679 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002680 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2681 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002682}
2683
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002684llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002685 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002686 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002687 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002688 return llvm::ConstantInt::get(
2689 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2690 Offset);
2691}
2692
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002693/* *** Private Interface *** */
2694
2695/// EmitImageInfo - Emit the image info marker used to encode some module
2696/// level information.
2697///
2698/// See: <rdr://4810609&4810587&4810587>
2699/// struct IMAGE_INFO {
2700/// unsigned version;
2701/// unsigned flags;
2702/// };
2703enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002704 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2705 // this implies.
2706 eImageInfo_GarbageCollected = (1 << 1),
2707 eImageInfo_GCOnly = (1 << 2),
2708 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2709
2710 // A flag indicating that the module has no instances of an
2711 // @synthesize of a superclass variable. <rdar://problem/6803242>
2712 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002713};
2714
2715void CGObjCMac::EmitImageInfo() {
2716 unsigned version = 0; // Version is unused?
2717 unsigned flags = 0;
2718
2719 // FIXME: Fix and continue?
2720 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2721 flags |= eImageInfo_GarbageCollected;
2722 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2723 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002724
2725 // We never allow @synthesize of a superclass property.
2726 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002727
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002728 // Emitted as int[2];
2729 llvm::Constant *values[2] = {
2730 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2731 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2732 };
2733 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002734
2735 const char *Section;
2736 if (ObjCABI == 1)
2737 Section = "__OBJC, __image_info,regular";
2738 else
2739 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002740 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002741 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2742 llvm::ConstantArray::get(AT, values, 2),
2743 Section,
2744 0,
2745 true);
2746 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002747}
2748
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002749
2750// struct objc_module {
2751// unsigned long version;
2752// unsigned long size;
2753// const char *name;
2754// Symtab symtab;
2755// };
2756
2757// FIXME: Get from somewhere
2758static const int ModuleVersion = 7;
2759
2760void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002761 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002762
2763 std::vector<llvm::Constant*> Values(4);
2764 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2765 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002766 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002767 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002768 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002769 CreateMetadataVar("\01L_OBJC_MODULES",
2770 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2771 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002772 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002773}
2774
2775llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002776 unsigned NumClasses = DefinedClasses.size();
2777 unsigned NumCategories = DefinedCategories.size();
2778
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002779 // Return null if no symbols were defined.
2780 if (!NumClasses && !NumCategories)
2781 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2782
2783 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002784 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2785 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2786 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2787 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2788
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002789 // The runtime expects exactly the list of defined classes followed
2790 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002791 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002792 for (unsigned i=0; i<NumClasses; i++)
2793 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2794 ObjCTypes.Int8PtrTy);
2795 for (unsigned i=0; i<NumCategories; i++)
2796 Symbols[NumClasses + i] =
2797 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2798 ObjCTypes.Int8PtrTy);
2799
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002800 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002801 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002802 NumClasses + NumCategories),
2803 Symbols);
2804
2805 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2806
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002807 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002808 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2809 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002810 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002811 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2812}
2813
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002814llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002815 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002816 LazySymbols.insert(ID->getIdentifier());
2817
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002818 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2819
2820 if (!Entry) {
2821 llvm::Constant *Casted =
2822 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2823 ObjCTypes.ClassPtrTy);
2824 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002825 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2826 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002827 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002828 }
2829
2830 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002831}
2832
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002833llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002834 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2835
2836 if (!Entry) {
2837 llvm::Constant *Casted =
2838 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2839 ObjCTypes.SelectorPtrTy);
2840 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002841 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2842 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002843 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002844 }
2845
2846 return Builder.CreateLoad(Entry, false, "tmp");
2847}
2848
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002849llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002850 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002851
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002852 if (!Entry)
2853 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2854 llvm::ConstantArray::get(Ident->getName()),
2855 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002856 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002857
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002858 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002859}
2860
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002861/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2862/// interface declaration.
2863const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2864 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002865 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar2a031922009-04-22 05:08:15 +00002866 QualType T = CGM.getContext().getObjCInterfaceType(OID);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002867 const llvm::StructType *InterfaceTy =
2868 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2869 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002870}
2871
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002872/// GetIvarLayoutName - Returns a unique constant for the given
2873/// ivar layout bitmap.
2874llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2875 const ObjCCommonTypesHelper &ObjCTypes) {
2876 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2877}
2878
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002879void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2880 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002881 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002882 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002883 unsigned int BytePos, bool ForStrongLayout,
2884 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002885 bool IsUnion = (RD && RD->isUnion());
2886 uint64_t MaxUnionIvarSize = 0;
2887 uint64_t MaxSkippedUnionIvarSize = 0;
2888 FieldDecl *MaxField = 0;
2889 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002890 FieldDecl *LastFieldBitfield = 0;
2891
Chris Lattnerf1690852009-03-31 08:48:01 +00002892 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002893 if (RecFields.empty())
2894 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002895 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002896 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002897 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2898 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2899
2900 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2901
2902 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002903 FieldDecl *Field = RecFields[i];
2904 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002905 if (!Field->getIdentifier() || Field->isBitField()) {
2906 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002907 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002908 }
2909 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002910 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002911 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002912 if (FQT->isUnionType())
2913 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002914 else
2915 assert(FQT->isRecordType() &&
2916 "only union/record is supported for ivar layout bitmap");
2917
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002918 const RecordType *RT = FQT->getAsRecordType();
2919 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002920 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002921 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2922 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002923 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2924 const llvm::StructLayout *RecLayout =
2925 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2926
2927 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002928 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002929 ForStrongLayout, Index, SkIndex,
2930 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002931 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002932 continue;
2933 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002934
2935 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002936 const ConstantArrayType *CArray =
2937 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002938 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002939 assert(CArray && "only array with know element size is supported");
2940 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002941 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2942 const ConstantArrayType *CArray =
2943 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002944 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002945 FQT = CArray->getElementType();
2946 }
2947
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002948 assert(!FQT->isUnionType() &&
2949 "layout for array of unions not supported");
2950 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002951 int OldIndex = Index;
2952 int OldSkIndex = SkIndex;
2953
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002954 // FIXME - Use a common routine with the above!
2955 const RecordType *RT = FQT->getAsRecordType();
2956 const RecordDecl *RD = RT->getDecl();
2957 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002958 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2959 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002960 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2961 const llvm::StructLayout *RecLayout =
2962 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002963
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002964 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002965 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002966 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002967 ForStrongLayout, Index, SkIndex,
2968 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002969 TmpRecFields.clear();
2970
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002971 // Replicate layout information for each array element. Note that
2972 // one element is already done.
2973 uint64_t ElIx = 1;
2974 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2975 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002976 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002977 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2978 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002979 GC_IVAR gcivar;
2980 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2981 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2982 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002983 }
2984
Chris Lattnerf1690852009-03-31 08:48:01 +00002985 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002986 GC_IVAR skivar;
2987 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2988 skivar.ivar_size = SkipIvars[i].ivar_size;
2989 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002990 }
2991 }
2992 continue;
2993 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002994 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002995 // At this point, we are done with Record/Union and array there of.
2996 // For other arrays we are down to its element type.
2997 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2998 do {
2999 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3000 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3001 break;
3002 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003003 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003004 GCAttr = QualType::Strong;
3005 break;
3006 }
3007 else if (const PointerType *PT = FQT->getAsPointerType()) {
3008 FQT = PT->getPointeeType();
3009 }
3010 else {
3011 break;
3012 }
3013 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003014
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003015 if ((ForStrongLayout && GCAttr == QualType::Strong)
3016 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3017 if (IsUnion)
3018 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003019 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3020 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003021 if (UnionIvarSize > MaxUnionIvarSize)
3022 {
3023 MaxUnionIvarSize = UnionIvarSize;
3024 MaxField = Field;
3025 }
3026 }
3027 else
3028 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003029 GC_IVAR gcivar;
3030 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3031 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3032 WordSizeInBits;
3033 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003034 }
3035 }
3036 else if ((ForStrongLayout &&
3037 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3038 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3039 if (IsUnion)
3040 {
3041 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3042 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3043 {
3044 MaxSkippedUnionIvarSize = UnionIvarSize;
3045 MaxSkippedField = Field;
3046 }
3047 }
3048 else
3049 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003050 GC_IVAR skivar;
3051 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3052 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003053 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003054 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003055 }
3056 }
3057 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003058 if (LastFieldBitfield) {
3059 // Last field was a bitfield. Must update skip info.
3060 GC_IVAR skivar;
3061 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3062 LastFieldBitfield);
3063 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3064 uint64_t BitFieldSize =
3065 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3066 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3067 + ((BitFieldSize % ByteSizeInBits) != 0);
3068 SkipIvars.push_back(skivar); ++SkIndex;
3069 }
3070
Chris Lattnerf1690852009-03-31 08:48:01 +00003071 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003072 GC_IVAR gcivar;
3073 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3074 gcivar.ivar_size = MaxUnionIvarSize;
3075 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003076 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003077
3078 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003079 GC_IVAR skivar;
3080 skivar.ivar_bytepos = BytePos +
3081 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3082 skivar.ivar_size = MaxSkippedUnionIvarSize;
3083 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003084 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003085}
3086
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003087static int
Chris Lattnerf1690852009-03-31 08:48:01 +00003088IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003089{
3090 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
3091 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
3092
3093 if (sa < sb)
3094 return -1;
3095 if (sa > sb)
3096 return 1;
3097 return 0;
3098}
3099
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003100/// BuildIvarLayout - Builds ivar layout bitmap for the class
3101/// implementation for the __strong or __weak case.
3102/// The layout map displays which words in ivar list must be skipped
3103/// and which must be scanned by GC (see below). String is built of bytes.
3104/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3105/// of words to skip and right nibble is count of words to scan. So, each
3106/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3107/// represented by a 0x00 byte which also ends the string.
3108/// 1. when ForStrongLayout is true, following ivars are scanned:
3109/// - id, Class
3110/// - object *
3111/// - __strong anything
3112///
3113/// 2. When ForStrongLayout is false, following ivars are scanned:
3114/// - __weak anything
3115///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003116llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003117 const ObjCImplementationDecl *OMD,
3118 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003119 int Index = -1;
3120 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003121 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003122 int SkipScan;
3123 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003124 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3125 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3126 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003127
Chris Lattnerf1690852009-03-31 08:48:01 +00003128 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003129 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003130 CGM.getContext().CollectObjCIvars(OI, RecFields);
3131 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003132 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003133
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003134 SkipIvars.clear();
3135 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003136
3137 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00003138 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3139 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003140 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003141 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003142
3143 // Sort on byte position in case we encounterred a union nested in
3144 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003145 if (hasUnion && !IvarsInfo.empty())
3146 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3147 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003148 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3149
3150 // Build the string of skip/scan nibbles
3151 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003152 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003153 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003154 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003155 if (IvarsInfo[0].ivar_bytepos == 0) {
3156 WordsToSkip = 0;
3157 WordsToScan = IvarsInfo[0].ivar_size;
3158 }
3159 else {
3160 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3161 WordsToScan = IvarsInfo[0].ivar_size;
3162 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003163 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003164 {
3165 unsigned int TailPrevGCObjC =
3166 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3167 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3168 {
3169 // consecutive 'scanned' object pointers.
3170 WordsToScan += IvarsInfo[i].ivar_size;
3171 }
3172 else
3173 {
3174 // Skip over 'gc'able object pointer which lay over each other.
3175 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3176 continue;
3177 // Must skip over 1 or more words. We save current skip/scan values
3178 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003179 SKIP_SCAN SkScan;
3180 SkScan.skip = WordsToSkip;
3181 SkScan.scan = WordsToScan;
3182 SkipScanIvars.push_back(SkScan); ++SkipScan;
3183
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003184 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003185 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3186 SkScan.scan = 0;
3187 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003188 WordsToSkip = 0;
3189 WordsToScan = IvarsInfo[i].ivar_size;
3190 }
3191 }
3192 if (WordsToScan > 0)
3193 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003194 SKIP_SCAN SkScan;
3195 SkScan.skip = WordsToSkip;
3196 SkScan.scan = WordsToScan;
3197 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003198 }
3199
3200 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003201 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003202 {
3203 int LastByteSkipped =
3204 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3205 int LastByteScanned =
3206 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3207 BytesSkipped = (LastByteSkipped > LastByteScanned);
3208 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3209 if (BytesSkipped)
3210 {
3211 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003212 SKIP_SCAN SkScan;
3213 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3214 SkScan.scan = 0;
3215 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003216 }
3217 }
3218 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3219 // as 0xMN.
3220 for (int i = 0; i <= SkipScan; i++)
3221 {
3222 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3223 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3224 // 0xM0 followed by 0x0N detected.
3225 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3226 for (int j = i+1; j < SkipScan; j++)
3227 SkipScanIvars[j] = SkipScanIvars[j+1];
3228 --SkipScan;
3229 }
3230 }
3231
3232 // Generate the string.
3233 std::string BitMap;
3234 for (int i = 0; i <= SkipScan; i++)
3235 {
3236 unsigned char byte;
3237 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3238 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3239 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3240 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3241
3242 if (skip_small > 0 || skip_big > 0)
3243 BytesSkipped = true;
3244 // first skip big.
3245 for (unsigned int ix = 0; ix < skip_big; ix++)
3246 BitMap += (unsigned char)(0xf0);
3247
3248 // next (skip small, scan)
3249 if (skip_small)
3250 {
3251 byte = skip_small << 4;
3252 if (scan_big > 0)
3253 {
3254 byte |= 0xf;
3255 --scan_big;
3256 }
3257 else if (scan_small)
3258 {
3259 byte |= scan_small;
3260 scan_small = 0;
3261 }
3262 BitMap += byte;
3263 }
3264 // next scan big
3265 for (unsigned int ix = 0; ix < scan_big; ix++)
3266 BitMap += (unsigned char)(0x0f);
3267 // last scan small
3268 if (scan_small)
3269 {
3270 byte = scan_small;
3271 BitMap += byte;
3272 }
3273 }
3274 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003275 unsigned char zero = 0;
3276 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003277
3278 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3279 printf("\n%s ivar layout for class '%s': ",
3280 ForStrongLayout ? "strong" : "weak",
3281 OMD->getClassInterface()->getNameAsCString());
3282 const unsigned char *s = (unsigned char*)BitMap.c_str();
3283 for (unsigned i = 0; i < BitMap.size(); i++)
3284 if (!(s[i] & 0xf0))
3285 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3286 else
3287 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3288 printf("\n");
3289 }
3290
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003291 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3292 // final layout.
3293 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003294 return llvm::Constant::getNullValue(PtrTy);
3295 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3296 llvm::ConstantArray::get(BitMap.c_str()),
3297 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003298 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003299 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003300}
3301
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003302llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003303 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3304
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003305 // FIXME: Avoid std::string copying.
3306 if (!Entry)
3307 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3308 llvm::ConstantArray::get(Sel.getAsString()),
3309 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003310 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003311
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003312 return getConstantGEP(Entry, 0, 0);
3313}
3314
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003315// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003316llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003317 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3318}
3319
3320// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003321llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003322 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3323}
3324
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003325llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003326 std::string TypeStr;
3327 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3328
3329 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003330
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003331 if (!Entry)
3332 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3333 llvm::ConstantArray::get(TypeStr),
3334 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003335 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003336
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003337 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003338}
3339
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003340llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003341 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003342 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3343 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003344
3345 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3346
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003347 if (!Entry)
3348 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3349 llvm::ConstantArray::get(TypeStr),
3350 "__TEXT,__cstring,cstring_literals",
3351 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003352
3353 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003354}
3355
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003356// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003357llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003358 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3359
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003360 if (!Entry)
3361 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3362 llvm::ConstantArray::get(Ident->getName()),
3363 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003364 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003365
3366 return getConstantGEP(Entry, 0, 0);
3367}
3368
3369// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003370// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003371llvm::Constant *
3372 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3373 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003374 std::string TypeStr;
3375 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003376 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3377}
3378
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003379void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3380 const ObjCContainerDecl *CD,
3381 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003382 NameOut = '\01';
3383 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003384 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003385 assert (CD && "Missing container decl in GetNameForMethod");
3386 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003387 if (const ObjCCategoryImplDecl *CID =
3388 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3389 NameOut += '(';
3390 NameOut += CID->getNameAsString();
3391 NameOut+= ')';
3392 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003393 NameOut += ' ';
3394 NameOut += D->getSelector().getAsString();
3395 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003396}
3397
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003398void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003399 EmitModuleInfo();
3400
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003401 // Emit the dummy bodies for any protocols which were referenced but
3402 // never defined.
3403 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3404 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3405 if (i->second->hasInitializer())
3406 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003407
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003408 std::vector<llvm::Constant*> Values(5);
3409 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3410 Values[1] = GetClassName(i->first);
3411 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3412 Values[3] = Values[4] =
3413 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3414 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3415 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3416 Values));
3417 }
3418
3419 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003420 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003421 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003422 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003423 }
3424
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003425 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003426 llvm::GlobalValue *GV =
3427 new llvm::GlobalVariable(AT, false,
3428 llvm::GlobalValue::AppendingLinkage,
3429 llvm::ConstantArray::get(AT, Used),
3430 "llvm.used",
3431 &CGM.getModule());
3432
3433 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003434
3435 // Add assembler directives to add lazy undefined symbol references
3436 // for classes which are referenced but not defined. This is
3437 // important for correct linker interaction.
3438
3439 // FIXME: Uh, this isn't particularly portable.
3440 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003441
3442 if (!CGM.getModule().getModuleInlineAsm().empty())
3443 s << "\n";
3444
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003445 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3446 e = LazySymbols.end(); i != e; ++i) {
3447 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3448 }
3449 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3450 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003451 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003452 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3453 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003454
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003455 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003456}
3457
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003458CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003459 : CGObjCCommonMac(cgm),
3460 ObjCTypes(cgm)
3461{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003462 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003463 ObjCABI = 2;
3464}
3465
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003466/* *** */
3467
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003468ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3469: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003470{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003471 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3472 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003473
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003474 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003475 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003476 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003477 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003478 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3479
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003480 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003481 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003482 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003483
3484 // FIXME: It would be nice to unify this with the opaque type, so
3485 // that the IR comes out a bit cleaner.
3486 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3487 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003488
3489 // I'm not sure I like this. The implicit coordination is a bit
3490 // gross. We should solve this in a reasonable fashion because this
3491 // is a pretty common task (match some runtime data structure with
3492 // an LLVM data structure).
3493
3494 // FIXME: This is leaked.
3495 // FIXME: Merge with rewriter code?
3496
3497 // struct _objc_super {
3498 // id self;
3499 // Class cls;
3500 // }
3501 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3502 SourceLocation(),
3503 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003504 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3505 Ctx.getObjCIdType(), 0, false));
3506 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3507 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003508 RD->completeDefinition(Ctx);
3509
3510 SuperCTy = Ctx.getTagDeclType(RD);
3511 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3512
3513 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003514 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3515
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003516 // struct _prop_t {
3517 // char *name;
3518 // char *attributes;
3519 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003520 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003521 CGM.getModule().addTypeName("struct._prop_t",
3522 PropertyTy);
3523
3524 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003525 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003526 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003527 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003528 // }
3529 PropertyListTy = llvm::StructType::get(IntTy,
3530 IntTy,
3531 llvm::ArrayType::get(PropertyTy, 0),
3532 NULL);
3533 CGM.getModule().addTypeName("struct._prop_list_t",
3534 PropertyListTy);
3535 // struct _prop_list_t *
3536 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3537
3538 // struct _objc_method {
3539 // SEL _cmd;
3540 // char *method_type;
3541 // char *_imp;
3542 // }
3543 MethodTy = llvm::StructType::get(SelectorPtrTy,
3544 Int8PtrTy,
3545 Int8PtrTy,
3546 NULL);
3547 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003548
3549 // struct _objc_cache *
3550 CacheTy = llvm::OpaqueType::get();
3551 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3552 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003553}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003554
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003555ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3556 : ObjCCommonTypesHelper(cgm)
3557{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003558 // struct _objc_method_description {
3559 // SEL name;
3560 // char *types;
3561 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003562 MethodDescriptionTy =
3563 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003564 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003565 NULL);
3566 CGM.getModule().addTypeName("struct._objc_method_description",
3567 MethodDescriptionTy);
3568
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003569 // struct _objc_method_description_list {
3570 // int count;
3571 // struct _objc_method_description[1];
3572 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003573 MethodDescriptionListTy =
3574 llvm::StructType::get(IntTy,
3575 llvm::ArrayType::get(MethodDescriptionTy, 0),
3576 NULL);
3577 CGM.getModule().addTypeName("struct._objc_method_description_list",
3578 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003579
3580 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003581 MethodDescriptionListPtrTy =
3582 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3583
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003584 // Protocol description structures
3585
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003586 // struct _objc_protocol_extension {
3587 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3588 // struct _objc_method_description_list *optional_instance_methods;
3589 // struct _objc_method_description_list *optional_class_methods;
3590 // struct _objc_property_list *instance_properties;
3591 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003592 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003593 llvm::StructType::get(IntTy,
3594 MethodDescriptionListPtrTy,
3595 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003596 PropertyListPtrTy,
3597 NULL);
3598 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3599 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003600
3601 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003602 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3603
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003604 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003605
3606 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3607 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3608
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003609 const llvm::Type *T =
3610 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3611 LongTy,
3612 llvm::ArrayType::get(ProtocolTyHolder, 0),
3613 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003614 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3615
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003616 // struct _objc_protocol {
3617 // struct _objc_protocol_extension *isa;
3618 // char *protocol_name;
3619 // struct _objc_protocol **_objc_protocol_list;
3620 // struct _objc_method_description_list *instance_methods;
3621 // struct _objc_method_description_list *class_methods;
3622 // }
3623 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003624 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003625 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3626 MethodDescriptionListPtrTy,
3627 MethodDescriptionListPtrTy,
3628 NULL);
3629 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3630
3631 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3632 CGM.getModule().addTypeName("struct._objc_protocol_list",
3633 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003634 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003635 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3636
3637 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003638 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003639 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003640
3641 // Class description structures
3642
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003643 // struct _objc_ivar {
3644 // char *ivar_name;
3645 // char *ivar_type;
3646 // int ivar_offset;
3647 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003648 IvarTy = llvm::StructType::get(Int8PtrTy,
3649 Int8PtrTy,
3650 IntTy,
3651 NULL);
3652 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3653
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003654 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003655 IvarListTy = llvm::OpaqueType::get();
3656 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3657 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3658
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003659 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003660 MethodListTy = llvm::OpaqueType::get();
3661 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3662 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3663
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003664 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003665 ClassExtensionTy =
3666 llvm::StructType::get(IntTy,
3667 Int8PtrTy,
3668 PropertyListPtrTy,
3669 NULL);
3670 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3671 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3672
3673 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3674
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003675 // struct _objc_class {
3676 // Class isa;
3677 // Class super_class;
3678 // char *name;
3679 // long version;
3680 // long info;
3681 // long instance_size;
3682 // struct _objc_ivar_list *ivars;
3683 // struct _objc_method_list *methods;
3684 // struct _objc_cache *cache;
3685 // struct _objc_protocol_list *protocols;
3686 // char *ivar_layout;
3687 // struct _objc_class_ext *ext;
3688 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003689 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3690 llvm::PointerType::getUnqual(ClassTyHolder),
3691 Int8PtrTy,
3692 LongTy,
3693 LongTy,
3694 LongTy,
3695 IvarListPtrTy,
3696 MethodListPtrTy,
3697 CachePtrTy,
3698 ProtocolListPtrTy,
3699 Int8PtrTy,
3700 ClassExtensionPtrTy,
3701 NULL);
3702 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3703
3704 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3705 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3706 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3707
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003708 // struct _objc_category {
3709 // char *category_name;
3710 // char *class_name;
3711 // struct _objc_method_list *instance_method;
3712 // struct _objc_method_list *class_method;
3713 // uint32_t size; // sizeof(struct _objc_category)
3714 // struct _objc_property_list *instance_properties;// category's @property
3715 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003716 CategoryTy = llvm::StructType::get(Int8PtrTy,
3717 Int8PtrTy,
3718 MethodListPtrTy,
3719 MethodListPtrTy,
3720 ProtocolListPtrTy,
3721 IntTy,
3722 PropertyListPtrTy,
3723 NULL);
3724 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3725
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003726 // Global metadata structures
3727
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003728 // struct _objc_symtab {
3729 // long sel_ref_cnt;
3730 // SEL *refs;
3731 // short cls_def_cnt;
3732 // short cat_def_cnt;
3733 // char *defs[cls_def_cnt + cat_def_cnt];
3734 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003735 SymtabTy = llvm::StructType::get(LongTy,
3736 SelectorPtrTy,
3737 ShortTy,
3738 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003739 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003740 NULL);
3741 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3742 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3743
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003744 // struct _objc_module {
3745 // long version;
3746 // long size; // sizeof(struct _objc_module)
3747 // char *name;
3748 // struct _objc_symtab* symtab;
3749 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003750 ModuleTy =
3751 llvm::StructType::get(LongTy,
3752 LongTy,
3753 Int8PtrTy,
3754 SymtabPtrTy,
3755 NULL);
3756 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003757
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003758
Anders Carlsson124526b2008-09-09 10:10:21 +00003759 // FIXME: This is the size of the setjmp buffer and should be
3760 // target specific. 18 is what's used on 32-bit X86.
3761 uint64_t SetJmpBufferSize = 18;
3762
3763 // Exceptions
3764 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003765 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003766
3767 ExceptionDataTy =
3768 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3769 SetJmpBufferSize),
3770 StackPtrTy, NULL);
3771 CGM.getModule().addTypeName("struct._objc_exception_data",
3772 ExceptionDataTy);
3773
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003774}
3775
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003776ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003777: ObjCCommonTypesHelper(cgm)
3778{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003779 // struct _method_list_t {
3780 // uint32_t entsize; // sizeof(struct _objc_method)
3781 // uint32_t method_count;
3782 // struct _objc_method method_list[method_count];
3783 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003784 MethodListnfABITy = llvm::StructType::get(IntTy,
3785 IntTy,
3786 llvm::ArrayType::get(MethodTy, 0),
3787 NULL);
3788 CGM.getModule().addTypeName("struct.__method_list_t",
3789 MethodListnfABITy);
3790 // struct method_list_t *
3791 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003792
3793 // struct _protocol_t {
3794 // id isa; // NULL
3795 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003796 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003797 // const struct method_list_t * const instance_methods;
3798 // const struct method_list_t * const class_methods;
3799 // const struct method_list_t *optionalInstanceMethods;
3800 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003801 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003802 // const uint32_t size; // sizeof(struct _protocol_t)
3803 // const uint32_t flags; // = 0
3804 // }
3805
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003806 // Holder for struct _protocol_list_t *
3807 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3808
3809 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3810 Int8PtrTy,
3811 llvm::PointerType::getUnqual(
3812 ProtocolListTyHolder),
3813 MethodListnfABIPtrTy,
3814 MethodListnfABIPtrTy,
3815 MethodListnfABIPtrTy,
3816 MethodListnfABIPtrTy,
3817 PropertyListPtrTy,
3818 IntTy,
3819 IntTy,
3820 NULL);
3821 CGM.getModule().addTypeName("struct._protocol_t",
3822 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003823
3824 // struct _protocol_t*
3825 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003826
Fariborz Jahanianda320092009-01-29 19:24:30 +00003827 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003828 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003829 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003830 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003831 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3832 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003833 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003834 NULL);
3835 CGM.getModule().addTypeName("struct._objc_protocol_list",
3836 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003837 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3838 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003839
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003840 // struct _objc_protocol_list*
3841 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003842
3843 // struct _ivar_t {
3844 // unsigned long int *offset; // pointer to ivar offset location
3845 // char *name;
3846 // char *type;
3847 // uint32_t alignment;
3848 // uint32_t size;
3849 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003850 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3851 Int8PtrTy,
3852 Int8PtrTy,
3853 IntTy,
3854 IntTy,
3855 NULL);
3856 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3857
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003858 // struct _ivar_list_t {
3859 // uint32 entsize; // sizeof(struct _ivar_t)
3860 // uint32 count;
3861 // struct _iver_t list[count];
3862 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003863 IvarListnfABITy = llvm::StructType::get(IntTy,
3864 IntTy,
3865 llvm::ArrayType::get(
3866 IvarnfABITy, 0),
3867 NULL);
3868 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3869
3870 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003871
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003872 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003873 // uint32_t const flags;
3874 // uint32_t const instanceStart;
3875 // uint32_t const instanceSize;
3876 // uint32_t const reserved; // only when building for 64bit targets
3877 // const uint8_t * const ivarLayout;
3878 // const char *const name;
3879 // const struct _method_list_t * const baseMethods;
3880 // const struct _objc_protocol_list *const baseProtocols;
3881 // const struct _ivar_list_t *const ivars;
3882 // const uint8_t * const weakIvarLayout;
3883 // const struct _prop_list_t * const properties;
3884 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003885
3886 // FIXME. Add 'reserved' field in 64bit abi mode!
3887 ClassRonfABITy = llvm::StructType::get(IntTy,
3888 IntTy,
3889 IntTy,
3890 Int8PtrTy,
3891 Int8PtrTy,
3892 MethodListnfABIPtrTy,
3893 ProtocolListnfABIPtrTy,
3894 IvarListnfABIPtrTy,
3895 Int8PtrTy,
3896 PropertyListPtrTy,
3897 NULL);
3898 CGM.getModule().addTypeName("struct._class_ro_t",
3899 ClassRonfABITy);
3900
3901 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3902 std::vector<const llvm::Type*> Params;
3903 Params.push_back(ObjectPtrTy);
3904 Params.push_back(SelectorPtrTy);
3905 ImpnfABITy = llvm::PointerType::getUnqual(
3906 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3907
3908 // struct _class_t {
3909 // struct _class_t *isa;
3910 // struct _class_t * const superclass;
3911 // void *cache;
3912 // IMP *vtable;
3913 // struct class_ro_t *ro;
3914 // }
3915
3916 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3917 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3918 llvm::PointerType::getUnqual(ClassTyHolder),
3919 CachePtrTy,
3920 llvm::PointerType::getUnqual(ImpnfABITy),
3921 llvm::PointerType::getUnqual(
3922 ClassRonfABITy),
3923 NULL);
3924 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3925
3926 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3927 ClassnfABITy);
3928
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003929 // LLVM for struct _class_t *
3930 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3931
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003932 // struct _category_t {
3933 // const char * const name;
3934 // struct _class_t *const cls;
3935 // const struct _method_list_t * const instance_methods;
3936 // const struct _method_list_t * const class_methods;
3937 // const struct _protocol_list_t * const protocols;
3938 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003939 // }
3940 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003941 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003942 MethodListnfABIPtrTy,
3943 MethodListnfABIPtrTy,
3944 ProtocolListnfABIPtrTy,
3945 PropertyListPtrTy,
3946 NULL);
3947 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003948
3949 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003950 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3951 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003952
3953 // MessageRefTy - LLVM for:
3954 // struct _message_ref_t {
3955 // IMP messenger;
3956 // SEL name;
3957 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003958
3959 // First the clang type for struct _message_ref_t
3960 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3961 SourceLocation(),
3962 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003963 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3964 Ctx.VoidPtrTy, 0, false));
3965 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3966 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003967 RD->completeDefinition(Ctx);
3968
3969 MessageRefCTy = Ctx.getTagDeclType(RD);
3970 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3971 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003972
3973 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3974 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3975
3976 // SuperMessageRefTy - LLVM for:
3977 // struct _super_message_ref_t {
3978 // SUPER_IMP messenger;
3979 // SEL name;
3980 // };
3981 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3982 SelectorPtrTy,
3983 NULL);
3984 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3985
3986 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3987 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3988
Daniel Dunbare588b992009-03-01 04:46:24 +00003989
3990 // struct objc_typeinfo {
3991 // const void** vtable; // objc_ehtype_vtable + 2
3992 // const char* name; // c++ typeinfo string
3993 // Class cls;
3994 // };
3995 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3996 Int8PtrTy,
3997 ClassnfABIPtrTy,
3998 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003999 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004000 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004001}
4002
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004003llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4004 FinishNonFragileABIModule();
4005
4006 return NULL;
4007}
4008
4009void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4010 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004011
4012 // Build list of all implemented classe addresses in array
4013 // L_OBJC_LABEL_CLASS_$.
4014 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4015 // list of 'nonlazy' implementations (defined as those with a +load{}
4016 // method!!).
4017 unsigned NumClasses = DefinedClasses.size();
4018 if (NumClasses) {
4019 std::vector<llvm::Constant*> Symbols(NumClasses);
4020 for (unsigned i=0; i<NumClasses; i++)
4021 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4022 ObjCTypes.Int8PtrTy);
4023 llvm::Constant* Init =
4024 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4025 NumClasses),
4026 Symbols);
4027
4028 llvm::GlobalVariable *GV =
4029 new llvm::GlobalVariable(Init->getType(), false,
4030 llvm::GlobalValue::InternalLinkage,
4031 Init,
4032 "\01L_OBJC_LABEL_CLASS_$",
4033 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004034 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004035 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4036 UsedGlobals.push_back(GV);
4037 }
4038
4039 // Build list of all implemented category addresses in array
4040 // L_OBJC_LABEL_CATEGORY_$.
4041 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4042 // list of 'nonlazy' category implementations (defined as those with a +load{}
4043 // method!!).
4044 unsigned NumCategory = DefinedCategories.size();
4045 if (NumCategory) {
4046 std::vector<llvm::Constant*> Symbols(NumCategory);
4047 for (unsigned i=0; i<NumCategory; i++)
4048 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4049 ObjCTypes.Int8PtrTy);
4050 llvm::Constant* Init =
4051 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4052 NumCategory),
4053 Symbols);
4054
4055 llvm::GlobalVariable *GV =
4056 new llvm::GlobalVariable(Init->getType(), false,
4057 llvm::GlobalValue::InternalLinkage,
4058 Init,
4059 "\01L_OBJC_LABEL_CATEGORY_$",
4060 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004061 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004062 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4063 UsedGlobals.push_back(GV);
4064 }
4065
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004066 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4067 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4068 std::vector<llvm::Constant*> Values(2);
4069 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004070 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004071 // FIXME: Fix and continue?
4072 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4073 flags |= eImageInfo_GarbageCollected;
4074 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4075 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004076 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004077 llvm::Constant* Init = llvm::ConstantArray::get(
4078 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4079 Values);
4080 llvm::GlobalVariable *IMGV =
4081 new llvm::GlobalVariable(Init->getType(), false,
4082 llvm::GlobalValue::InternalLinkage,
4083 Init,
4084 "\01L_OBJC_IMAGE_INFO",
4085 &CGM.getModule());
4086 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4087 UsedGlobals.push_back(IMGV);
4088
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004089 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004090
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004091 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4092 e = UsedGlobals.end(); i != e; ++i) {
4093 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4094 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004095
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004096 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4097 llvm::GlobalValue *GV =
4098 new llvm::GlobalVariable(AT, false,
4099 llvm::GlobalValue::AppendingLinkage,
4100 llvm::ConstantArray::get(AT, Used),
4101 "llvm.used",
4102 &CGM.getModule());
4103
4104 GV->setSection("llvm.metadata");
4105
4106}
4107
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004108// Metadata flags
4109enum MetaDataDlags {
4110 CLS = 0x0,
4111 CLS_META = 0x1,
4112 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004113 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004114 CLS_EXCEPTION = 0x20
4115};
4116/// BuildClassRoTInitializer - generate meta-data for:
4117/// struct _class_ro_t {
4118/// uint32_t const flags;
4119/// uint32_t const instanceStart;
4120/// uint32_t const instanceSize;
4121/// uint32_t const reserved; // only when building for 64bit targets
4122/// const uint8_t * const ivarLayout;
4123/// const char *const name;
4124/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004125/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004126/// const struct _ivar_list_t *const ivars;
4127/// const uint8_t * const weakIvarLayout;
4128/// const struct _prop_list_t * const properties;
4129/// }
4130///
4131llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4132 unsigned flags,
4133 unsigned InstanceStart,
4134 unsigned InstanceSize,
4135 const ObjCImplementationDecl *ID) {
4136 std::string ClassName = ID->getNameAsString();
4137 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4138 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4139 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4140 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4141 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004142 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004143 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4144 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004145 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004146 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004147 // const struct _method_list_t * const baseMethods;
4148 std::vector<llvm::Constant*> Methods;
4149 std::string MethodListName("\01l_OBJC_$_");
4150 if (flags & CLS_META) {
4151 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4152 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4153 e = ID->classmeth_end(); i != e; ++i) {
4154 // Class methods should always be defined.
4155 Methods.push_back(GetMethodConstant(*i));
4156 }
4157 } else {
4158 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4159 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4160 e = ID->instmeth_end(); i != e; ++i) {
4161 // Instance methods should always be defined.
4162 Methods.push_back(GetMethodConstant(*i));
4163 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004164 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4165 e = ID->propimpl_end(); i != e; ++i) {
4166 ObjCPropertyImplDecl *PID = *i;
4167
4168 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4169 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4170
4171 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4172 if (llvm::Constant *C = GetMethodConstant(MD))
4173 Methods.push_back(C);
4174 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4175 if (llvm::Constant *C = GetMethodConstant(MD))
4176 Methods.push_back(C);
4177 }
4178 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004179 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004180 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004181 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004182
4183 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4184 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4185 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4186 + OID->getNameAsString(),
4187 OID->protocol_begin(),
4188 OID->protocol_end());
4189
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004190 if (flags & CLS_META)
4191 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4192 else
4193 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004194 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004195 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4196 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004197 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004198 if (flags & CLS_META)
4199 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4200 else
4201 Values[ 9] =
4202 EmitPropertyList(
4203 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4204 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4206 Values);
4207 llvm::GlobalVariable *CLASS_RO_GV =
4208 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4209 llvm::GlobalValue::InternalLinkage,
4210 Init,
4211 (flags & CLS_META) ?
4212 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4213 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4214 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004215 CLASS_RO_GV->setAlignment(
4216 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004217 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004218 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004219
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004220}
4221
4222/// BuildClassMetaData - This routine defines that to-level meta-data
4223/// for the given ClassName for:
4224/// struct _class_t {
4225/// struct _class_t *isa;
4226/// struct _class_t * const superclass;
4227/// void *cache;
4228/// IMP *vtable;
4229/// struct class_ro_t *ro;
4230/// }
4231///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004232llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4233 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004234 llvm::Constant *IsAGV,
4235 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004236 llvm::Constant *ClassRoGV,
4237 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004238 std::vector<llvm::Constant*> Values(5);
4239 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004240 Values[1] = SuperClassGV
4241 ? SuperClassGV
4242 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004243 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4244 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4245 Values[4] = ClassRoGV; // &CLASS_RO_GV
4246 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4247 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004248 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4249 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004250 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004251 GV->setAlignment(
4252 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004253 if (HiddenVisibility)
4254 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004255 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004256}
4257
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004258void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4259 uint32_t &InstanceStart,
4260 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004261 // Find first and last (non-padding) ivars in this interface.
4262
4263 // FIXME: Use iterator.
4264 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4265 GetNamedIvarList(OID, OIvars);
4266
4267 if (OIvars.empty()) {
4268 InstanceStart = InstanceSize = 0;
4269 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004270 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004271
4272 const ObjCIvarDecl *First = OIvars.front();
4273 const ObjCIvarDecl *Last = OIvars.back();
4274
4275 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4276 const llvm::Type *FieldTy =
4277 CGM.getTypes().ConvertTypeForMem(Last->getType());
4278 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4279 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004280}
4281
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004282void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4283 std::string ClassName = ID->getNameAsString();
4284 if (!ObjCEmptyCacheVar) {
4285 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004286 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004287 false,
4288 llvm::GlobalValue::ExternalLinkage,
4289 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004290 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004291 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004292
4293 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004294 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004295 false,
4296 llvm::GlobalValue::ExternalLinkage,
4297 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004298 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004299 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004300 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004301 assert(ID->getClassInterface() &&
4302 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004303 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004304 uint32_t InstanceStart =
4305 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4306 uint32_t InstanceSize = InstanceStart;
4307 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004308 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4309 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004310
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004311 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004312
Daniel Dunbar04d40782009-04-14 06:00:08 +00004313 bool classIsHidden =
4314 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004315 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004316 flags |= OBJC2_CLS_HIDDEN;
4317 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004318 // class is root
4319 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004320 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004321 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004322 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004323 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004324 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4325 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4326 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004327 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004328 // work on super class metadata symbol.
4329 std::string SuperClassName =
4330 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004331 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004332 }
4333 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4334 InstanceStart,
4335 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004336 std::string TClassName = ObjCMetaClassName + ClassName;
4337 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004338 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4339 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004340
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004341 // Metadata for the class
4342 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004343 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004344 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004345
4346 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4347 flags |= CLS_EXCEPTION;
4348
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004349 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004350 flags |= CLS_ROOT;
4351 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004352 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004353 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004354 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004355 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004356 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004357 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004358 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004359 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004360 InstanceStart,
4361 InstanceSize,
4362 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004363
4364 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004365 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004366 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4367 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004368 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004369
4370 // Force the definition of the EHType if necessary.
4371 if (flags & CLS_EXCEPTION)
4372 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004373}
4374
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004375/// GenerateProtocolRef - This routine is called to generate code for
4376/// a protocol reference expression; as in:
4377/// @code
4378/// @protocol(Proto1);
4379/// @endcode
4380/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4381/// which will hold address of the protocol meta-data.
4382///
4383llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4384 const ObjCProtocolDecl *PD) {
4385
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004386 // This routine is called for @protocol only. So, we must build definition
4387 // of protocol's meta-data (not a reference to it!)
4388 //
4389 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004390 ObjCTypes.ExternalProtocolPtrTy);
4391
4392 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4393 ProtocolName += PD->getNameAsCString();
4394
4395 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4396 if (PTGV)
4397 return Builder.CreateLoad(PTGV, false, "tmp");
4398 PTGV = new llvm::GlobalVariable(
4399 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004400 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004401 Init,
4402 ProtocolName,
4403 &CGM.getModule());
4404 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4405 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4406 UsedGlobals.push_back(PTGV);
4407 return Builder.CreateLoad(PTGV, false, "tmp");
4408}
4409
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004410/// GenerateCategory - Build metadata for a category implementation.
4411/// struct _category_t {
4412/// const char * const name;
4413/// struct _class_t *const cls;
4414/// const struct _method_list_t * const instance_methods;
4415/// const struct _method_list_t * const class_methods;
4416/// const struct _protocol_list_t * const protocols;
4417/// const struct _prop_list_t * const properties;
4418/// }
4419///
4420void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4421{
4422 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004423 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4424 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004425 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004426 std::string ExtClassName(getClassSymbolPrefix() +
4427 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004428
4429 std::vector<llvm::Constant*> Values(6);
4430 Values[0] = GetClassName(OCD->getIdentifier());
4431 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004432 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004433 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004434 std::vector<llvm::Constant*> Methods;
4435 std::string MethodListName(Prefix);
4436 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4437 "_$_" + OCD->getNameAsString();
4438
4439 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4440 e = OCD->instmeth_end(); i != e; ++i) {
4441 // Instance methods should always be defined.
4442 Methods.push_back(GetMethodConstant(*i));
4443 }
4444
4445 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004446 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004447 Methods);
4448
4449 MethodListName = Prefix;
4450 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4451 OCD->getNameAsString();
4452 Methods.clear();
4453 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4454 e = OCD->classmeth_end(); i != e; ++i) {
4455 // Class methods should always be defined.
4456 Methods.push_back(GetMethodConstant(*i));
4457 }
4458
4459 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004460 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004461 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004462 const ObjCCategoryDecl *Category =
4463 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004464 if (Category) {
4465 std::string ExtName(Interface->getNameAsString() + "_$_" +
4466 OCD->getNameAsString());
4467 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4468 + Interface->getNameAsString() + "_$_"
4469 + Category->getNameAsString(),
4470 Category->protocol_begin(),
4471 Category->protocol_end());
4472 Values[5] =
4473 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4474 OCD, Category, ObjCTypes);
4475 }
4476 else {
4477 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4478 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4479 }
4480
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004481 llvm::Constant *Init =
4482 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4483 Values);
4484 llvm::GlobalVariable *GCATV
4485 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4486 false,
4487 llvm::GlobalValue::InternalLinkage,
4488 Init,
4489 ExtCatName,
4490 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004491 GCATV->setAlignment(
4492 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004493 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004494 UsedGlobals.push_back(GCATV);
4495 DefinedCategories.push_back(GCATV);
4496}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004497
4498/// GetMethodConstant - Return a struct objc_method constant for the
4499/// given method if it has been defined. The result is null if the
4500/// method has not been defined. The return value has type MethodPtrTy.
4501llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4502 const ObjCMethodDecl *MD) {
4503 // FIXME: Use DenseMap::lookup
4504 llvm::Function *Fn = MethodDefinitions[MD];
4505 if (!Fn)
4506 return 0;
4507
4508 std::vector<llvm::Constant*> Method(3);
4509 Method[0] =
4510 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4511 ObjCTypes.SelectorPtrTy);
4512 Method[1] = GetMethodVarType(MD);
4513 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4514 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4515}
4516
4517/// EmitMethodList - Build meta-data for method declarations
4518/// struct _method_list_t {
4519/// uint32_t entsize; // sizeof(struct _objc_method)
4520/// uint32_t method_count;
4521/// struct _objc_method method_list[method_count];
4522/// }
4523///
4524llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4525 const std::string &Name,
4526 const char *Section,
4527 const ConstantVector &Methods) {
4528 // Return null for empty list.
4529 if (Methods.empty())
4530 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4531
4532 std::vector<llvm::Constant*> Values(3);
4533 // sizeof(struct _objc_method)
4534 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4535 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4536 // method_count
4537 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4538 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4539 Methods.size());
4540 Values[2] = llvm::ConstantArray::get(AT, Methods);
4541 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4542
4543 llvm::GlobalVariable *GV =
4544 new llvm::GlobalVariable(Init->getType(), false,
4545 llvm::GlobalValue::InternalLinkage,
4546 Init,
4547 Name,
4548 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004549 GV->setAlignment(
4550 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004551 GV->setSection(Section);
4552 UsedGlobals.push_back(GV);
4553 return llvm::ConstantExpr::getBitCast(GV,
4554 ObjCTypes.MethodListnfABIPtrTy);
4555}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004556
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004557/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4558/// the given ivar.
4559///
4560llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004561 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004562 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004563 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004564 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4565 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004566 llvm::GlobalVariable *IvarOffsetGV =
4567 CGM.getModule().getGlobalVariable(Name);
4568 if (!IvarOffsetGV)
4569 IvarOffsetGV =
4570 new llvm::GlobalVariable(ObjCTypes.LongTy,
4571 false,
4572 llvm::GlobalValue::ExternalLinkage,
4573 0,
4574 Name,
4575 &CGM.getModule());
4576 return IvarOffsetGV;
4577}
4578
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004579llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004580 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004581 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004582 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004583 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4584 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4585 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004586 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004587 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004588
4589 // FIXME: This matches gcc, but shouldn't the visibility be set on
4590 // the use as well (i.e., in ObjCIvarOffsetVariable).
4591 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4592 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4593 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004594 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004595 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004596 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004597 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004598 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004599}
4600
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004601/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004602/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004603/// IvarListnfABIPtrTy.
4604/// struct _ivar_t {
4605/// unsigned long int *offset; // pointer to ivar offset location
4606/// char *name;
4607/// char *type;
4608/// uint32_t alignment;
4609/// uint32_t size;
4610/// }
4611/// struct _ivar_list_t {
4612/// uint32 entsize; // sizeof(struct _ivar_t)
4613/// uint32 count;
4614/// struct _iver_t list[count];
4615/// }
4616///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004617
4618void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4619 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4620 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4621 E = OID->ivar_end(); I != E; ++I) {
4622 // Ignore unnamed bit-fields.
4623 if (!(*I)->getDeclName())
4624 continue;
4625
4626 Res.push_back(*I);
4627 }
4628
4629 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4630 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4631 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4632 Res.push_back(IV);
4633}
4634
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004635llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4636 const ObjCImplementationDecl *ID) {
4637
4638 std::vector<llvm::Constant*> Ivars, Ivar(5);
4639
4640 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4641 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4642
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004643 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004644
Daniel Dunbar91636d62009-04-20 00:33:43 +00004645 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004646 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004647 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004648
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004649 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4650 ObjCIvarDecl *IVD = OIvars[i];
4651 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004652 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004653 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004654 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004655 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004656 const llvm::Type *FieldTy =
4657 CGM.getTypes().ConvertTypeForMem(Field->getType());
4658 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4659 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4660 Field->getType().getTypePtr()) >> 3;
4661 Align = llvm::Log2_32(Align);
4662 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004663 // NOTE. Size of a bitfield does not match gcc's, because of the
4664 // way bitfields are treated special in each. But I am told that
4665 // 'size' for bitfield ivars is ignored by the runtime so it does
4666 // not matter. If it matters, there is enough info to get the
4667 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004668 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4669 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4670 }
4671 // Return null for empty list.
4672 if (Ivars.empty())
4673 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4674 std::vector<llvm::Constant*> Values(3);
4675 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4676 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4677 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4678 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4679 Ivars.size());
4680 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4681 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4682 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4683 llvm::GlobalVariable *GV =
4684 new llvm::GlobalVariable(Init->getType(), false,
4685 llvm::GlobalValue::InternalLinkage,
4686 Init,
4687 Prefix + OID->getNameAsString(),
4688 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004689 GV->setAlignment(
4690 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004691 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004692
4693 UsedGlobals.push_back(GV);
4694 return llvm::ConstantExpr::getBitCast(GV,
4695 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004696}
4697
4698llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4699 const ObjCProtocolDecl *PD) {
4700 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4701
4702 if (!Entry) {
4703 // We use the initializer as a marker of whether this is a forward
4704 // reference or not. At module finalization we add the empty
4705 // contents for protocols which were referenced but never defined.
4706 Entry =
4707 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4708 llvm::GlobalValue::ExternalLinkage,
4709 0,
4710 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4711 &CGM.getModule());
4712 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4713 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004714 }
4715
4716 return Entry;
4717}
4718
4719/// GetOrEmitProtocol - Generate the protocol meta-data:
4720/// @code
4721/// struct _protocol_t {
4722/// id isa; // NULL
4723/// const char * const protocol_name;
4724/// const struct _protocol_list_t * protocol_list; // super protocols
4725/// const struct method_list_t * const instance_methods;
4726/// const struct method_list_t * const class_methods;
4727/// const struct method_list_t *optionalInstanceMethods;
4728/// const struct method_list_t *optionalClassMethods;
4729/// const struct _prop_list_t * properties;
4730/// const uint32_t size; // sizeof(struct _protocol_t)
4731/// const uint32_t flags; // = 0
4732/// }
4733/// @endcode
4734///
4735
4736llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4737 const ObjCProtocolDecl *PD) {
4738 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4739
4740 // Early exit if a defining object has already been generated.
4741 if (Entry && Entry->hasInitializer())
4742 return Entry;
4743
4744 const char *ProtocolName = PD->getNameAsCString();
4745
4746 // Construct method lists.
4747 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4748 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004749 for (ObjCProtocolDecl::instmeth_iterator
4750 i = PD->instmeth_begin(CGM.getContext()),
4751 e = PD->instmeth_end(CGM.getContext());
4752 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004754 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4756 OptInstanceMethods.push_back(C);
4757 } else {
4758 InstanceMethods.push_back(C);
4759 }
4760 }
4761
Douglas Gregor6ab35242009-04-09 21:40:53 +00004762 for (ObjCProtocolDecl::classmeth_iterator
4763 i = PD->classmeth_begin(CGM.getContext()),
4764 e = PD->classmeth_end(CGM.getContext());
4765 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004766 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004767 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004768 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4769 OptClassMethods.push_back(C);
4770 } else {
4771 ClassMethods.push_back(C);
4772 }
4773 }
4774
4775 std::vector<llvm::Constant*> Values(10);
4776 // isa is NULL
4777 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4778 Values[1] = GetClassName(PD->getIdentifier());
4779 Values[2] = EmitProtocolList(
4780 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4781 PD->protocol_begin(),
4782 PD->protocol_end());
4783
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004784 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 + PD->getNameAsString(),
4786 "__DATA, __objc_const",
4787 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004788 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 + PD->getNameAsString(),
4790 "__DATA, __objc_const",
4791 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004792 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 + PD->getNameAsString(),
4794 "__DATA, __objc_const",
4795 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004796 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 + PD->getNameAsString(),
4798 "__DATA, __objc_const",
4799 OptClassMethods);
4800 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4801 0, PD, ObjCTypes);
4802 uint32_t Size =
4803 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4804 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4805 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4806 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4807 Values);
4808
4809 if (Entry) {
4810 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004811 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 Entry->setInitializer(Init);
4813 } else {
4814 Entry =
4815 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004816 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 Init,
4818 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4819 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004820 Entry->setAlignment(
4821 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004824 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4825
4826 // Use this protocol meta-data to build protocol list table in section
4827 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004828 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004829 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004830 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004831 Entry,
4832 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4833 +ProtocolName,
4834 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004835 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004836 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004837 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004838 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4839 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004840 return Entry;
4841}
4842
4843/// EmitProtocolList - Generate protocol list meta-data:
4844/// @code
4845/// struct _protocol_list_t {
4846/// long protocol_count; // Note, this is 32/64 bit
4847/// struct _protocol_t[protocol_count];
4848/// }
4849/// @endcode
4850///
4851llvm::Constant *
4852CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4853 ObjCProtocolDecl::protocol_iterator begin,
4854 ObjCProtocolDecl::protocol_iterator end) {
4855 std::vector<llvm::Constant*> ProtocolRefs;
4856
Fariborz Jahanianda320092009-01-29 19:24:30 +00004857 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004858 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004859 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4860
Daniel Dunbar948e2582009-02-15 07:36:20 +00004861 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004862 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4863 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004864 return llvm::ConstantExpr::getBitCast(GV,
4865 ObjCTypes.ProtocolListnfABIPtrTy);
4866
4867 for (; begin != end; ++begin)
4868 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4869
Fariborz Jahanianda320092009-01-29 19:24:30 +00004870 // This list is null terminated.
4871 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004872 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004873
4874 std::vector<llvm::Constant*> Values(2);
4875 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4876 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004877 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004878 ProtocolRefs.size()),
4879 ProtocolRefs);
4880
4881 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4882 GV = new llvm::GlobalVariable(Init->getType(), false,
4883 llvm::GlobalValue::InternalLinkage,
4884 Init,
4885 Name,
4886 &CGM.getModule());
4887 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004888 GV->setAlignment(
4889 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004890 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004891 return llvm::ConstantExpr::getBitCast(GV,
4892 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004893}
4894
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004895/// GetMethodDescriptionConstant - This routine build following meta-data:
4896/// struct _objc_method {
4897/// SEL _cmd;
4898/// char *method_type;
4899/// char *_imp;
4900/// }
4901
4902llvm::Constant *
4903CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4904 std::vector<llvm::Constant*> Desc(3);
4905 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4906 ObjCTypes.SelectorPtrTy);
4907 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004908 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004909 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4910 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4911}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004912
4913/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4914/// This code gen. amounts to generating code for:
4915/// @code
4916/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4917/// @encode
4918///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004919LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004920 CodeGen::CodeGenFunction &CGF,
4921 QualType ObjectTy,
4922 llvm::Value *BaseValue,
4923 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004924 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004925 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004926 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4927 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004928}
4929
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004930llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4931 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004932 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004933 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004934 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4935 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004936}
4937
Fariborz Jahanian46551122009-02-04 00:22:57 +00004938CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4939 CodeGen::CodeGenFunction &CGF,
4940 QualType ResultType,
4941 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004942 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004943 QualType Arg0Ty,
4944 bool IsSuper,
4945 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004946 // FIXME. Even though IsSuper is passes. This function doese not
4947 // handle calls to 'super' receivers.
4948 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004949 llvm::Value *Arg0 = Receiver;
4950 if (!IsSuper)
4951 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952
4953 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004954 // FIXME. This is too much work to get the ABI-specific result type
4955 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4957 llvm::SmallVector<QualType, 16>());
4958 llvm::Constant *Fn;
4959 std::string Name("\01l_");
4960 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004961#if 0
4962 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004963 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004964 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004965 // FIXME. Is there a better way of getting these names.
4966 // They are available in RuntimeFunctions vector pair.
4967 Name += "objc_msgSendId_stret_fixup";
4968 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004969 else
4970#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004971 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004972 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004973 Name += "objc_msgSendSuper2_stret_fixup";
4974 }
4975 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004976 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004977 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004978 Name += "objc_msgSend_stret_fixup";
4979 }
4980 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004981 else if (ResultType->isFloatingType() &&
4982 // Selection of frret API only happens in 32bit nonfragile ABI.
4983 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004984 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004985 Name += "objc_msgSend_fpret_fixup";
4986 }
4987 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004988#if 0
4989// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004990 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004991 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 Name += "objc_msgSendId_fixup";
4993 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004994 else
4995#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004996 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004997 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004998 Name += "objc_msgSendSuper2_fixup";
4999 }
5000 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005001 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005002 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005003 Name += "objc_msgSend_fixup";
5004 }
5005 }
5006 Name += '_';
5007 std::string SelName(Sel.getAsString());
5008 // Replace all ':' in selector name with '_' ouch!
5009 for(unsigned i = 0; i < SelName.size(); i++)
5010 if (SelName[i] == ':')
5011 SelName[i] = '_';
5012 Name += SelName;
5013 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5014 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005015 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 std::vector<llvm::Constant*> Values(2);
5017 Values[0] = Fn;
5018 Values[1] = GetMethodVarName(Sel);
5019 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5020 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005021 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 Init,
5023 Name,
5024 &CGM.getModule());
5025 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005026 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005027 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005028 }
5029 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005030
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005031 CallArgList ActualArgs;
5032 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5033 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5034 ObjCTypes.MessageRefCPtrTy));
5035 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005036 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5037 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5038 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005039 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005040 Callee = CGF.Builder.CreateBitCast(Callee,
5041 llvm::PointerType::getUnqual(FTy));
5042 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005043}
5044
5045/// Generate code for a message send expression in the nonfragile abi.
5046CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5047 CodeGen::CodeGenFunction &CGF,
5048 QualType ResultType,
5049 Selector Sel,
5050 llvm::Value *Receiver,
5051 bool IsClassMessage,
5052 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005053 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005054 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005055 false, CallArgs);
5056}
5057
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005058llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005059CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005060 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5061
Daniel Dunbardfff2302009-03-02 05:18:14 +00005062 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005063 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5064 llvm::GlobalValue::ExternalLinkage,
5065 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005066 }
5067
5068 return GV;
5069}
5070
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005071llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005072 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005073 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5074
5075 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005076 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005077 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005078 Entry =
5079 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5080 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005081 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005082 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005083 &CGM.getModule());
5084 Entry->setAlignment(
5085 CGM.getTargetData().getPrefTypeAlignment(
5086 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005087 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5088 UsedGlobals.push_back(Entry);
5089 }
5090
5091 return Builder.CreateLoad(Entry, false, "tmp");
5092}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005093
Daniel Dunbar11394522009-04-18 08:51:00 +00005094llvm::Value *
5095CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5096 const ObjCInterfaceDecl *ID) {
5097 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5098
5099 if (!Entry) {
5100 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5101 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5102 Entry =
5103 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5104 llvm::GlobalValue::InternalLinkage,
5105 ClassGV,
5106 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5107 &CGM.getModule());
5108 Entry->setAlignment(
5109 CGM.getTargetData().getPrefTypeAlignment(
5110 ObjCTypes.ClassnfABIPtrTy));
5111 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005112 UsedGlobals.push_back(Entry);
5113 }
5114
5115 return Builder.CreateLoad(Entry, false, "tmp");
5116}
5117
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005118/// EmitMetaClassRef - Return a Value * of the address of _class_t
5119/// meta-data
5120///
5121llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5122 const ObjCInterfaceDecl *ID) {
5123 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5124 if (Entry)
5125 return Builder.CreateLoad(Entry, false, "tmp");
5126
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005127 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005128 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005129 Entry =
5130 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5131 llvm::GlobalValue::InternalLinkage,
5132 MetaClassGV,
5133 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5134 &CGM.getModule());
5135 Entry->setAlignment(
5136 CGM.getTargetData().getPrefTypeAlignment(
5137 ObjCTypes.ClassnfABIPtrTy));
5138
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005139 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005140 UsedGlobals.push_back(Entry);
5141
5142 return Builder.CreateLoad(Entry, false, "tmp");
5143}
5144
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005145/// GetClass - Return a reference to the class for the given interface
5146/// decl.
5147llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5148 const ObjCInterfaceDecl *ID) {
5149 return EmitClassRef(Builder, ID);
5150}
5151
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005152/// Generates a message send where the super is the receiver. This is
5153/// a message send to self with special delivery semantics indicating
5154/// which class's method should be called.
5155CodeGen::RValue
5156CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5157 QualType ResultType,
5158 Selector Sel,
5159 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005160 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005161 llvm::Value *Receiver,
5162 bool IsClassMessage,
5163 const CodeGen::CallArgList &CallArgs) {
5164 // ...
5165 // Create and init a super structure; this is a (receiver, class)
5166 // pair we will pass to objc_msgSendSuper.
5167 llvm::Value *ObjCSuper =
5168 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5169
5170 llvm::Value *ReceiverAsObject =
5171 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5172 CGF.Builder.CreateStore(ReceiverAsObject,
5173 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5174
5175 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005176 llvm::Value *Target;
5177 if (IsClassMessage) {
5178 if (isCategoryImpl) {
5179 // Message sent to "super' in a class method defined in
5180 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005181 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005182 Target = CGF.Builder.CreateStructGEP(Target, 0);
5183 Target = CGF.Builder.CreateLoad(Target);
5184 }
5185 else
5186 Target = EmitMetaClassRef(CGF.Builder, Class);
5187 }
5188 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005189 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005190
5191 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5192 // and ObjCTypes types.
5193 const llvm::Type *ClassTy =
5194 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5195 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5196 CGF.Builder.CreateStore(Target,
5197 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5198
5199 return EmitMessageSend(CGF, ResultType, Sel,
5200 ObjCSuper, ObjCTypes.SuperPtrCTy,
5201 true, CallArgs);
5202}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005203
5204llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5205 Selector Sel) {
5206 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5207
5208 if (!Entry) {
5209 llvm::Constant *Casted =
5210 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5211 ObjCTypes.SelectorPtrTy);
5212 Entry =
5213 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5214 llvm::GlobalValue::InternalLinkage,
5215 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5216 &CGM.getModule());
5217 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5218 UsedGlobals.push_back(Entry);
5219 }
5220
5221 return Builder.CreateLoad(Entry, false, "tmp");
5222}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005223/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5224/// objc_assign_ivar (id src, id *dst)
5225///
5226void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5227 llvm::Value *src, llvm::Value *dst)
5228{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005229 const llvm::Type * SrcTy = src->getType();
5230 if (!isa<llvm::PointerType>(SrcTy)) {
5231 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5232 assert(Size <= 8 && "does not support size > 8");
5233 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5234 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005235 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5236 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005237 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5238 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005239 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005240 src, dst, "assignivar");
5241 return;
5242}
5243
5244/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5245/// objc_assign_strongCast (id src, id *dst)
5246///
5247void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5248 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.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005262 src, dst, "weakassign");
5263 return;
5264}
5265
5266/// EmitObjCWeakRead - Code gen for loading value of a __weak
5267/// object: objc_read_weak (id *src)
5268///
5269llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5270 CodeGen::CodeGenFunction &CGF,
5271 llvm::Value *AddrWeakObj)
5272{
Eli Friedman8339b352009-03-07 03:57:15 +00005273 const llvm::Type* DestTy =
5274 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005275 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005276 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005277 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005278 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005279 return read_weak;
5280}
5281
5282/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5283/// objc_assign_weak (id src, id *dst)
5284///
5285void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5286 llvm::Value *src, llvm::Value *dst)
5287{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005288 const llvm::Type * SrcTy = src->getType();
5289 if (!isa<llvm::PointerType>(SrcTy)) {
5290 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5291 assert(Size <= 8 && "does not support size > 8");
5292 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5293 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005294 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5295 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005296 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5297 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005298 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005299 src, dst, "weakassign");
5300 return;
5301}
5302
5303/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5304/// objc_assign_global (id src, id *dst)
5305///
5306void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5307 llvm::Value *src, llvm::Value *dst)
5308{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005309 const llvm::Type * SrcTy = src->getType();
5310 if (!isa<llvm::PointerType>(SrcTy)) {
5311 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5312 assert(Size <= 8 && "does not support size > 8");
5313 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5314 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005315 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5316 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005317 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5318 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005319 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005320 src, dst, "globalassign");
5321 return;
5322}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005323
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005324void
5325CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5326 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005327 bool isTry = isa<ObjCAtTryStmt>(S);
5328 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5329 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005330 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005331 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005332 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005333 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5334
5335 // For @synchronized, call objc_sync_enter(sync.expr). The
5336 // evaluation of the expression must occur before we enter the
5337 // @synchronized. We can safely avoid a temp here because jumps into
5338 // @synchronized are illegal & this will dominate uses.
5339 llvm::Value *SyncArg = 0;
5340 if (!isTry) {
5341 SyncArg =
5342 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5343 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005344 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005345 }
5346
5347 // Push an EH context entry, used for handling rethrows and jumps
5348 // through finally.
5349 CGF.PushCleanupBlock(FinallyBlock);
5350
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005351 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005352
5353 CGF.EmitBlock(TryBlock);
5354 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5355 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5356 CGF.EmitBranchThroughCleanup(FinallyEnd);
5357
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005358 // Emit the exception handler.
5359
5360 CGF.EmitBlock(TryHandler);
5361
5362 llvm::Value *llvm_eh_exception =
5363 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5364 llvm::Value *llvm_eh_selector_i64 =
5365 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5366 llvm::Value *llvm_eh_typeid_for_i64 =
5367 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5368 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5369 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5370
5371 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5372 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005373 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005374
5375 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005376 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005377 bool HasCatchAll = false;
5378 if (isTry) {
5379 if (const ObjCAtCatchStmt* CatchStmt =
5380 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5381 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005382 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005383 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005384
5385 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005386 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005387 // Use i8* null here to signal this is a catch all, not a cleanup.
5388 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5389 SelectorArgs.push_back(Null);
5390 HasCatchAll = true;
5391 break;
5392 }
5393
Daniel Dunbarede8de92009-03-06 00:01:21 +00005394 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5395 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005396 llvm::Value *IDEHType =
5397 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5398 if (!IDEHType)
5399 IDEHType =
5400 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5401 llvm::GlobalValue::ExternalLinkage,
5402 0, "OBJC_EHTYPE_id", &CGM.getModule());
5403 SelectorArgs.push_back(IDEHType);
5404 HasCatchAll = true;
5405 break;
5406 }
5407
5408 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005409 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005410 assert(PT && "Invalid @catch type.");
5411 const ObjCInterfaceType *IT =
5412 PT->getPointeeType()->getAsObjCInterfaceType();
5413 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005414 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005415 SelectorArgs.push_back(EHType);
5416 }
5417 }
5418 }
5419
5420 // We use a cleanup unless there was already a catch all.
5421 if (!HasCatchAll) {
5422 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005423 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005424 }
5425
5426 llvm::Value *Selector =
5427 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5428 SelectorArgs.begin(), SelectorArgs.end(),
5429 "selector");
5430 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005431 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005432 const Stmt *CatchBody = Handlers[i].second;
5433
5434 llvm::BasicBlock *Next = 0;
5435
5436 // The last handler always matches.
5437 if (i + 1 != e) {
5438 assert(CatchParam && "Only last handler can be a catch all.");
5439
5440 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5441 Next = CGF.createBasicBlock("catch.next");
5442 llvm::Value *Id =
5443 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5444 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5445 ObjCTypes.Int8PtrTy));
5446 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5447 Match, Next);
5448
5449 CGF.EmitBlock(Match);
5450 }
5451
5452 if (CatchBody) {
5453 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5454 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5455
5456 // Cleanups must call objc_end_catch.
5457 //
5458 // FIXME: It seems incorrect for objc_begin_catch to be inside
5459 // this context, but this matches gcc.
5460 CGF.PushCleanupBlock(MatchEnd);
5461 CGF.setInvokeDest(MatchHandler);
5462
5463 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005464 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005465
5466 // Bind the catch parameter if it exists.
5467 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005468 ExcObject =
5469 CGF.Builder.CreateBitCast(ExcObject,
5470 CGF.ConvertType(CatchParam->getType()));
5471 // CatchParam is a ParmVarDecl because of the grammar
5472 // construction used to handle this, but for codegen purposes
5473 // we treat this as a local decl.
5474 CGF.EmitLocalBlockVarDecl(*CatchParam);
5475 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005476 }
5477
5478 CGF.ObjCEHValueStack.push_back(ExcObject);
5479 CGF.EmitStmt(CatchBody);
5480 CGF.ObjCEHValueStack.pop_back();
5481
5482 CGF.EmitBranchThroughCleanup(FinallyEnd);
5483
5484 CGF.EmitBlock(MatchHandler);
5485
5486 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5487 // We are required to emit this call to satisfy LLVM, even
5488 // though we don't use the result.
5489 llvm::SmallVector<llvm::Value*, 8> Args;
5490 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005491 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005492 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5493 0));
5494 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5495 CGF.Builder.CreateStore(Exc, RethrowPtr);
5496 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5497
5498 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5499
5500 CGF.EmitBlock(MatchEnd);
5501
5502 // Unfortunately, we also have to generate another EH frame here
5503 // in case this throws.
5504 llvm::BasicBlock *MatchEndHandler =
5505 CGF.createBasicBlock("match.end.handler");
5506 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005507 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005508 Cont, MatchEndHandler,
5509 Args.begin(), Args.begin());
5510
5511 CGF.EmitBlock(Cont);
5512 if (Info.SwitchBlock)
5513 CGF.EmitBlock(Info.SwitchBlock);
5514 if (Info.EndBlock)
5515 CGF.EmitBlock(Info.EndBlock);
5516
5517 CGF.EmitBlock(MatchEndHandler);
5518 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5519 // We are required to emit this call to satisfy LLVM, even
5520 // though we don't use the result.
5521 Args.clear();
5522 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005523 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5525 0));
5526 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5527 CGF.Builder.CreateStore(Exc, RethrowPtr);
5528 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5529
5530 if (Next)
5531 CGF.EmitBlock(Next);
5532 } else {
5533 assert(!Next && "catchup should be last handler.");
5534
5535 CGF.Builder.CreateStore(Exc, RethrowPtr);
5536 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5537 }
5538 }
5539
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005540 // Pop the cleanup entry, the @finally is outside this cleanup
5541 // scope.
5542 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5543 CGF.setInvokeDest(PrevLandingPad);
5544
5545 CGF.EmitBlock(FinallyBlock);
5546
5547 if (isTry) {
5548 if (const ObjCAtFinallyStmt* FinallyStmt =
5549 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5550 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5551 } else {
5552 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5553 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005554 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005555 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005556
5557 if (Info.SwitchBlock)
5558 CGF.EmitBlock(Info.SwitchBlock);
5559 if (Info.EndBlock)
5560 CGF.EmitBlock(Info.EndBlock);
5561
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005562 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005563 CGF.EmitBranch(FinallyEnd);
5564
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005565 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005566 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005567 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005568 CGF.Builder.CreateUnreachable();
5569
5570 CGF.EmitBlock(FinallyEnd);
5571}
5572
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005573/// EmitThrowStmt - Generate code for a throw statement.
5574void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5575 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005577 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005578 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005579 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5581 "Unexpected rethrow outside @catch block.");
5582 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005583 }
5584
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005585 llvm::Value *ExceptionAsObject =
5586 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5587 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5588 if (InvokeDest) {
5589 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005590 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005591 Cont, InvokeDest,
5592 &ExceptionAsObject, &ExceptionAsObject + 1);
5593 CGF.EmitBlock(Cont);
5594 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005595 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 CGF.Builder.CreateUnreachable();
5597
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005598 // Clear the insertion point to indicate we are in unreachable code.
5599 CGF.Builder.ClearInsertionPoint();
5600}
Daniel Dunbare588b992009-03-01 04:46:24 +00005601
5602llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005603CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5604 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005605 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005606
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005607 // If we don't need a definition, return the entry if found or check
5608 // if we use an external reference.
5609 if (!ForDefinition) {
5610 if (Entry)
5611 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005612
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005613 // If this type (or a super class) has the __objc_exception__
5614 // attribute, emit an external reference.
5615 if (hasObjCExceptionAttribute(ID))
5616 return Entry =
5617 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5618 llvm::GlobalValue::ExternalLinkage,
5619 0,
5620 (std::string("OBJC_EHTYPE_$_") +
5621 ID->getIdentifier()->getName()),
5622 &CGM.getModule());
5623 }
5624
5625 // Otherwise we need to either make a new entry or fill in the
5626 // initializer.
5627 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005628 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005629 std::string VTableName = "objc_ehtype_vtable";
5630 llvm::GlobalVariable *VTableGV =
5631 CGM.getModule().getGlobalVariable(VTableName);
5632 if (!VTableGV)
5633 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5634 llvm::GlobalValue::ExternalLinkage,
5635 0, VTableName, &CGM.getModule());
5636
5637 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5638
5639 std::vector<llvm::Constant*> Values(3);
5640 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5641 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005642 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005643 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5644
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005645 if (Entry) {
5646 Entry->setInitializer(Init);
5647 } else {
5648 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5649 llvm::GlobalValue::WeakAnyLinkage,
5650 Init,
5651 (std::string("OBJC_EHTYPE_$_") +
5652 ID->getIdentifier()->getName()),
5653 &CGM.getModule());
5654 }
5655
Daniel Dunbar04d40782009-04-14 06:00:08 +00005656 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005657 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005658 Entry->setAlignment(8);
5659
5660 if (ForDefinition) {
5661 Entry->setSection("__DATA,__objc_const");
5662 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5663 } else {
5664 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5665 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005666
5667 return Entry;
5668}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005669
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005670/* *** */
5671
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005672CodeGen::CGObjCRuntime *
5673CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005674 return new CGObjCMac(CGM);
5675}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005676
5677CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005678CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005679 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005680}