blob: d3ac8c92e24f390bb1bdb140dbcbf142496dca15 [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
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Chris Lattner72db6c32009-04-22 02:44:54 +000087 llvm::Constant *getGetPropertyFn() {
88 CodeGen::CodeGenTypes &Types = CGM.getTypes();
89 ASTContext &Ctx = CGM.getContext();
90 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
91 llvm::SmallVector<QualType,16> Params;
92 QualType IdType = Ctx.getObjCIdType();
93 QualType SelType = Ctx.getObjCSelType();
94 Params.push_back(IdType);
95 Params.push_back(SelType);
96 Params.push_back(Ctx.LongTy);
97 Params.push_back(Ctx.BoolTy);
98 const llvm::FunctionType *FTy =
99 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
100 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
101 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
Chris Lattner72db6c32009-04-22 02:44:54 +0000103 llvm::Constant *getSetPropertyFn() {
104 CodeGen::CodeGenTypes &Types = CGM.getTypes();
105 ASTContext &Ctx = CGM.getContext();
106 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
107 llvm::SmallVector<QualType,16> Params;
108 QualType IdType = Ctx.getObjCIdType();
109 QualType SelType = Ctx.getObjCSelType();
110 Params.push_back(IdType);
111 Params.push_back(SelType);
112 Params.push_back(Ctx.LongTy);
113 Params.push_back(IdType);
114 Params.push_back(Ctx.BoolTy);
115 Params.push_back(Ctx.BoolTy);
116 const llvm::FunctionType *FTy =
117 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
118 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
119 }
120
121 llvm::Constant *getEnumerationMutationFn() {
122 // void objc_enumerationMutation (id)
123 std::vector<const llvm::Type*> Args;
124 Args.push_back(ObjectPtrTy);
125 llvm::FunctionType *FTy =
126 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
127 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
128 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000129
130 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000131 llvm::Constant *getGcReadWeakFn() {
132 // id objc_read_weak (id *)
133 std::vector<const llvm::Type*> Args;
134 Args.push_back(ObjectPtrTy->getPointerTo());
135 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
136 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
137 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000138
139 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000140 llvm::Constant *getGcAssignWeakFn() {
141 // id objc_assign_weak (id, id *)
142 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
143 Args.push_back(ObjectPtrTy->getPointerTo());
144 llvm::FunctionType *FTy =
145 llvm::FunctionType::get(ObjectPtrTy, Args, false);
146 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
147 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000148
149 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000150 llvm::Constant *getGcAssignGlobalFn() {
151 // id objc_assign_global(id, id *)
152 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
153 Args.push_back(ObjectPtrTy->getPointerTo());
154 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
155 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
156 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000157
158 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000159 llvm::Constant *getGcAssignIvarFn() {
160 // id objc_assign_ivar(id, id *)
161 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
162 Args.push_back(ObjectPtrTy->getPointerTo());
163 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
164 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
165 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000166
167 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000168 llvm::Constant *getGcAssignStrongCastFn() {
169 // id objc_assign_global(id, id *)
170 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
171 Args.push_back(ObjectPtrTy->getPointerTo());
172 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
173 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
174 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000175
176 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000177 llvm::Constant *getExceptionThrowFn() {
178 // void objc_exception_throw(id)
179 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
180 llvm::FunctionType *FTy =
181 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
182 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
183 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000184
Daniel Dunbar1c566672009-02-24 01:43:46 +0000185 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000186 llvm::Constant *getSyncEnterFn() {
187 // void objc_sync_enter (id)
188 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
189 llvm::FunctionType *FTy =
190 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
191 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
192 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000193
194 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000195 llvm::Constant *getSyncExitFn() {
196 // void objc_sync_exit (id)
197 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
198 llvm::FunctionType *FTy =
199 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
200 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
201 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000202
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000203 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
204 ~ObjCCommonTypesHelper(){}
205};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000206
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000207/// ObjCTypesHelper - Helper class that encapsulates lazy
208/// construction of varies types used during ObjC generation.
209class ObjCTypesHelper : public ObjCCommonTypesHelper {
210private:
211
Chris Lattner4176b0c2009-04-22 02:32:31 +0000212 llvm::Constant *getMessageSendFn() {
213 // id objc_msgSend (id, SEL, ...)
214 std::vector<const llvm::Type*> Params;
215 Params.push_back(ObjectPtrTy);
216 Params.push_back(SelectorPtrTy);
217 return
218 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
219 Params, true),
220 "objc_msgSend");
221 }
222
223 llvm::Constant *getMessageSendStretFn() {
224 // id objc_msgSend_stret (id, SEL, ...)
225 std::vector<const llvm::Type*> Params;
226 Params.push_back(ObjectPtrTy);
227 Params.push_back(SelectorPtrTy);
228 return
229 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
230 Params, true),
231 "objc_msgSend_stret");
232
233 }
234
235 llvm::Constant *getMessageSendFpretFn() {
236 // FIXME: This should be long double on x86_64?
237 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
238 std::vector<const llvm::Type*> Params;
239 Params.push_back(ObjectPtrTy);
240 Params.push_back(SelectorPtrTy);
241 return
242 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
243 Params,
244 true),
245 "objc_msgSend_fpret");
246
247 }
248
249 llvm::Constant *getMessageSendSuperFn() {
250 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
251 std::vector<const llvm::Type*> Params;
252 Params.push_back(SuperPtrTy);
253 Params.push_back(SelectorPtrTy);
254 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
255 Params, true),
256 "objc_msgSendSuper");
257 }
258 llvm::Constant *getMessageSendSuperStretFn() {
259 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
260 // SEL op, ...)
261 std::vector<const llvm::Type*> Params;
262 Params.push_back(Int8PtrTy);
263 Params.push_back(SuperPtrTy);
264 Params.push_back(SelectorPtrTy);
265 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
266 Params, true),
267 "objc_msgSendSuper_stret");
268 }
269
270 llvm::Constant *getMessageSendSuperFpretFn() {
271 // There is no objc_msgSendSuper_fpret? How can that work?
272 return getMessageSendSuperFn();
273 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000274
275public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000276 /// SymtabTy - LLVM type for struct objc_symtab.
277 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000278 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
279 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000280 /// ModuleTy - LLVM type for struct objc_module.
281 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000282
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000283 /// ProtocolTy - LLVM type for struct objc_protocol.
284 const llvm::StructType *ProtocolTy;
285 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
286 const llvm::Type *ProtocolPtrTy;
287 /// ProtocolExtensionTy - LLVM type for struct
288 /// objc_protocol_extension.
289 const llvm::StructType *ProtocolExtensionTy;
290 /// ProtocolExtensionTy - LLVM type for struct
291 /// objc_protocol_extension *.
292 const llvm::Type *ProtocolExtensionPtrTy;
293 /// MethodDescriptionTy - LLVM type for struct
294 /// objc_method_description.
295 const llvm::StructType *MethodDescriptionTy;
296 /// MethodDescriptionListTy - LLVM type for struct
297 /// objc_method_description_list.
298 const llvm::StructType *MethodDescriptionListTy;
299 /// MethodDescriptionListPtrTy - LLVM type for struct
300 /// objc_method_description_list *.
301 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000302 /// ProtocolListTy - LLVM type for struct objc_property_list.
303 const llvm::Type *ProtocolListTy;
304 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
305 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000306 /// CategoryTy - LLVM type for struct objc_category.
307 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000308 /// ClassTy - LLVM type for struct objc_class.
309 const llvm::StructType *ClassTy;
310 /// ClassPtrTy - LLVM type for struct objc_class *.
311 const llvm::Type *ClassPtrTy;
312 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
313 const llvm::StructType *ClassExtensionTy;
314 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
315 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000316 // IvarTy - LLVM type for struct objc_ivar.
317 const llvm::StructType *IvarTy;
318 /// IvarListTy - LLVM type for struct objc_ivar_list.
319 const llvm::Type *IvarListTy;
320 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
321 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000322 /// MethodListTy - LLVM type for struct objc_method_list.
323 const llvm::Type *MethodListTy;
324 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
325 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000326
327 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
328 const llvm::Type *ExceptionDataTy;
329
Anders Carlsson124526b2008-09-09 10:10:21 +0000330 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000331 llvm::Constant *getExceptionTryEnterFn() {
332 std::vector<const llvm::Type*> Params;
333 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
334 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
335 Params, false),
336 "objc_exception_try_enter");
337 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000338
339 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000340 llvm::Constant *getExceptionTryExitFn() {
341 std::vector<const llvm::Type*> Params;
342 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
343 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
344 Params, false),
345 "objc_exception_try_exit");
346 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000347
348 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000349 llvm::Constant *getExceptionExtractFn() {
350 std::vector<const llvm::Type*> Params;
351 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
352 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
353 Params, false),
354 "objc_exception_extract");
355
356 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000357
358 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000359 llvm::Constant *getExceptionMatchFn() {
360 std::vector<const llvm::Type*> Params;
361 Params.push_back(ClassPtrTy);
362 Params.push_back(ObjectPtrTy);
363 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
364 Params, false),
365 "objc_exception_match");
366
367 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000368
369 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000370 llvm::Constant *getSetJmpFn() {
371 std::vector<const llvm::Type*> Params;
372 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
373 return
374 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
375 Params, false),
376 "_setjmp");
377
378 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000379
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000380public:
381 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000382 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000383
384
Chris Lattner74391b42009-03-22 21:03:39 +0000385 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000386 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000387 }
388
Chris Lattner74391b42009-03-22 21:03:39 +0000389 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000390 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000391 }
392
Chris Lattner74391b42009-03-22 21:03:39 +0000393 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000394 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000395 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000396};
397
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000398/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000399/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000400class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000401public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000402
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000403 // MethodListnfABITy - LLVM for struct _method_list_t
404 const llvm::StructType *MethodListnfABITy;
405
406 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
407 const llvm::Type *MethodListnfABIPtrTy;
408
409 // ProtocolnfABITy = LLVM for struct _protocol_t
410 const llvm::StructType *ProtocolnfABITy;
411
Daniel Dunbar948e2582009-02-15 07:36:20 +0000412 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
413 const llvm::Type *ProtocolnfABIPtrTy;
414
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000415 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
416 const llvm::StructType *ProtocolListnfABITy;
417
418 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
419 const llvm::Type *ProtocolListnfABIPtrTy;
420
421 // ClassnfABITy - LLVM for struct _class_t
422 const llvm::StructType *ClassnfABITy;
423
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000424 // ClassnfABIPtrTy - LLVM for struct _class_t*
425 const llvm::Type *ClassnfABIPtrTy;
426
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000427 // IvarnfABITy - LLVM for struct _ivar_t
428 const llvm::StructType *IvarnfABITy;
429
430 // IvarListnfABITy - LLVM for struct _ivar_list_t
431 const llvm::StructType *IvarListnfABITy;
432
433 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
434 const llvm::Type *IvarListnfABIPtrTy;
435
436 // ClassRonfABITy - LLVM for struct _class_ro_t
437 const llvm::StructType *ClassRonfABITy;
438
439 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
440 const llvm::Type *ImpnfABITy;
441
442 // CategorynfABITy - LLVM for struct _category_t
443 const llvm::StructType *CategorynfABITy;
444
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000445 // New types for nonfragile abi messaging.
446
447 // MessageRefTy - LLVM for:
448 // struct _message_ref_t {
449 // IMP messenger;
450 // SEL name;
451 // };
452 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000453 // MessageRefCTy - clang type for struct _message_ref_t
454 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000455
456 // MessageRefPtrTy - LLVM for struct _message_ref_t*
457 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000458 // MessageRefCPtrTy - clang type for struct _message_ref_t*
459 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000460
Fariborz Jahanianef163782009-02-05 01:13:09 +0000461 // MessengerTy - Type of the messenger (shown as IMP above)
462 const llvm::FunctionType *MessengerTy;
463
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000464 // SuperMessageRefTy - LLVM for:
465 // struct _super_message_ref_t {
466 // SUPER_IMP messenger;
467 // SEL name;
468 // };
469 const llvm::StructType *SuperMessageRefTy;
470
471 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
472 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000473
Chris Lattner1c02f862009-04-22 02:53:24 +0000474 llvm::Constant *getMessageSendFixupFn() {
475 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
476 std::vector<const llvm::Type*> Params;
477 Params.push_back(ObjectPtrTy);
478 Params.push_back(MessageRefPtrTy);
479 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
480 Params, true),
481 "objc_msgSend_fixup");
482 }
483
484 llvm::Constant *getMessageSendFpretFixupFn() {
485 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
486 std::vector<const llvm::Type*> Params;
487 Params.push_back(ObjectPtrTy);
488 Params.push_back(MessageRefPtrTy);
489 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
490 Params, true),
491 "objc_msgSend_fpret_fixup");
492 }
493
494 llvm::Constant *getMessageSendStretFixupFn() {
495 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
496 std::vector<const llvm::Type*> Params;
497 Params.push_back(ObjectPtrTy);
498 Params.push_back(MessageRefPtrTy);
499 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
500 Params, true),
501 "objc_msgSend_stret_fixup");
502 }
503
504 llvm::Constant *getMessageSendIdFixupFn() {
505 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
506 std::vector<const llvm::Type*> Params;
507 Params.push_back(ObjectPtrTy);
508 Params.push_back(MessageRefPtrTy);
509 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
510 Params, true),
511 "objc_msgSendId_fixup");
512 }
513
514 llvm::Constant *getMessageSendIdStretFixupFn() {
515 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
516 std::vector<const llvm::Type*> Params;
517 Params.push_back(ObjectPtrTy);
518 Params.push_back(MessageRefPtrTy);
519 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
520 Params, true),
521 "objc_msgSendId_stret_fixup");
522 }
523 llvm::Constant *getMessageSendSuper2FixupFn() {
524 // id objc_msgSendSuper2_fixup (struct objc_super *,
525 // struct _super_message_ref_t*, ...)
526 std::vector<const llvm::Type*> Params;
527 Params.push_back(SuperPtrTy);
528 Params.push_back(SuperMessageRefPtrTy);
529 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
530 Params, true),
531 "objc_msgSendSuper2_fixup");
532 }
533
534 llvm::Constant *getMessageSendSuper2StretFixupFn() {
535 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
536 // struct _super_message_ref_t*, ...)
537 std::vector<const llvm::Type*> Params;
538 Params.push_back(SuperPtrTy);
539 Params.push_back(SuperMessageRefPtrTy);
540 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
541 Params, true),
542 "objc_msgSendSuper2_stret_fixup");
543 }
544
545
546
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000547 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
548 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000549 llvm::Value *getEHPersonalityPtr() {
550 llvm::Constant *Personality =
551 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
552 std::vector<const llvm::Type*>(),
553 true),
554 "__objc_personality_v0");
555 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
556 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000557
Chris Lattner8a569112009-04-22 02:15:23 +0000558 llvm::Constant *getUnwindResumeOrRethrowFn() {
559 std::vector<const llvm::Type*> Params;
560 Params.push_back(Int8PtrTy);
561 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
562 Params, false),
563 "_Unwind_Resume_or_Rethrow");
564 }
565
566 llvm::Constant *getObjCEndCatchFn() {
567 std::vector<const llvm::Type*> Params;
568 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
569 Params, false),
570 "objc_end_catch");
571
572 }
573
574 llvm::Constant *getObjCBeginCatchFn() {
575 std::vector<const llvm::Type*> Params;
576 Params.push_back(Int8PtrTy);
577 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
578 Params, false),
579 "objc_begin_catch");
580 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000581
582 const llvm::StructType *EHTypeTy;
583 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000584
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000585 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
586 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000587};
588
589class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000590public:
591 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000592 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000593 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000594 unsigned int ivar_bytepos;
595 unsigned int ivar_size;
596 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
597 };
598
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000599 class SKIP_SCAN {
600 public:
601 unsigned int skip;
602 unsigned int scan;
603 SKIP_SCAN() : skip(0), scan(0) {}
604 };
605
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000606protected:
607 CodeGen::CodeGenModule &CGM;
608 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000609 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000610
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000611 // gc ivar layout bitmap calculation helper caches.
612 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
613 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
614 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000615
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000616 /// LazySymbols - Symbols to generate a lazy reference for. See
617 /// DefinedSymbols and FinishModule().
618 std::set<IdentifierInfo*> LazySymbols;
619
620 /// DefinedSymbols - External symbols which are defined by this
621 /// module. The symbols in this list and LazySymbols are used to add
622 /// special linker symbols which ensure that Objective-C modules are
623 /// linked properly.
624 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000625
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000626 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000627 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000628
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000629 /// MethodVarNames - uniqued method variable names.
630 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000631
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000632 /// MethodVarTypes - uniqued method type signatures. We have to use
633 /// a StringMap here because have no other unique reference.
634 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000635
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000636 /// MethodDefinitions - map of methods which have been defined in
637 /// this translation unit.
638 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000639
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000640 /// PropertyNames - uniqued method variable names.
641 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000642
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000643 /// ClassReferences - uniqued class references.
644 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000645
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000646 /// SelectorReferences - uniqued selector references.
647 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000648
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000649 /// Protocols - Protocols for which an objc_protocol structure has
650 /// been emitted. Forward declarations are handled by creating an
651 /// empty structure whose initializer is filled in when/if defined.
652 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000653
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000654 /// DefinedProtocols - Protocols which have actually been
655 /// defined. We should not need this, see FIXME in GenerateProtocol.
656 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000657
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000658 /// DefinedClasses - List of defined classes.
659 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000660
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000661 /// DefinedCategories - List of defined categories.
662 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000663
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000664 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000665 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000666 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000667
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000668 /// GetNameForMethod - Return a name for the given method.
669 /// \param[out] NameOut - The return value.
670 void GetNameForMethod(const ObjCMethodDecl *OMD,
671 const ObjCContainerDecl *CD,
672 std::string &NameOut);
673
674 /// GetMethodVarName - Return a unique constant for the given
675 /// selector's name. The return value has type char *.
676 llvm::Constant *GetMethodVarName(Selector Sel);
677 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
678 llvm::Constant *GetMethodVarName(const std::string &Name);
679
680 /// GetMethodVarType - Return a unique constant for the given
681 /// selector's name. The return value has type char *.
682
683 // FIXME: This is a horrible name.
684 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000685 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000686
687 /// GetPropertyName - Return a unique constant for the given
688 /// name. The return value has type char *.
689 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
690
691 // FIXME: This can be dropped once string functions are unified.
692 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
693 const Decl *Container);
694
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000695 /// GetClassName - Return a unique constant for the given selector's
696 /// name. The return value has type char *.
697 llvm::Constant *GetClassName(IdentifierInfo *Ident);
698
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000699 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
700 /// interface declaration.
701 const llvm::StructLayout *GetInterfaceDeclStructLayout(
702 const ObjCInterfaceDecl *ID) const;
703
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000704 /// BuildIvarLayout - Builds ivar layout bitmap for the class
705 /// implementation for the __strong or __weak case.
706 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000707 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
708 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000709
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000710 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
711 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000712 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000713 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000714 unsigned int BytePos, bool ForStrongLayout,
715 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000716
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000717 /// GetIvarLayoutName - Returns a unique constant for the given
718 /// ivar layout bitmap.
719 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
720 const ObjCCommonTypesHelper &ObjCTypes);
721
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000722 /// EmitPropertyList - Emit the given property list. The return
723 /// value has type PropertyListPtrTy.
724 llvm::Constant *EmitPropertyList(const std::string &Name,
725 const Decl *Container,
726 const ObjCContainerDecl *OCD,
727 const ObjCCommonTypesHelper &ObjCTypes);
728
Fariborz Jahanianda320092009-01-29 19:24:30 +0000729 /// GetProtocolRef - Return a reference to the internal protocol
730 /// description, creating an empty one if it has not been
731 /// defined. The return value has type ProtocolPtrTy.
732 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000733
734 /// GetIvarBaseOffset - returns ivars byte offset.
735 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000736 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000737
Chris Lattnercd0ee142009-03-31 08:33:16 +0000738 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000739 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
740 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000741 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000742
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000743 /// CreateMetadataVar - Create a global variable with internal
744 /// linkage for use by the Objective-C runtime.
745 ///
746 /// This is a convenience wrapper which not only creates the
747 /// variable, but also sets the section and alignment and adds the
748 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000749 ///
750 /// \param Name - The variable name.
751 /// \param Init - The variable initializer; this is also used to
752 /// define the type of the variable.
753 /// \param Section - The section the variable should go into, or 0.
754 /// \param Align - The alignment for the variable, or 0.
755 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000756 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000757 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
758 llvm::Constant *Init,
759 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000760 unsigned Align,
761 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000762
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000763 /// GetNamedIvarList - Return the list of ivars in the interface
764 /// itself (not including super classes and not including unnamed
765 /// bitfields).
766 ///
767 /// For the non-fragile ABI, this also includes synthesized property
768 /// ivars.
769 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
770 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
771
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000772public:
773 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
774 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000775
Steve Naroff33fdb732009-03-31 16:53:37 +0000776 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000777
778 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
779 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000780
781 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
782
783 /// GetOrEmitProtocol - Get the protocol object for the given
784 /// declaration, emitting it if necessary. The return value has type
785 /// ProtocolPtrTy.
786 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
787
788 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
789 /// object for the given declaration, emitting it if needed. These
790 /// forward references will be filled in with empty bodies if no
791 /// definition is seen. The return value has type ProtocolPtrTy.
792 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000793};
794
795class CGObjCMac : public CGObjCCommonMac {
796private:
797 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000798 /// EmitImageInfo - Emit the image info marker used to encode some module
799 /// level information.
800 void EmitImageInfo();
801
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000802 /// EmitModuleInfo - Another marker encoding module level
803 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000804 void EmitModuleInfo();
805
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000806 /// EmitModuleSymols - Emit module symbols, the list of defined
807 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000808 llvm::Constant *EmitModuleSymbols();
809
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000810 /// FinishModule - Write out global data structures at the end of
811 /// processing a translation unit.
812 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000813
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000814 /// EmitClassExtension - Generate the class extension structure used
815 /// to store the weak ivar layout and properties. The return value
816 /// has type ClassExtensionPtrTy.
817 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
818
819 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
820 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000821 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000822 const ObjCInterfaceDecl *ID);
823
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000824 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000825 QualType ResultType,
826 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000827 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000828 QualType Arg0Ty,
829 bool IsSuper,
830 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000831
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000832 /// EmitIvarList - Emit the ivar list for the given
833 /// implementation. If ForClass is true the list of class ivars
834 /// (i.e. metaclass ivars) is emitted, otherwise the list of
835 /// interface ivars will be emitted. The return value has type
836 /// IvarListPtrTy.
837 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000838 bool ForClass);
839
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000840 /// EmitMetaClass - Emit a forward reference to the class structure
841 /// for the metaclass of the given interface. The return value has
842 /// type ClassPtrTy.
843 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
844
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000845 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000846 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000847 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
848 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000849 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000850 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000851
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000852 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000853
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000854 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000855
856 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000857 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000858 llvm::Constant *EmitMethodList(const std::string &Name,
859 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000860 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000861
862 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000863 /// method declarations.
864 /// - TypeName: The name for the type containing the methods.
865 /// - IsProtocol: True iff these methods are for a protocol.
866 /// - ClassMethds: True iff these are class methods.
867 /// - Required: When true, only "required" methods are
868 /// listed. Similarly, when false only "optional" methods are
869 /// listed. For classes this should always be true.
870 /// - begin, end: The method list to output.
871 ///
872 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000873 llvm::Constant *EmitMethodDescList(const std::string &Name,
874 const char *Section,
875 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000876
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000877 /// GetOrEmitProtocol - Get the protocol object for the given
878 /// declaration, emitting it if necessary. The return value has type
879 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000880 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000881
882 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
883 /// object for the given declaration, emitting it if needed. These
884 /// forward references will be filled in with empty bodies if no
885 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000886 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000887
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000888 /// EmitProtocolExtension - Generate the protocol extension
889 /// structure used to store optional instance and class methods, and
890 /// protocol properties. The return value has type
891 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000892 llvm::Constant *
893 EmitProtocolExtension(const ObjCProtocolDecl *PD,
894 const ConstantVector &OptInstanceMethods,
895 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000896
897 /// EmitProtocolList - Generate the list of referenced
898 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000899 llvm::Constant *EmitProtocolList(const std::string &Name,
900 ObjCProtocolDecl::protocol_iterator begin,
901 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000902
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000903 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
904 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000905 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000906
Fariborz Jahanianda320092009-01-29 19:24:30 +0000907 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000908 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000909
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000910 virtual llvm::Function *ModuleInitFunction();
911
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000912 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000913 QualType ResultType,
914 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000915 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000916 bool IsClassMessage,
917 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000918
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000919 virtual CodeGen::RValue
920 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000921 QualType ResultType,
922 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000923 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000924 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000925 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000926 bool IsClassMessage,
927 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000928
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000929 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000930 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000931
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000932 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000933
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000934 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000935
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000936 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000937
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000938 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000939 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000940
Chris Lattner74391b42009-03-22 21:03:39 +0000941 virtual llvm::Constant *GetPropertyGetFunction();
942 virtual llvm::Constant *GetPropertySetFunction();
943 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000944
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000945 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
946 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000947 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
948 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000949 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000950 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000951 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
952 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000953 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
954 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000955 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
956 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000957 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
958 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000959
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000960 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
961 QualType ObjectTy,
962 llvm::Value *BaseValue,
963 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000964 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000965 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000966 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000967 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000968};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000969
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000970class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000971private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000972 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000973 llvm::GlobalVariable* ObjCEmptyCacheVar;
974 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000975
Daniel Dunbar11394522009-04-18 08:51:00 +0000976 /// SuperClassReferences - uniqued super class references.
977 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
978
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000979 /// MetaClassReferences - uniqued meta class references.
980 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000981
982 /// EHTypeReferences - uniqued class ehtype references.
983 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000984
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000985 /// FinishNonFragileABIModule - Write out global data structures at the end of
986 /// processing a translation unit.
987 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +0000988
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000989 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
990 unsigned InstanceStart,
991 unsigned InstanceSize,
992 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000993 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
994 llvm::Constant *IsAGV,
995 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000996 llvm::Constant *ClassRoGV,
997 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000998
999 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1000
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001001 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1002
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001003 /// EmitMethodList - Emit the method list for the given
1004 /// implementation. The return value has type MethodListnfABITy.
1005 llvm::Constant *EmitMethodList(const std::string &Name,
1006 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001007 const ConstantVector &Methods);
1008 /// EmitIvarList - Emit the ivar list for the given
1009 /// implementation. If ForClass is true the list of class ivars
1010 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1011 /// interface ivars will be emitted. The return value has type
1012 /// IvarListnfABIPtrTy.
1013 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001014
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001015 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001016 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001017 unsigned long int offset);
1018
Fariborz Jahanianda320092009-01-29 19:24:30 +00001019 /// GetOrEmitProtocol - Get the protocol object for the given
1020 /// declaration, emitting it if necessary. The return value has type
1021 /// ProtocolPtrTy.
1022 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1023
1024 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1025 /// object for the given declaration, emitting it if needed. These
1026 /// forward references will be filled in with empty bodies if no
1027 /// definition is seen. The return value has type ProtocolPtrTy.
1028 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1029
1030 /// EmitProtocolList - Generate the list of referenced
1031 /// protocols. The return value has type ProtocolListPtrTy.
1032 llvm::Constant *EmitProtocolList(const std::string &Name,
1033 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001034 ObjCProtocolDecl::protocol_iterator end);
1035
1036 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1037 QualType ResultType,
1038 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001039 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001040 QualType Arg0Ty,
1041 bool IsSuper,
1042 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001043
1044 /// GetClassGlobal - Return the global variable for the Objective-C
1045 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001046 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1047
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001048 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001049 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001050 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001051 const ObjCInterfaceDecl *ID);
1052
1053 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1054 /// for the given super class reference.
1055 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1056 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001057
1058 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1059 /// meta-data
1060 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1061 const ObjCInterfaceDecl *ID);
1062
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001063 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1064 /// the given ivar.
1065 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001066 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001067 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001068 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001069
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001070 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1071 /// for the given selector.
1072 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001073
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001074 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001075 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001076 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1077 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001078
1079 const char *getMetaclassSymbolPrefix() const {
1080 return "OBJC_METACLASS_$_";
1081 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001082
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001083 const char *getClassSymbolPrefix() const {
1084 return "OBJC_CLASS_$_";
1085 }
1086
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001087 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1088 uint32_t &InstanceStart,
1089 uint32_t &InstanceSize);
1090
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001091public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001092 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001093 // FIXME. All stubs for now!
1094 virtual llvm::Function *ModuleInitFunction();
1095
1096 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1097 QualType ResultType,
1098 Selector Sel,
1099 llvm::Value *Receiver,
1100 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001101 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001102
1103 virtual CodeGen::RValue
1104 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1105 QualType ResultType,
1106 Selector Sel,
1107 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001108 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001109 llvm::Value *Receiver,
1110 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001111 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001112
1113 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001114 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001115
1116 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001117 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001118
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001119 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001120
1121 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001122 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001123 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001124
Chris Lattner74391b42009-03-22 21:03:39 +00001125 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001126 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001127 }
Chris Lattner74391b42009-03-22 21:03:39 +00001128 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001129 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001130 }
Chris Lattner74391b42009-03-22 21:03:39 +00001131 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001132 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001133 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001134
1135 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001136 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001137 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001138 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001139 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001140 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001141 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001142 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001143 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001144 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001145 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001146 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001147 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001148 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001149 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1150 QualType ObjectTy,
1151 llvm::Value *BaseValue,
1152 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001153 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001154 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001155 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001156 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001157};
1158
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001159} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001160
1161/* *** Helper Functions *** */
1162
1163/// getConstantGEP() - Help routine to construct simple GEPs.
1164static llvm::Constant *getConstantGEP(llvm::Constant *C,
1165 unsigned idx0,
1166 unsigned idx1) {
1167 llvm::Value *Idxs[] = {
1168 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1169 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1170 };
1171 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1172}
1173
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001174/// hasObjCExceptionAttribute - Return true if this class or any super
1175/// class has the __objc_exception__ attribute.
1176static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001177 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001178 return true;
1179 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1180 return hasObjCExceptionAttribute(Super);
1181 return false;
1182}
1183
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001184/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001185
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001186CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1187 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001188{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001189 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001190 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001191}
1192
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001193/// GetClass - Return a reference to the class for the given interface
1194/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001195llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001196 const ObjCInterfaceDecl *ID) {
1197 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001198}
1199
1200/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001201llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001202 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001203}
1204
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001205/// Generate a constant CFString object.
1206/*
1207 struct __builtin_CFString {
1208 const int *isa; // point to __CFConstantStringClassReference
1209 int flags;
1210 const char *str;
1211 long length;
1212 };
1213*/
1214
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001215llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001216 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001217 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001218}
1219
1220/// Generates a message send where the super is the receiver. This is
1221/// a message send to self with special delivery semantics indicating
1222/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001223CodeGen::RValue
1224CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001225 QualType ResultType,
1226 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001227 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001228 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001229 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001230 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001231 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001232 // Create and init a super structure; this is a (receiver, class)
1233 // pair we will pass to objc_msgSendSuper.
1234 llvm::Value *ObjCSuper =
1235 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1236 llvm::Value *ReceiverAsObject =
1237 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1238 CGF.Builder.CreateStore(ReceiverAsObject,
1239 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001240
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001241 // If this is a class message the metaclass is passed as the target.
1242 llvm::Value *Target;
1243 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001244 if (isCategoryImpl) {
1245 // Message sent to 'super' in a class method defined in a category
1246 // implementation requires an odd treatment.
1247 // If we are in a class method, we must retrieve the
1248 // _metaclass_ for the current class, pointed at by
1249 // the class's "isa" pointer. The following assumes that
1250 // isa" is the first ivar in a class (which it must be).
1251 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1252 Target = CGF.Builder.CreateStructGEP(Target, 0);
1253 Target = CGF.Builder.CreateLoad(Target);
1254 }
1255 else {
1256 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1257 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1258 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1259 Target = Super;
1260 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001261 } else {
1262 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1263 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001264 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1265 // and ObjCTypes types.
1266 const llvm::Type *ClassTy =
1267 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001268 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001269 CGF.Builder.CreateStore(Target,
1270 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1271
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001272 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001273 ObjCSuper, ObjCTypes.SuperPtrCTy,
1274 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001275}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001276
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001277/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001278CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001279 QualType ResultType,
1280 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001281 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001282 bool IsClassMessage,
1283 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001284 llvm::Value *Arg0 =
1285 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001286 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001287 Arg0, CGF.getContext().getObjCIdType(),
1288 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001289}
1290
1291CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001292 QualType ResultType,
1293 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001294 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001295 QualType Arg0Ty,
1296 bool IsSuper,
1297 const CallArgList &CallArgs) {
1298 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001299 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1300 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1301 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001302 CGF.getContext().getObjCSelType()));
1303 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001304
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001305 CodeGenTypes &Types = CGM.getTypes();
1306 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1307 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001308
1309 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001310 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001311 Fn = ObjCTypes.getSendStretFn(IsSuper);
1312 } else if (ResultType->isFloatingType()) {
1313 // FIXME: Sadly, this is wrong. This actually depends on the
1314 // architecture. This happens to be right for x86-32 though.
1315 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1316 } else {
1317 Fn = ObjCTypes.getSendFn(IsSuper);
1318 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001319 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001320 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001321}
1322
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001323llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001324 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001325 // FIXME: I don't understand why gcc generates this, or where it is
1326 // resolved. Investigate. Its also wasteful to look this up over and
1327 // over.
1328 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1329
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001330 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1331 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001332}
1333
Fariborz Jahanianda320092009-01-29 19:24:30 +00001334void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001335 // FIXME: We shouldn't need this, the protocol decl should contain
1336 // enough information to tell us whether this was a declaration or a
1337 // definition.
1338 DefinedProtocols.insert(PD->getIdentifier());
1339
1340 // If we have generated a forward reference to this protocol, emit
1341 // it now. Otherwise do nothing, the protocol objects are lazily
1342 // emitted.
1343 if (Protocols.count(PD->getIdentifier()))
1344 GetOrEmitProtocol(PD);
1345}
1346
Fariborz Jahanianda320092009-01-29 19:24:30 +00001347llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001348 if (DefinedProtocols.count(PD->getIdentifier()))
1349 return GetOrEmitProtocol(PD);
1350 return GetOrEmitProtocolRef(PD);
1351}
1352
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001353/*
1354 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1355 struct _objc_protocol {
1356 struct _objc_protocol_extension *isa;
1357 char *protocol_name;
1358 struct _objc_protocol_list *protocol_list;
1359 struct _objc__method_prototype_list *instance_methods;
1360 struct _objc__method_prototype_list *class_methods
1361 };
1362
1363 See EmitProtocolExtension().
1364*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001365llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1366 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1367
1368 // Early exit if a defining object has already been generated.
1369 if (Entry && Entry->hasInitializer())
1370 return Entry;
1371
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001372 // FIXME: I don't understand why gcc generates this, or where it is
1373 // resolved. Investigate. Its also wasteful to look this up over and
1374 // over.
1375 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1376
Chris Lattner8ec03f52008-11-24 03:54:41 +00001377 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001378
1379 // Construct method lists.
1380 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1381 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001382 for (ObjCProtocolDecl::instmeth_iterator
1383 i = PD->instmeth_begin(CGM.getContext()),
1384 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001385 ObjCMethodDecl *MD = *i;
1386 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1387 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1388 OptInstanceMethods.push_back(C);
1389 } else {
1390 InstanceMethods.push_back(C);
1391 }
1392 }
1393
Douglas Gregor6ab35242009-04-09 21:40:53 +00001394 for (ObjCProtocolDecl::classmeth_iterator
1395 i = PD->classmeth_begin(CGM.getContext()),
1396 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001397 ObjCMethodDecl *MD = *i;
1398 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1399 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1400 OptClassMethods.push_back(C);
1401 } else {
1402 ClassMethods.push_back(C);
1403 }
1404 }
1405
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001406 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001407 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001408 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001409 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001410 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001411 PD->protocol_begin(),
1412 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001413 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001414 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1415 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001416 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1417 InstanceMethods);
1418 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001419 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1420 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001421 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1422 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001423 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1424 Values);
1425
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001426 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001427 // Already created, fix the linkage and update the initializer.
1428 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001429 Entry->setInitializer(Init);
1430 } else {
1431 Entry =
1432 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1433 llvm::GlobalValue::InternalLinkage,
1434 Init,
1435 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1436 &CGM.getModule());
1437 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001438 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001439 UsedGlobals.push_back(Entry);
1440 // FIXME: Is this necessary? Why only for protocol?
1441 Entry->setAlignment(4);
1442 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001443
1444 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001445}
1446
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001447llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001448 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1449
1450 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001451 // We use the initializer as a marker of whether this is a forward
1452 // reference or not. At module finalization we add the empty
1453 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001454 Entry =
1455 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001456 llvm::GlobalValue::ExternalLinkage,
1457 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001458 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001459 &CGM.getModule());
1460 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001461 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001462 UsedGlobals.push_back(Entry);
1463 // FIXME: Is this necessary? Why only for protocol?
1464 Entry->setAlignment(4);
1465 }
1466
1467 return Entry;
1468}
1469
1470/*
1471 struct _objc_protocol_extension {
1472 uint32_t size;
1473 struct objc_method_description_list *optional_instance_methods;
1474 struct objc_method_description_list *optional_class_methods;
1475 struct objc_property_list *instance_properties;
1476 };
1477*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001478llvm::Constant *
1479CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1480 const ConstantVector &OptInstanceMethods,
1481 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001482 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001483 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001484 std::vector<llvm::Constant*> Values(4);
1485 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001486 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001487 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1488 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001489 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1490 OptInstanceMethods);
1491 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001492 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1493 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001494 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1495 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001496 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1497 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001498 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001499
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001500 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001501 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1502 Values[3]->isNullValue())
1503 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1504
1505 llvm::Constant *Init =
1506 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001507
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001508 // No special section, but goes in llvm.used
1509 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1510 Init,
1511 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001512}
1513
1514/*
1515 struct objc_protocol_list {
1516 struct objc_protocol_list *next;
1517 long count;
1518 Protocol *list[];
1519 };
1520*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001521llvm::Constant *
1522CGObjCMac::EmitProtocolList(const std::string &Name,
1523 ObjCProtocolDecl::protocol_iterator begin,
1524 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001525 std::vector<llvm::Constant*> ProtocolRefs;
1526
Daniel Dunbardbc933702008-08-21 21:57:41 +00001527 for (; begin != end; ++begin)
1528 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001529
1530 // Just return null for empty protocol lists
1531 if (ProtocolRefs.empty())
1532 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1533
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001535 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1536
1537 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001538 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001539 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1540 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1541 Values[2] =
1542 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1543 ProtocolRefs.size()),
1544 ProtocolRefs);
1545
1546 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1547 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001548 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001549 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001550 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1551}
1552
1553/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001554 struct _objc_property {
1555 const char * const name;
1556 const char * const attributes;
1557 };
1558
1559 struct _objc_property_list {
1560 uint32_t entsize; // sizeof (struct _objc_property)
1561 uint32_t prop_count;
1562 struct _objc_property[prop_count];
1563 };
1564*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001565llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1566 const Decl *Container,
1567 const ObjCContainerDecl *OCD,
1568 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001569 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001570 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1571 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001572 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001573 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001574 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001575 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1576 Prop));
1577 }
1578
1579 // Return null for empty list.
1580 if (Properties.empty())
1581 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1582
1583 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001584 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001585 std::vector<llvm::Constant*> Values(3);
1586 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1587 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1588 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1589 Properties.size());
1590 Values[2] = llvm::ConstantArray::get(AT, Properties);
1591 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1592
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001593 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001594 CreateMetadataVar(Name, Init,
1595 (ObjCABI == 2) ? "__DATA, __objc_const" :
1596 "__OBJC,__property,regular,no_dead_strip",
1597 (ObjCABI == 2) ? 8 : 4,
1598 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001599 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001600}
1601
1602/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001603 struct objc_method_description_list {
1604 int count;
1605 struct objc_method_description list[];
1606 };
1607*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001608llvm::Constant *
1609CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1610 std::vector<llvm::Constant*> Desc(2);
1611 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1612 ObjCTypes.SelectorPtrTy);
1613 Desc[1] = GetMethodVarType(MD);
1614 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1615 Desc);
1616}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001617
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001618llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1619 const char *Section,
1620 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001621 // Return null for empty list.
1622 if (Methods.empty())
1623 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1624
1625 std::vector<llvm::Constant*> Values(2);
1626 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1627 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1628 Methods.size());
1629 Values[1] = llvm::ConstantArray::get(AT, Methods);
1630 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1631
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001632 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001633 return llvm::ConstantExpr::getBitCast(GV,
1634 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001635}
1636
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001637/*
1638 struct _objc_category {
1639 char *category_name;
1640 char *class_name;
1641 struct _objc_method_list *instance_methods;
1642 struct _objc_method_list *class_methods;
1643 struct _objc_protocol_list *protocols;
1644 uint32_t size; // <rdar://4585769>
1645 struct _objc_property_list *instance_properties;
1646 };
1647 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001648void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001649 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001650
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001651 // FIXME: This is poor design, the OCD should have a pointer to the
1652 // category decl. Additionally, note that Category can be null for
1653 // the @implementation w/o an @interface case. Sema should just
1654 // create one for us as it does for @implementation so everyone else
1655 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001656 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001657 const ObjCCategoryDecl *Category =
1658 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001659 std::string ExtName(Interface->getNameAsString() + "_" +
1660 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001661
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001662 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1663 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1664 e = OCD->instmeth_end(); i != e; ++i) {
1665 // Instance methods should always be defined.
1666 InstanceMethods.push_back(GetMethodConstant(*i));
1667 }
1668 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1669 e = OCD->classmeth_end(); i != e; ++i) {
1670 // Class methods should always be defined.
1671 ClassMethods.push_back(GetMethodConstant(*i));
1672 }
1673
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001674 std::vector<llvm::Constant*> Values(7);
1675 Values[0] = GetClassName(OCD->getIdentifier());
1676 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001677 Values[2] =
1678 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1679 ExtName,
1680 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001681 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001682 Values[3] =
1683 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001684 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001685 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001686 if (Category) {
1687 Values[4] =
1688 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1689 Category->protocol_begin(),
1690 Category->protocol_end());
1691 } else {
1692 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1693 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001694 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001695
1696 // If there is no category @interface then there can be no properties.
1697 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001698 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001699 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001700 } else {
1701 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1702 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001703
1704 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1705 Values);
1706
1707 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001708 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1709 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001710 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001711 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001712}
1713
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001714// FIXME: Get from somewhere?
1715enum ClassFlags {
1716 eClassFlags_Factory = 0x00001,
1717 eClassFlags_Meta = 0x00002,
1718 // <rdr://5142207>
1719 eClassFlags_HasCXXStructors = 0x02000,
1720 eClassFlags_Hidden = 0x20000,
1721 eClassFlags_ABI2_Hidden = 0x00010,
1722 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1723};
1724
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001725/*
1726 struct _objc_class {
1727 Class isa;
1728 Class super_class;
1729 const char *name;
1730 long version;
1731 long info;
1732 long instance_size;
1733 struct _objc_ivar_list *ivars;
1734 struct _objc_method_list *methods;
1735 struct _objc_cache *cache;
1736 struct _objc_protocol_list *protocols;
1737 // Objective-C 1.0 extensions (<rdr://4585769>)
1738 const char *ivar_layout;
1739 struct _objc_class_ext *ext;
1740 };
1741
1742 See EmitClassExtension();
1743 */
1744void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001745 DefinedSymbols.insert(ID->getIdentifier());
1746
Chris Lattner8ec03f52008-11-24 03:54:41 +00001747 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001748 // FIXME: Gross
1749 ObjCInterfaceDecl *Interface =
1750 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001751 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001752 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001753 Interface->protocol_begin(),
1754 Interface->protocol_end());
Chris Lattnerb7b58b12009-04-19 06:02:28 +00001755 const llvm::Type *InterfaceTy;
1756 if (Interface->isForwardDecl())
1757 InterfaceTy = llvm::StructType::get(NULL, NULL);
1758 else
1759 InterfaceTy =
Chris Lattner03d9f342009-04-01 06:23:52 +00001760 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001761 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001762 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001763
1764 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001765 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001766 Flags |= eClassFlags_Hidden;
1767
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001768 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1769 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1770 e = ID->instmeth_end(); i != e; ++i) {
1771 // Instance methods should always be defined.
1772 InstanceMethods.push_back(GetMethodConstant(*i));
1773 }
1774 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1775 e = ID->classmeth_end(); i != e; ++i) {
1776 // Class methods should always be defined.
1777 ClassMethods.push_back(GetMethodConstant(*i));
1778 }
1779
1780 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1781 e = ID->propimpl_end(); i != e; ++i) {
1782 ObjCPropertyImplDecl *PID = *i;
1783
1784 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1786
1787 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1788 if (llvm::Constant *C = GetMethodConstant(MD))
1789 InstanceMethods.push_back(C);
1790 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1791 if (llvm::Constant *C = GetMethodConstant(MD))
1792 InstanceMethods.push_back(C);
1793 }
1794 }
1795
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001796 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001797 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001798 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001799 // Record a reference to the super class.
1800 LazySymbols.insert(Super->getIdentifier());
1801
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001802 Values[ 1] =
1803 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1804 ObjCTypes.ClassPtrTy);
1805 } else {
1806 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1807 }
1808 Values[ 2] = GetClassName(ID->getIdentifier());
1809 // Version is always 0.
1810 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1811 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1812 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001813 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001814 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001815 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001816 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001817 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001818 // cache is always NULL.
1819 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1820 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001821 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001822 // Values[10] = BuildIvarLayout(ID, true);
1823 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001824 Values[11] = EmitClassExtension(ID);
1825 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1826 Values);
1827
1828 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001829 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1830 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001831 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001832 DefinedClasses.push_back(GV);
1833}
1834
1835llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1836 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001837 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001838 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001839 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001840 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001841
Daniel Dunbar04d40782009-04-14 06:00:08 +00001842 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001843 Flags |= eClassFlags_Hidden;
1844
1845 std::vector<llvm::Constant*> Values(12);
1846 // The isa for the metaclass is the root of the hierarchy.
1847 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1848 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1849 Root = Super;
1850 Values[ 0] =
1851 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1852 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001853 // The super class for the metaclass is emitted as the name of the
1854 // super class. The runtime fixes this up to point to the
1855 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001856 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1857 Values[ 1] =
1858 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1859 ObjCTypes.ClassPtrTy);
1860 } else {
1861 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1862 }
1863 Values[ 2] = GetClassName(ID->getIdentifier());
1864 // Version is always 0.
1865 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1866 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1867 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001868 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001869 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001870 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001871 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001872 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001873 // cache is always NULL.
1874 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1875 Values[ 9] = Protocols;
1876 // ivar_layout for metaclass is always NULL.
1877 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1878 // The class extension is always unused for metaclasses.
1879 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1880 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1881 Values);
1882
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001883 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001884 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001885
1886 // Check for a forward reference.
1887 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1888 if (GV) {
1889 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1890 "Forward metaclass reference has incorrect type.");
1891 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1892 GV->setInitializer(Init);
1893 } else {
1894 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1895 llvm::GlobalValue::InternalLinkage,
1896 Init, Name,
1897 &CGM.getModule());
1898 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001899 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001900 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001901 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001902
1903 return GV;
1904}
1905
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001906llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001907 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001908
1909 // FIXME: Should we look these up somewhere other than the
1910 // module. Its a bit silly since we only generate these while
1911 // processing an implementation, so exactly one pointer would work
1912 // if know when we entered/exitted an implementation block.
1913
1914 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001915 // Previously, metaclass with internal linkage may have been defined.
1916 // pass 'true' as 2nd argument so it is returned.
1917 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001918 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1919 "Forward metaclass reference has incorrect type.");
1920 return GV;
1921 } else {
1922 // Generate as an external reference to keep a consistent
1923 // module. This will be patched up when we emit the metaclass.
1924 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1925 llvm::GlobalValue::ExternalLinkage,
1926 0,
1927 Name,
1928 &CGM.getModule());
1929 }
1930}
1931
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001932/*
1933 struct objc_class_ext {
1934 uint32_t size;
1935 const char *weak_ivar_layout;
1936 struct _objc_property_list *properties;
1937 };
1938*/
1939llvm::Constant *
1940CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1941 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001942 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001943
1944 std::vector<llvm::Constant*> Values(3);
1945 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001946 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001947 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001948 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001949 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001950 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001951
1952 // Return null if no extension bits are used.
1953 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1954 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1955
1956 llvm::Constant *Init =
1957 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001958 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001959 Init, "__OBJC,__class_ext,regular,no_dead_strip",
1960 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001961}
1962
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001963/// getInterfaceDeclForIvar - Get the interface declaration node where
1964/// this ivar is declared in.
1965/// FIXME. Ideally, this info should be in the ivar node. But currently
1966/// it is not and prevailing wisdom is that ASTs should not have more
1967/// info than is absolutely needed, even though this info reflects the
1968/// source language.
1969///
1970static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1971 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001972 const ObjCIvarDecl *IVD,
1973 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001974 if (!OI)
1975 return 0;
1976 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1977 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1978 E = OI->ivar_end(); I != E; ++I)
1979 if ((*I)->getIdentifier() == IVD->getIdentifier())
1980 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001981 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001982 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
1983 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001984 ObjCPropertyDecl *PDecl = (*I);
1985 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1986 if (IV->getIdentifier() == IVD->getIdentifier())
1987 return OI;
1988 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001989 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001990}
1991
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001992/*
1993 struct objc_ivar {
1994 char *ivar_name;
1995 char *ivar_type;
1996 int ivar_offset;
1997 };
1998
1999 struct objc_ivar_list {
2000 int ivar_count;
2001 struct objc_ivar list[count];
2002 };
2003 */
2004llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002005 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002006 std::vector<llvm::Constant*> Ivars, Ivar(3);
2007
2008 // When emitting the root class GCC emits ivar entries for the
2009 // actual class structure. It is not clear if we need to follow this
2010 // behavior; for now lets try and get away with not doing it. If so,
2011 // the cleanest solution would be to make up an ObjCInterfaceDecl
2012 // for the class.
2013 if (ForClass)
2014 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002015
2016 ObjCInterfaceDecl *OID =
2017 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002018 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002019
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002020 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2021 GetNamedIvarList(OID, OIvars);
2022
2023 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2024 ObjCIvarDecl *IVD = OIvars[i];
2025 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002026 Ivar[0] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00002027 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002028 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
2029 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002030 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002031 }
2032
2033 // Return null for empty list.
2034 if (Ivars.empty())
2035 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2036
2037 std::vector<llvm::Constant*> Values(2);
2038 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2039 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2040 Ivars.size());
2041 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2042 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2043
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002044 llvm::GlobalVariable *GV;
2045 if (ForClass)
2046 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002047 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2048 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002049 else
2050 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2051 + ID->getNameAsString(),
2052 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002053 4, true);
2054 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002055}
2056
2057/*
2058 struct objc_method {
2059 SEL method_name;
2060 char *method_types;
2061 void *method;
2062 };
2063
2064 struct objc_method_list {
2065 struct objc_method_list *obsolete;
2066 int count;
2067 struct objc_method methods_list[count];
2068 };
2069*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002070
2071/// GetMethodConstant - Return a struct objc_method constant for the
2072/// given method if it has been defined. The result is null if the
2073/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002074llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002075 // FIXME: Use DenseMap::lookup
2076 llvm::Function *Fn = MethodDefinitions[MD];
2077 if (!Fn)
2078 return 0;
2079
2080 std::vector<llvm::Constant*> Method(3);
2081 Method[0] =
2082 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2083 ObjCTypes.SelectorPtrTy);
2084 Method[1] = GetMethodVarType(MD);
2085 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2086 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2087}
2088
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002089llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2090 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002091 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002092 // Return null for empty list.
2093 if (Methods.empty())
2094 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2095
2096 std::vector<llvm::Constant*> Values(3);
2097 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2098 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2099 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2100 Methods.size());
2101 Values[2] = llvm::ConstantArray::get(AT, Methods);
2102 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2103
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002104 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105 return llvm::ConstantExpr::getBitCast(GV,
2106 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002107}
2108
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002109llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002110 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002111 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002112 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002113
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002114 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002115 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002116 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002117 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002118 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002119 llvm::GlobalValue::InternalLinkage,
2120 Name,
2121 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002122 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002123
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002124 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002125}
2126
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002127uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002128 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002129 if (!Field->isBitField())
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002130 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2131
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00002132 // FIXME. Must be a better way of getting a bitfield base offset.
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002133 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
2134 // FIXME: The "field no" for bitfields is something completely
2135 // different; it is the offset in multiples of the base type size!
2136 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
2137 const llvm::Type *Ty =
2138 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
2139 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
2140 return (Offset + BFI.Begin) / 8;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002141}
2142
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002143/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002144uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2145 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002146 const FieldDecl *Field) {
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002147 // Is this a c struct?
2148 if (!OI)
2149 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002150 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00002151 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2152 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002153}
2154
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002155llvm::GlobalVariable *
2156CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2157 llvm::Constant *Init,
2158 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002159 unsigned Align,
2160 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002161 const llvm::Type *Ty = Init->getType();
2162 llvm::GlobalVariable *GV =
2163 new llvm::GlobalVariable(Ty, false,
2164 llvm::GlobalValue::InternalLinkage,
2165 Init,
2166 Name,
2167 &CGM.getModule());
2168 if (Section)
2169 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002170 if (Align)
2171 GV->setAlignment(Align);
2172 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002173 UsedGlobals.push_back(GV);
2174 return GV;
2175}
2176
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002177llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002178 // Abuse this interface function as a place to finalize.
2179 FinishModule();
2180
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002181 return NULL;
2182}
2183
Chris Lattner74391b42009-03-22 21:03:39 +00002184llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002185 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002186}
2187
Chris Lattner74391b42009-03-22 21:03:39 +00002188llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002189 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002190}
2191
Chris Lattner74391b42009-03-22 21:03:39 +00002192llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002193 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002194}
2195
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002196/*
2197
2198Objective-C setjmp-longjmp (sjlj) Exception Handling
2199--
2200
2201The basic framework for a @try-catch-finally is as follows:
2202{
2203 objc_exception_data d;
2204 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002205 bool _call_try_exit = true;
2206
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002207 objc_exception_try_enter(&d);
2208 if (!setjmp(d.jmp_buf)) {
2209 ... try body ...
2210 } else {
2211 // exception path
2212 id _caught = objc_exception_extract(&d);
2213
2214 // enter new try scope for handlers
2215 if (!setjmp(d.jmp_buf)) {
2216 ... match exception and execute catch blocks ...
2217
2218 // fell off end, rethrow.
2219 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002220 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002221 } else {
2222 // exception in catch block
2223 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002224 _call_try_exit = false;
2225 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002226 }
2227 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002228 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002229
2230finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002231 if (_call_try_exit)
2232 objc_exception_try_exit(&d);
2233
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002234 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002235 ... dispatch to finally destination ...
2236
2237finally_rethrow:
2238 objc_exception_throw(_rethrow);
2239
2240finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002241}
2242
2243This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002244uses _rethrow to determine if objc_exception_try_exit should be called
2245and if the object should be rethrown. This breaks in the face of
2246throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002247
2248We specialize this framework for a few particular circumstances:
2249
2250 - If there are no catch blocks, then we avoid emitting the second
2251 exception handling context.
2252
2253 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2254 e)) we avoid emitting the code to rethrow an uncaught exception.
2255
2256 - FIXME: If there is no @finally block we can do a few more
2257 simplifications.
2258
2259Rethrows and Jumps-Through-Finally
2260--
2261
2262Support for implicit rethrows and jumping through the finally block is
2263handled by storing the current exception-handling context in
2264ObjCEHStack.
2265
Daniel Dunbar898d5082008-09-30 01:06:03 +00002266In order to implement proper @finally semantics, we support one basic
2267mechanism for jumping through the finally block to an arbitrary
2268destination. Constructs which generate exits from a @try or @catch
2269block use this mechanism to implement the proper semantics by chaining
2270jumps, as necessary.
2271
2272This mechanism works like the one used for indirect goto: we
2273arbitrarily assign an ID to each destination and store the ID for the
2274destination in a variable prior to entering the finally block. At the
2275end of the finally block we simply create a switch to the proper
2276destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002277
2278Code gen for @synchronized(expr) stmt;
2279Effectively generating code for:
2280objc_sync_enter(expr);
2281@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002282*/
2283
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002284void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2285 const Stmt &S) {
2286 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002287 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002288 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002289 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002290 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2291 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2292 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002293
2294 // For @synchronized, call objc_sync_enter(sync.expr). The
2295 // evaluation of the expression must occur before we enter the
2296 // @synchronized. We can safely avoid a temp here because jumps into
2297 // @synchronized are illegal & this will dominate uses.
2298 llvm::Value *SyncArg = 0;
2299 if (!isTry) {
2300 SyncArg =
2301 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2302 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002303 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002304 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002305
2306 // Push an EH context entry, used for handling rethrows and jumps
2307 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002308 CGF.PushCleanupBlock(FinallyBlock);
2309
Anders Carlsson273558f2009-02-07 21:37:21 +00002310 CGF.ObjCEHValueStack.push_back(0);
2311
Daniel Dunbar898d5082008-09-30 01:06:03 +00002312 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002313 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2314 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002315 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2316 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002317 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2318 "_call_try_exit");
2319 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2320
Anders Carlsson80f25672008-09-09 17:59:25 +00002321 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002322 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002323 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2324 "jmpbufarray");
2325 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002326 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002327 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002328
Daniel Dunbar55e87422008-11-11 02:29:29 +00002329 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2330 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002331 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002332 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002333
2334 // Emit the @try block.
2335 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002336 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2337 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002338 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002339
2340 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002341 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002342
2343 // Retrieve the exception object. We may emit multiple blocks but
2344 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002345 llvm::Value *Caught =
2346 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2347 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002348 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002349 if (!isTry)
2350 {
2351 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002352 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002353 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002354 }
2355 else if (const ObjCAtCatchStmt* CatchStmt =
2356 cast<ObjCAtTryStmt>(S).getCatchStmts())
2357 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002358 // Enter a new exception try block (in case a @catch block throws
2359 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002360 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002361
Chris Lattner34b02a12009-04-22 02:26:14 +00002362 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002363 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002364 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002365
Daniel Dunbar55e87422008-11-11 02:29:29 +00002366 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2367 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002368 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002369
2370 CGF.EmitBlock(CatchBlock);
2371
Daniel Dunbar55e40722008-09-27 07:03:52 +00002372 // Handle catch list. As a special case we check if everything is
2373 // matched and avoid generating code for falling off the end if
2374 // so.
2375 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002376 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002377 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002378
Steve Naroff7ba138a2009-03-03 19:52:17 +00002379 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002380 const PointerType *PT = 0;
2381
Anders Carlsson80f25672008-09-09 17:59:25 +00002382 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002383 if (!CatchParam) {
2384 AllMatched = true;
2385 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002386 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002387
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002388 // catch(id e) always matches.
2389 // FIXME: For the time being we also match id<X>; this should
2390 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002391 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002392 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002393 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002394 }
2395
Daniel Dunbar55e40722008-09-27 07:03:52 +00002396 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002397 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002398 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002399 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002400 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002401 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002402
Anders Carlssondde0a942008-09-11 09:15:33 +00002403 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002404 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002405 break;
2406 }
2407
Daniel Dunbar129271a2008-09-27 07:36:24 +00002408 assert(PT && "Unexpected non-pointer type in @catch");
2409 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002410 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002411 assert(ObjCType && "Catch parameter must have Objective-C type!");
2412
2413 // Check if the @catch block matches the exception object.
2414 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2415
Chris Lattner34b02a12009-04-22 02:26:14 +00002416 llvm::Value *Match =
2417 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2418 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002419
Daniel Dunbar55e87422008-11-11 02:29:29 +00002420 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002421
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002422 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002423 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002424
2425 // Emit the @catch block.
2426 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002427 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002428 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002429
2430 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002431 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002432 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002433 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002434
2435 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002436 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002437
2438 CGF.EmitBlock(NextCatchBlock);
2439 }
2440
Daniel Dunbar55e40722008-09-27 07:03:52 +00002441 if (!AllMatched) {
2442 // None of the handlers caught the exception, so store it to be
2443 // rethrown at the end of the @finally block.
2444 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002445 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002446 }
2447
2448 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002449 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002450 CGF.Builder.CreateStore(
2451 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2452 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002453 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002454 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002455 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002456 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002457 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002458 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002459 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002460 }
2461
Daniel Dunbar898d5082008-09-30 01:06:03 +00002462 // Pop the exception-handling stack entry. It is important to do
2463 // this now, because the code in the @finally block is not in this
2464 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002465 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2466
Anders Carlsson273558f2009-02-07 21:37:21 +00002467 CGF.ObjCEHValueStack.pop_back();
2468
Anders Carlsson80f25672008-09-09 17:59:25 +00002469 // Emit the @finally block.
2470 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002471 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2472
2473 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2474
2475 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002476 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002477
2478 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002479 if (isTry) {
2480 if (const ObjCAtFinallyStmt* FinallyStmt =
2481 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2482 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002483 } else {
2484 // Emit objc_sync_exit(expr); as finally's sole statement for
2485 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002486 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002487 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002488
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002489 // Emit the switch block
2490 if (Info.SwitchBlock)
2491 CGF.EmitBlock(Info.SwitchBlock);
2492 if (Info.EndBlock)
2493 CGF.EmitBlock(Info.EndBlock);
2494
Daniel Dunbar898d5082008-09-30 01:06:03 +00002495 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002496 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002497 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002498 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002499
2500 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002501}
2502
2503void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002504 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002505 llvm::Value *ExceptionAsObject;
2506
2507 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2508 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2509 ExceptionAsObject =
2510 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2511 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002512 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002513 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002514 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002515 }
2516
Chris Lattnerbbccd612009-04-22 02:38:11 +00002517 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002518 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002519
2520 // Clear the insertion point to indicate we are in unreachable code.
2521 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002522}
2523
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002524/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002525/// object: objc_read_weak (id *src)
2526///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002527llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002528 llvm::Value *AddrWeakObj)
2529{
Eli Friedman8339b352009-03-07 03:57:15 +00002530 const llvm::Type* DestTy =
2531 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002532 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002533 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002534 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002535 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002536 return read_weak;
2537}
2538
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002539/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2540/// objc_assign_weak (id src, id *dst)
2541///
2542void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2543 llvm::Value *src, llvm::Value *dst)
2544{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002545 const llvm::Type * SrcTy = src->getType();
2546 if (!isa<llvm::PointerType>(SrcTy)) {
2547 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2548 assert(Size <= 8 && "does not support size > 8");
2549 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2550 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002551 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2552 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002553 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2554 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002555 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002556 src, dst, "weakassign");
2557 return;
2558}
2559
Fariborz Jahanian58626502008-11-19 00:59:10 +00002560/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2561/// objc_assign_global (id src, id *dst)
2562///
2563void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2564 llvm::Value *src, llvm::Value *dst)
2565{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002566 const llvm::Type * SrcTy = src->getType();
2567 if (!isa<llvm::PointerType>(SrcTy)) {
2568 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2569 assert(Size <= 8 && "does not support size > 8");
2570 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2571 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002572 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2573 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002574 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2575 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002576 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002577 src, dst, "globalassign");
2578 return;
2579}
2580
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002581/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2582/// objc_assign_ivar (id src, id *dst)
2583///
2584void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2585 llvm::Value *src, llvm::Value *dst)
2586{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002587 const llvm::Type * SrcTy = src->getType();
2588 if (!isa<llvm::PointerType>(SrcTy)) {
2589 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2590 assert(Size <= 8 && "does not support size > 8");
2591 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2592 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002593 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2594 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002595 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2596 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002597 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002598 src, dst, "assignivar");
2599 return;
2600}
2601
Fariborz Jahanian58626502008-11-19 00:59:10 +00002602/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2603/// objc_assign_strongCast (id src, id *dst)
2604///
2605void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2606 llvm::Value *src, llvm::Value *dst)
2607{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002608 const llvm::Type * SrcTy = src->getType();
2609 if (!isa<llvm::PointerType>(SrcTy)) {
2610 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2611 assert(Size <= 8 && "does not support size > 8");
2612 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2613 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002614 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2615 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002616 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2617 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002618 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002619 src, dst, "weakassign");
2620 return;
2621}
2622
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002623/// EmitObjCValueForIvar - Code Gen for ivar reference.
2624///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002625LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2626 QualType ObjectTy,
2627 llvm::Value *BaseValue,
2628 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002629 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002630 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2631 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002632 if (Ivar->isBitField())
2633 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2634 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002635 // TODO: Add a special case for isa (index 0)
2636 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2637 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002638 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002639 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2640 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002641 LValue::SetObjCIvar(LV, true);
2642 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002643}
2644
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002645llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002646 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002647 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002648 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Daniel Dunbar60952f92009-04-20 00:37:55 +00002649 const FieldDecl *Field =
2650 Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002651 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002652 return llvm::ConstantInt::get(
2653 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2654 Offset);
2655}
2656
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002657/* *** Private Interface *** */
2658
2659/// EmitImageInfo - Emit the image info marker used to encode some module
2660/// level information.
2661///
2662/// See: <rdr://4810609&4810587&4810587>
2663/// struct IMAGE_INFO {
2664/// unsigned version;
2665/// unsigned flags;
2666/// };
2667enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002668 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2669 // this implies.
2670 eImageInfo_GarbageCollected = (1 << 1),
2671 eImageInfo_GCOnly = (1 << 2),
2672 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2673
2674 // A flag indicating that the module has no instances of an
2675 // @synthesize of a superclass variable. <rdar://problem/6803242>
2676 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002677};
2678
2679void CGObjCMac::EmitImageInfo() {
2680 unsigned version = 0; // Version is unused?
2681 unsigned flags = 0;
2682
2683 // FIXME: Fix and continue?
2684 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2685 flags |= eImageInfo_GarbageCollected;
2686 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2687 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002688
2689 // We never allow @synthesize of a superclass property.
2690 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002691
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002692 // Emitted as int[2];
2693 llvm::Constant *values[2] = {
2694 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2695 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2696 };
2697 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002698
2699 const char *Section;
2700 if (ObjCABI == 1)
2701 Section = "__OBJC, __image_info,regular";
2702 else
2703 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002704 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002705 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2706 llvm::ConstantArray::get(AT, values, 2),
2707 Section,
2708 0,
2709 true);
2710 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002711}
2712
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002713
2714// struct objc_module {
2715// unsigned long version;
2716// unsigned long size;
2717// const char *name;
2718// Symtab symtab;
2719// };
2720
2721// FIXME: Get from somewhere
2722static const int ModuleVersion = 7;
2723
2724void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002725 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002726
2727 std::vector<llvm::Constant*> Values(4);
2728 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2729 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002730 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002731 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002732 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002733 CreateMetadataVar("\01L_OBJC_MODULES",
2734 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2735 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002736 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002737}
2738
2739llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002740 unsigned NumClasses = DefinedClasses.size();
2741 unsigned NumCategories = DefinedCategories.size();
2742
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002743 // Return null if no symbols were defined.
2744 if (!NumClasses && !NumCategories)
2745 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2746
2747 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002748 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2749 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2750 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2751 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2752
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002753 // The runtime expects exactly the list of defined classes followed
2754 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002755 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002756 for (unsigned i=0; i<NumClasses; i++)
2757 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2758 ObjCTypes.Int8PtrTy);
2759 for (unsigned i=0; i<NumCategories; i++)
2760 Symbols[NumClasses + i] =
2761 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2762 ObjCTypes.Int8PtrTy);
2763
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002764 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002765 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002766 NumClasses + NumCategories),
2767 Symbols);
2768
2769 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2770
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002771 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002772 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2773 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002774 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002775 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2776}
2777
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002778llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002779 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002780 LazySymbols.insert(ID->getIdentifier());
2781
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002782 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2783
2784 if (!Entry) {
2785 llvm::Constant *Casted =
2786 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2787 ObjCTypes.ClassPtrTy);
2788 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002789 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2790 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002791 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002792 }
2793
2794 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002795}
2796
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002797llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002798 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2799
2800 if (!Entry) {
2801 llvm::Constant *Casted =
2802 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2803 ObjCTypes.SelectorPtrTy);
2804 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002805 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2806 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002807 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002808 }
2809
2810 return Builder.CreateLoad(Entry, false, "tmp");
2811}
2812
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002813llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002814 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002815
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002816 if (!Entry)
2817 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2818 llvm::ConstantArray::get(Ident->getName()),
2819 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002820 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002821
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002822 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002823}
2824
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002825/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2826/// interface declaration.
2827const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2828 const ObjCInterfaceDecl *OID) const {
Daniel Dunbar24c89912009-04-21 21:41:56 +00002829 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar2a031922009-04-22 05:08:15 +00002830 QualType T = CGM.getContext().getObjCInterfaceType(OID);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002831 const llvm::StructType *InterfaceTy =
2832 cast<llvm::StructType>(CGM.getTypes().ConvertType(T));
2833 return CGM.getTargetData().getStructLayout(InterfaceTy);
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002834}
2835
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002836/// GetIvarLayoutName - Returns a unique constant for the given
2837/// ivar layout bitmap.
2838llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2839 const ObjCCommonTypesHelper &ObjCTypes) {
2840 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2841}
2842
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002843void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2844 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002845 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002846 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002847 unsigned int BytePos, bool ForStrongLayout,
2848 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002849 bool IsUnion = (RD && RD->isUnion());
2850 uint64_t MaxUnionIvarSize = 0;
2851 uint64_t MaxSkippedUnionIvarSize = 0;
2852 FieldDecl *MaxField = 0;
2853 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002854 FieldDecl *LastFieldBitfield = 0;
2855
Chris Lattnerf1690852009-03-31 08:48:01 +00002856 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002857 if (RecFields.empty())
2858 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002859 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002860 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002861 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2862 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2863
2864 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2865
2866 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002867 FieldDecl *Field = RecFields[i];
2868 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002869 if (!Field->getIdentifier() || Field->isBitField()) {
2870 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002871 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002872 }
2873 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002874 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002875 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002876 if (FQT->isUnionType())
2877 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002878 else
2879 assert(FQT->isRecordType() &&
2880 "only union/record is supported for ivar layout bitmap");
2881
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002882 const RecordType *RT = FQT->getAsRecordType();
2883 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002884 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002885 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2886 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002887 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2888 const llvm::StructLayout *RecLayout =
2889 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2890
2891 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002892 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002893 ForStrongLayout, Index, SkIndex,
2894 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002895 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002896 continue;
2897 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002898
2899 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002900 const ConstantArrayType *CArray =
2901 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002902 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002903 assert(CArray && "only array with know element size is supported");
2904 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002905 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2906 const ConstantArrayType *CArray =
2907 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002908 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002909 FQT = CArray->getElementType();
2910 }
2911
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002912 assert(!FQT->isUnionType() &&
2913 "layout for array of unions not supported");
2914 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002915 int OldIndex = Index;
2916 int OldSkIndex = SkIndex;
2917
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002918 // FIXME - Use a common routine with the above!
2919 const RecordType *RT = FQT->getAsRecordType();
2920 const RecordDecl *RD = RT->getDecl();
2921 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002922 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2923 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002924 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2925 const llvm::StructLayout *RecLayout =
2926 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002927
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002928 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002929 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002930 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002931 ForStrongLayout, Index, SkIndex,
2932 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002933 TmpRecFields.clear();
2934
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002935 // Replicate layout information for each array element. Note that
2936 // one element is already done.
2937 uint64_t ElIx = 1;
2938 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2939 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002940 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002941 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2942 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002943 GC_IVAR gcivar;
2944 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2945 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2946 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002947 }
2948
Chris Lattnerf1690852009-03-31 08:48:01 +00002949 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002950 GC_IVAR skivar;
2951 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2952 skivar.ivar_size = SkipIvars[i].ivar_size;
2953 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002954 }
2955 }
2956 continue;
2957 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002958 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002959 // At this point, we are done with Record/Union and array there of.
2960 // For other arrays we are down to its element type.
2961 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2962 do {
2963 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2964 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2965 break;
2966 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002967 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002968 GCAttr = QualType::Strong;
2969 break;
2970 }
2971 else if (const PointerType *PT = FQT->getAsPointerType()) {
2972 FQT = PT->getPointeeType();
2973 }
2974 else {
2975 break;
2976 }
2977 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002978
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002979 if ((ForStrongLayout && GCAttr == QualType::Strong)
2980 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2981 if (IsUnion)
2982 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002983 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2984 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002985 if (UnionIvarSize > MaxUnionIvarSize)
2986 {
2987 MaxUnionIvarSize = UnionIvarSize;
2988 MaxField = Field;
2989 }
2990 }
2991 else
2992 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002993 GC_IVAR gcivar;
2994 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2995 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2996 WordSizeInBits;
2997 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002998 }
2999 }
3000 else if ((ForStrongLayout &&
3001 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3002 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3003 if (IsUnion)
3004 {
3005 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3006 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3007 {
3008 MaxSkippedUnionIvarSize = UnionIvarSize;
3009 MaxSkippedField = Field;
3010 }
3011 }
3012 else
3013 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003014 GC_IVAR skivar;
3015 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3016 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003017 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003018 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003019 }
3020 }
3021 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003022 if (LastFieldBitfield) {
3023 // Last field was a bitfield. Must update skip info.
3024 GC_IVAR skivar;
3025 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3026 LastFieldBitfield);
3027 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3028 uint64_t BitFieldSize =
3029 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3030 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3031 + ((BitFieldSize % ByteSizeInBits) != 0);
3032 SkipIvars.push_back(skivar); ++SkIndex;
3033 }
3034
Chris Lattnerf1690852009-03-31 08:48:01 +00003035 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003036 GC_IVAR gcivar;
3037 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3038 gcivar.ivar_size = MaxUnionIvarSize;
3039 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003040 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003041
3042 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003043 GC_IVAR skivar;
3044 skivar.ivar_bytepos = BytePos +
3045 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3046 skivar.ivar_size = MaxSkippedUnionIvarSize;
3047 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003048 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003049}
3050
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003051static int
Chris Lattnerf1690852009-03-31 08:48:01 +00003052IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003053{
3054 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
3055 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
3056
3057 if (sa < sb)
3058 return -1;
3059 if (sa > sb)
3060 return 1;
3061 return 0;
3062}
3063
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003064/// BuildIvarLayout - Builds ivar layout bitmap for the class
3065/// implementation for the __strong or __weak case.
3066/// The layout map displays which words in ivar list must be skipped
3067/// and which must be scanned by GC (see below). String is built of bytes.
3068/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3069/// of words to skip and right nibble is count of words to scan. So, each
3070/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3071/// represented by a 0x00 byte which also ends the string.
3072/// 1. when ForStrongLayout is true, following ivars are scanned:
3073/// - id, Class
3074/// - object *
3075/// - __strong anything
3076///
3077/// 2. When ForStrongLayout is false, following ivars are scanned:
3078/// - __weak anything
3079///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003080llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003081 const ObjCImplementationDecl *OMD,
3082 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003083 int Index = -1;
3084 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003085 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003086 int SkipScan;
3087 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003088 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3089 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3090 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003091
Chris Lattnerf1690852009-03-31 08:48:01 +00003092 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003093 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003094 CGM.getContext().CollectObjCIvars(OI, RecFields);
3095 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003096 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003097
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003098 SkipIvars.clear();
3099 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003100
3101 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00003102 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3103 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003104 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003105 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003106
3107 // Sort on byte position in case we encounterred a union nested in
3108 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003109 if (hasUnion && !IvarsInfo.empty())
3110 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3111 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003112 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3113
3114 // Build the string of skip/scan nibbles
3115 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003116 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003117 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003118 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003119 if (IvarsInfo[0].ivar_bytepos == 0) {
3120 WordsToSkip = 0;
3121 WordsToScan = IvarsInfo[0].ivar_size;
3122 }
3123 else {
3124 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3125 WordsToScan = IvarsInfo[0].ivar_size;
3126 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003127 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003128 {
3129 unsigned int TailPrevGCObjC =
3130 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3131 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3132 {
3133 // consecutive 'scanned' object pointers.
3134 WordsToScan += IvarsInfo[i].ivar_size;
3135 }
3136 else
3137 {
3138 // Skip over 'gc'able object pointer which lay over each other.
3139 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3140 continue;
3141 // Must skip over 1 or more words. We save current skip/scan values
3142 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003143 SKIP_SCAN SkScan;
3144 SkScan.skip = WordsToSkip;
3145 SkScan.scan = WordsToScan;
3146 SkipScanIvars.push_back(SkScan); ++SkipScan;
3147
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003148 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003149 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3150 SkScan.scan = 0;
3151 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003152 WordsToSkip = 0;
3153 WordsToScan = IvarsInfo[i].ivar_size;
3154 }
3155 }
3156 if (WordsToScan > 0)
3157 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003158 SKIP_SCAN SkScan;
3159 SkScan.skip = WordsToSkip;
3160 SkScan.scan = WordsToScan;
3161 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003162 }
3163
3164 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003165 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003166 {
3167 int LastByteSkipped =
3168 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3169 int LastByteScanned =
3170 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3171 BytesSkipped = (LastByteSkipped > LastByteScanned);
3172 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3173 if (BytesSkipped)
3174 {
3175 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003176 SKIP_SCAN SkScan;
3177 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3178 SkScan.scan = 0;
3179 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003180 }
3181 }
3182 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3183 // as 0xMN.
3184 for (int i = 0; i <= SkipScan; i++)
3185 {
3186 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3187 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3188 // 0xM0 followed by 0x0N detected.
3189 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3190 for (int j = i+1; j < SkipScan; j++)
3191 SkipScanIvars[j] = SkipScanIvars[j+1];
3192 --SkipScan;
3193 }
3194 }
3195
3196 // Generate the string.
3197 std::string BitMap;
3198 for (int i = 0; i <= SkipScan; i++)
3199 {
3200 unsigned char byte;
3201 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3202 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3203 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3204 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3205
3206 if (skip_small > 0 || skip_big > 0)
3207 BytesSkipped = true;
3208 // first skip big.
3209 for (unsigned int ix = 0; ix < skip_big; ix++)
3210 BitMap += (unsigned char)(0xf0);
3211
3212 // next (skip small, scan)
3213 if (skip_small)
3214 {
3215 byte = skip_small << 4;
3216 if (scan_big > 0)
3217 {
3218 byte |= 0xf;
3219 --scan_big;
3220 }
3221 else if (scan_small)
3222 {
3223 byte |= scan_small;
3224 scan_small = 0;
3225 }
3226 BitMap += byte;
3227 }
3228 // next scan big
3229 for (unsigned int ix = 0; ix < scan_big; ix++)
3230 BitMap += (unsigned char)(0x0f);
3231 // last scan small
3232 if (scan_small)
3233 {
3234 byte = scan_small;
3235 BitMap += byte;
3236 }
3237 }
3238 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003239 unsigned char zero = 0;
3240 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003241
3242 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3243 printf("\n%s ivar layout for class '%s': ",
3244 ForStrongLayout ? "strong" : "weak",
3245 OMD->getClassInterface()->getNameAsCString());
3246 const unsigned char *s = (unsigned char*)BitMap.c_str();
3247 for (unsigned i = 0; i < BitMap.size(); i++)
3248 if (!(s[i] & 0xf0))
3249 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3250 else
3251 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3252 printf("\n");
3253 }
3254
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003255 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3256 // final layout.
3257 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003258 return llvm::Constant::getNullValue(PtrTy);
3259 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3260 llvm::ConstantArray::get(BitMap.c_str()),
3261 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003262 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003263 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003264}
3265
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003266llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003267 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3268
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003269 // FIXME: Avoid std::string copying.
3270 if (!Entry)
3271 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3272 llvm::ConstantArray::get(Sel.getAsString()),
3273 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003274 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003275
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003276 return getConstantGEP(Entry, 0, 0);
3277}
3278
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003279// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003280llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003281 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3282}
3283
3284// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003285llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003286 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3287}
3288
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003289llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003290 std::string TypeStr;
3291 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3292
3293 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003294
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003295 if (!Entry)
3296 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3297 llvm::ConstantArray::get(TypeStr),
3298 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003299 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003300
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003301 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003302}
3303
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003304llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003305 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003306 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3307 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003308
3309 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3310
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003311 if (!Entry)
3312 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3313 llvm::ConstantArray::get(TypeStr),
3314 "__TEXT,__cstring,cstring_literals",
3315 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003316
3317 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003318}
3319
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003320// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003321llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003322 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3323
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003324 if (!Entry)
3325 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3326 llvm::ConstantArray::get(Ident->getName()),
3327 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003328 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003329
3330 return getConstantGEP(Entry, 0, 0);
3331}
3332
3333// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003334// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003335llvm::Constant *
3336 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3337 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003338 std::string TypeStr;
3339 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003340 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3341}
3342
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003343void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3344 const ObjCContainerDecl *CD,
3345 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003346 NameOut = '\01';
3347 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003348 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003349 assert (CD && "Missing container decl in GetNameForMethod");
3350 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003351 if (const ObjCCategoryImplDecl *CID =
3352 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3353 NameOut += '(';
3354 NameOut += CID->getNameAsString();
3355 NameOut+= ')';
3356 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003357 NameOut += ' ';
3358 NameOut += D->getSelector().getAsString();
3359 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003360}
3361
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003362void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003363 EmitModuleInfo();
3364
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003365 // Emit the dummy bodies for any protocols which were referenced but
3366 // never defined.
3367 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3368 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3369 if (i->second->hasInitializer())
3370 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003371
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003372 std::vector<llvm::Constant*> Values(5);
3373 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3374 Values[1] = GetClassName(i->first);
3375 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3376 Values[3] = Values[4] =
3377 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3378 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3379 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3380 Values));
3381 }
3382
3383 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003384 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003385 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003386 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003387 }
3388
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003389 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003390 llvm::GlobalValue *GV =
3391 new llvm::GlobalVariable(AT, false,
3392 llvm::GlobalValue::AppendingLinkage,
3393 llvm::ConstantArray::get(AT, Used),
3394 "llvm.used",
3395 &CGM.getModule());
3396
3397 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003398
3399 // Add assembler directives to add lazy undefined symbol references
3400 // for classes which are referenced but not defined. This is
3401 // important for correct linker interaction.
3402
3403 // FIXME: Uh, this isn't particularly portable.
3404 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003405
3406 if (!CGM.getModule().getModuleInlineAsm().empty())
3407 s << "\n";
3408
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003409 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3410 e = LazySymbols.end(); i != e; ++i) {
3411 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3412 }
3413 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3414 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003415 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003416 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3417 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003418
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003419 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003420}
3421
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003422CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003423 : CGObjCCommonMac(cgm),
3424 ObjCTypes(cgm)
3425{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003426 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003427 ObjCABI = 2;
3428}
3429
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003430/* *** */
3431
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003432ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3433: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003434{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003435 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3436 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003437
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003438 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003439 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003440 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003441 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003442 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3443
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003444 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003445 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003446 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003447
3448 // FIXME: It would be nice to unify this with the opaque type, so
3449 // that the IR comes out a bit cleaner.
3450 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3451 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003452
3453 // I'm not sure I like this. The implicit coordination is a bit
3454 // gross. We should solve this in a reasonable fashion because this
3455 // is a pretty common task (match some runtime data structure with
3456 // an LLVM data structure).
3457
3458 // FIXME: This is leaked.
3459 // FIXME: Merge with rewriter code?
3460
3461 // struct _objc_super {
3462 // id self;
3463 // Class cls;
3464 // }
3465 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3466 SourceLocation(),
3467 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003468 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3469 Ctx.getObjCIdType(), 0, false));
3470 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3471 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003472 RD->completeDefinition(Ctx);
3473
3474 SuperCTy = Ctx.getTagDeclType(RD);
3475 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3476
3477 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003478 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3479
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003480 // struct _prop_t {
3481 // char *name;
3482 // char *attributes;
3483 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003484 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003485 CGM.getModule().addTypeName("struct._prop_t",
3486 PropertyTy);
3487
3488 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003489 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003490 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003491 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003492 // }
3493 PropertyListTy = llvm::StructType::get(IntTy,
3494 IntTy,
3495 llvm::ArrayType::get(PropertyTy, 0),
3496 NULL);
3497 CGM.getModule().addTypeName("struct._prop_list_t",
3498 PropertyListTy);
3499 // struct _prop_list_t *
3500 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3501
3502 // struct _objc_method {
3503 // SEL _cmd;
3504 // char *method_type;
3505 // char *_imp;
3506 // }
3507 MethodTy = llvm::StructType::get(SelectorPtrTy,
3508 Int8PtrTy,
3509 Int8PtrTy,
3510 NULL);
3511 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003512
3513 // struct _objc_cache *
3514 CacheTy = llvm::OpaqueType::get();
3515 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3516 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003517}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003518
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003519ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3520 : ObjCCommonTypesHelper(cgm)
3521{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003522 // struct _objc_method_description {
3523 // SEL name;
3524 // char *types;
3525 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003526 MethodDescriptionTy =
3527 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003528 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003529 NULL);
3530 CGM.getModule().addTypeName("struct._objc_method_description",
3531 MethodDescriptionTy);
3532
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003533 // struct _objc_method_description_list {
3534 // int count;
3535 // struct _objc_method_description[1];
3536 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003537 MethodDescriptionListTy =
3538 llvm::StructType::get(IntTy,
3539 llvm::ArrayType::get(MethodDescriptionTy, 0),
3540 NULL);
3541 CGM.getModule().addTypeName("struct._objc_method_description_list",
3542 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003543
3544 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003545 MethodDescriptionListPtrTy =
3546 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3547
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003548 // Protocol description structures
3549
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003550 // struct _objc_protocol_extension {
3551 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3552 // struct _objc_method_description_list *optional_instance_methods;
3553 // struct _objc_method_description_list *optional_class_methods;
3554 // struct _objc_property_list *instance_properties;
3555 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003556 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003557 llvm::StructType::get(IntTy,
3558 MethodDescriptionListPtrTy,
3559 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003560 PropertyListPtrTy,
3561 NULL);
3562 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3563 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003564
3565 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003566 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3567
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003568 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003569
3570 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3571 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3572
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003573 const llvm::Type *T =
3574 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3575 LongTy,
3576 llvm::ArrayType::get(ProtocolTyHolder, 0),
3577 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003578 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3579
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003580 // struct _objc_protocol {
3581 // struct _objc_protocol_extension *isa;
3582 // char *protocol_name;
3583 // struct _objc_protocol **_objc_protocol_list;
3584 // struct _objc_method_description_list *instance_methods;
3585 // struct _objc_method_description_list *class_methods;
3586 // }
3587 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003588 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003589 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3590 MethodDescriptionListPtrTy,
3591 MethodDescriptionListPtrTy,
3592 NULL);
3593 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3594
3595 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3596 CGM.getModule().addTypeName("struct._objc_protocol_list",
3597 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003598 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003599 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3600
3601 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003602 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003603 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003604
3605 // Class description structures
3606
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003607 // struct _objc_ivar {
3608 // char *ivar_name;
3609 // char *ivar_type;
3610 // int ivar_offset;
3611 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003612 IvarTy = llvm::StructType::get(Int8PtrTy,
3613 Int8PtrTy,
3614 IntTy,
3615 NULL);
3616 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3617
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003618 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003619 IvarListTy = llvm::OpaqueType::get();
3620 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3621 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3622
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003623 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003624 MethodListTy = llvm::OpaqueType::get();
3625 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3626 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3627
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003628 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003629 ClassExtensionTy =
3630 llvm::StructType::get(IntTy,
3631 Int8PtrTy,
3632 PropertyListPtrTy,
3633 NULL);
3634 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3635 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3636
3637 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3638
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003639 // struct _objc_class {
3640 // Class isa;
3641 // Class super_class;
3642 // char *name;
3643 // long version;
3644 // long info;
3645 // long instance_size;
3646 // struct _objc_ivar_list *ivars;
3647 // struct _objc_method_list *methods;
3648 // struct _objc_cache *cache;
3649 // struct _objc_protocol_list *protocols;
3650 // char *ivar_layout;
3651 // struct _objc_class_ext *ext;
3652 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003653 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3654 llvm::PointerType::getUnqual(ClassTyHolder),
3655 Int8PtrTy,
3656 LongTy,
3657 LongTy,
3658 LongTy,
3659 IvarListPtrTy,
3660 MethodListPtrTy,
3661 CachePtrTy,
3662 ProtocolListPtrTy,
3663 Int8PtrTy,
3664 ClassExtensionPtrTy,
3665 NULL);
3666 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3667
3668 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3669 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3670 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3671
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003672 // struct _objc_category {
3673 // char *category_name;
3674 // char *class_name;
3675 // struct _objc_method_list *instance_method;
3676 // struct _objc_method_list *class_method;
3677 // uint32_t size; // sizeof(struct _objc_category)
3678 // struct _objc_property_list *instance_properties;// category's @property
3679 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003680 CategoryTy = llvm::StructType::get(Int8PtrTy,
3681 Int8PtrTy,
3682 MethodListPtrTy,
3683 MethodListPtrTy,
3684 ProtocolListPtrTy,
3685 IntTy,
3686 PropertyListPtrTy,
3687 NULL);
3688 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3689
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003690 // Global metadata structures
3691
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003692 // struct _objc_symtab {
3693 // long sel_ref_cnt;
3694 // SEL *refs;
3695 // short cls_def_cnt;
3696 // short cat_def_cnt;
3697 // char *defs[cls_def_cnt + cat_def_cnt];
3698 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003699 SymtabTy = llvm::StructType::get(LongTy,
3700 SelectorPtrTy,
3701 ShortTy,
3702 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003703 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003704 NULL);
3705 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3706 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3707
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003708 // struct _objc_module {
3709 // long version;
3710 // long size; // sizeof(struct _objc_module)
3711 // char *name;
3712 // struct _objc_symtab* symtab;
3713 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003714 ModuleTy =
3715 llvm::StructType::get(LongTy,
3716 LongTy,
3717 Int8PtrTy,
3718 SymtabPtrTy,
3719 NULL);
3720 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003721
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003722
Anders Carlsson124526b2008-09-09 10:10:21 +00003723 // FIXME: This is the size of the setjmp buffer and should be
3724 // target specific. 18 is what's used on 32-bit X86.
3725 uint64_t SetJmpBufferSize = 18;
3726
3727 // Exceptions
3728 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003729 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003730
3731 ExceptionDataTy =
3732 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3733 SetJmpBufferSize),
3734 StackPtrTy, NULL);
3735 CGM.getModule().addTypeName("struct._objc_exception_data",
3736 ExceptionDataTy);
3737
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003738}
3739
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003740ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003741: ObjCCommonTypesHelper(cgm)
3742{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003743 // struct _method_list_t {
3744 // uint32_t entsize; // sizeof(struct _objc_method)
3745 // uint32_t method_count;
3746 // struct _objc_method method_list[method_count];
3747 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003748 MethodListnfABITy = llvm::StructType::get(IntTy,
3749 IntTy,
3750 llvm::ArrayType::get(MethodTy, 0),
3751 NULL);
3752 CGM.getModule().addTypeName("struct.__method_list_t",
3753 MethodListnfABITy);
3754 // struct method_list_t *
3755 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003756
3757 // struct _protocol_t {
3758 // id isa; // NULL
3759 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003760 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003761 // const struct method_list_t * const instance_methods;
3762 // const struct method_list_t * const class_methods;
3763 // const struct method_list_t *optionalInstanceMethods;
3764 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003765 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003766 // const uint32_t size; // sizeof(struct _protocol_t)
3767 // const uint32_t flags; // = 0
3768 // }
3769
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003770 // Holder for struct _protocol_list_t *
3771 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3772
3773 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3774 Int8PtrTy,
3775 llvm::PointerType::getUnqual(
3776 ProtocolListTyHolder),
3777 MethodListnfABIPtrTy,
3778 MethodListnfABIPtrTy,
3779 MethodListnfABIPtrTy,
3780 MethodListnfABIPtrTy,
3781 PropertyListPtrTy,
3782 IntTy,
3783 IntTy,
3784 NULL);
3785 CGM.getModule().addTypeName("struct._protocol_t",
3786 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003787
3788 // struct _protocol_t*
3789 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003790
Fariborz Jahanianda320092009-01-29 19:24:30 +00003791 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003792 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003793 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003794 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003795 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3796 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003797 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003798 NULL);
3799 CGM.getModule().addTypeName("struct._objc_protocol_list",
3800 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003801 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3802 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003803
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003804 // struct _objc_protocol_list*
3805 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003806
3807 // struct _ivar_t {
3808 // unsigned long int *offset; // pointer to ivar offset location
3809 // char *name;
3810 // char *type;
3811 // uint32_t alignment;
3812 // uint32_t size;
3813 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003814 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3815 Int8PtrTy,
3816 Int8PtrTy,
3817 IntTy,
3818 IntTy,
3819 NULL);
3820 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3821
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003822 // struct _ivar_list_t {
3823 // uint32 entsize; // sizeof(struct _ivar_t)
3824 // uint32 count;
3825 // struct _iver_t list[count];
3826 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003827 IvarListnfABITy = llvm::StructType::get(IntTy,
3828 IntTy,
3829 llvm::ArrayType::get(
3830 IvarnfABITy, 0),
3831 NULL);
3832 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3833
3834 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003835
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003836 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003837 // uint32_t const flags;
3838 // uint32_t const instanceStart;
3839 // uint32_t const instanceSize;
3840 // uint32_t const reserved; // only when building for 64bit targets
3841 // const uint8_t * const ivarLayout;
3842 // const char *const name;
3843 // const struct _method_list_t * const baseMethods;
3844 // const struct _objc_protocol_list *const baseProtocols;
3845 // const struct _ivar_list_t *const ivars;
3846 // const uint8_t * const weakIvarLayout;
3847 // const struct _prop_list_t * const properties;
3848 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003849
3850 // FIXME. Add 'reserved' field in 64bit abi mode!
3851 ClassRonfABITy = llvm::StructType::get(IntTy,
3852 IntTy,
3853 IntTy,
3854 Int8PtrTy,
3855 Int8PtrTy,
3856 MethodListnfABIPtrTy,
3857 ProtocolListnfABIPtrTy,
3858 IvarListnfABIPtrTy,
3859 Int8PtrTy,
3860 PropertyListPtrTy,
3861 NULL);
3862 CGM.getModule().addTypeName("struct._class_ro_t",
3863 ClassRonfABITy);
3864
3865 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3866 std::vector<const llvm::Type*> Params;
3867 Params.push_back(ObjectPtrTy);
3868 Params.push_back(SelectorPtrTy);
3869 ImpnfABITy = llvm::PointerType::getUnqual(
3870 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3871
3872 // struct _class_t {
3873 // struct _class_t *isa;
3874 // struct _class_t * const superclass;
3875 // void *cache;
3876 // IMP *vtable;
3877 // struct class_ro_t *ro;
3878 // }
3879
3880 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3881 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3882 llvm::PointerType::getUnqual(ClassTyHolder),
3883 CachePtrTy,
3884 llvm::PointerType::getUnqual(ImpnfABITy),
3885 llvm::PointerType::getUnqual(
3886 ClassRonfABITy),
3887 NULL);
3888 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3889
3890 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3891 ClassnfABITy);
3892
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003893 // LLVM for struct _class_t *
3894 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3895
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003896 // struct _category_t {
3897 // const char * const name;
3898 // struct _class_t *const cls;
3899 // const struct _method_list_t * const instance_methods;
3900 // const struct _method_list_t * const class_methods;
3901 // const struct _protocol_list_t * const protocols;
3902 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003903 // }
3904 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003905 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003906 MethodListnfABIPtrTy,
3907 MethodListnfABIPtrTy,
3908 ProtocolListnfABIPtrTy,
3909 PropertyListPtrTy,
3910 NULL);
3911 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003912
3913 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003914 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3915 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003916
3917 // MessageRefTy - LLVM for:
3918 // struct _message_ref_t {
3919 // IMP messenger;
3920 // SEL name;
3921 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003922
3923 // First the clang type for struct _message_ref_t
3924 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3925 SourceLocation(),
3926 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003927 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3928 Ctx.VoidPtrTy, 0, false));
3929 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3930 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003931 RD->completeDefinition(Ctx);
3932
3933 MessageRefCTy = Ctx.getTagDeclType(RD);
3934 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3935 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003936
3937 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3938 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3939
3940 // SuperMessageRefTy - LLVM for:
3941 // struct _super_message_ref_t {
3942 // SUPER_IMP messenger;
3943 // SEL name;
3944 // };
3945 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3946 SelectorPtrTy,
3947 NULL);
3948 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3949
3950 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3951 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3952
Daniel Dunbare588b992009-03-01 04:46:24 +00003953
3954 // struct objc_typeinfo {
3955 // const void** vtable; // objc_ehtype_vtable + 2
3956 // const char* name; // c++ typeinfo string
3957 // Class cls;
3958 // };
3959 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3960 Int8PtrTy,
3961 ClassnfABIPtrTy,
3962 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003963 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003964 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003965}
3966
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003967llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3968 FinishNonFragileABIModule();
3969
3970 return NULL;
3971}
3972
3973void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3974 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003975
3976 // Build list of all implemented classe addresses in array
3977 // L_OBJC_LABEL_CLASS_$.
3978 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3979 // list of 'nonlazy' implementations (defined as those with a +load{}
3980 // method!!).
3981 unsigned NumClasses = DefinedClasses.size();
3982 if (NumClasses) {
3983 std::vector<llvm::Constant*> Symbols(NumClasses);
3984 for (unsigned i=0; i<NumClasses; i++)
3985 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3986 ObjCTypes.Int8PtrTy);
3987 llvm::Constant* Init =
3988 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3989 NumClasses),
3990 Symbols);
3991
3992 llvm::GlobalVariable *GV =
3993 new llvm::GlobalVariable(Init->getType(), false,
3994 llvm::GlobalValue::InternalLinkage,
3995 Init,
3996 "\01L_OBJC_LABEL_CLASS_$",
3997 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003998 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003999 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4000 UsedGlobals.push_back(GV);
4001 }
4002
4003 // Build list of all implemented category addresses in array
4004 // L_OBJC_LABEL_CATEGORY_$.
4005 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4006 // list of 'nonlazy' category implementations (defined as those with a +load{}
4007 // method!!).
4008 unsigned NumCategory = DefinedCategories.size();
4009 if (NumCategory) {
4010 std::vector<llvm::Constant*> Symbols(NumCategory);
4011 for (unsigned i=0; i<NumCategory; i++)
4012 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4013 ObjCTypes.Int8PtrTy);
4014 llvm::Constant* Init =
4015 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4016 NumCategory),
4017 Symbols);
4018
4019 llvm::GlobalVariable *GV =
4020 new llvm::GlobalVariable(Init->getType(), false,
4021 llvm::GlobalValue::InternalLinkage,
4022 Init,
4023 "\01L_OBJC_LABEL_CATEGORY_$",
4024 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004025 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004026 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4027 UsedGlobals.push_back(GV);
4028 }
4029
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004030 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4031 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4032 std::vector<llvm::Constant*> Values(2);
4033 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004034 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004035 // FIXME: Fix and continue?
4036 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4037 flags |= eImageInfo_GarbageCollected;
4038 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4039 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004040 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004041 llvm::Constant* Init = llvm::ConstantArray::get(
4042 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4043 Values);
4044 llvm::GlobalVariable *IMGV =
4045 new llvm::GlobalVariable(Init->getType(), false,
4046 llvm::GlobalValue::InternalLinkage,
4047 Init,
4048 "\01L_OBJC_IMAGE_INFO",
4049 &CGM.getModule());
4050 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4051 UsedGlobals.push_back(IMGV);
4052
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004053 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004054
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004055 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4056 e = UsedGlobals.end(); i != e; ++i) {
4057 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4058 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004059
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004060 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4061 llvm::GlobalValue *GV =
4062 new llvm::GlobalVariable(AT, false,
4063 llvm::GlobalValue::AppendingLinkage,
4064 llvm::ConstantArray::get(AT, Used),
4065 "llvm.used",
4066 &CGM.getModule());
4067
4068 GV->setSection("llvm.metadata");
4069
4070}
4071
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004072// Metadata flags
4073enum MetaDataDlags {
4074 CLS = 0x0,
4075 CLS_META = 0x1,
4076 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004077 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004078 CLS_EXCEPTION = 0x20
4079};
4080/// BuildClassRoTInitializer - generate meta-data for:
4081/// struct _class_ro_t {
4082/// uint32_t const flags;
4083/// uint32_t const instanceStart;
4084/// uint32_t const instanceSize;
4085/// uint32_t const reserved; // only when building for 64bit targets
4086/// const uint8_t * const ivarLayout;
4087/// const char *const name;
4088/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004089/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004090/// const struct _ivar_list_t *const ivars;
4091/// const uint8_t * const weakIvarLayout;
4092/// const struct _prop_list_t * const properties;
4093/// }
4094///
4095llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4096 unsigned flags,
4097 unsigned InstanceStart,
4098 unsigned InstanceSize,
4099 const ObjCImplementationDecl *ID) {
4100 std::string ClassName = ID->getNameAsString();
4101 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4102 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4103 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4104 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4105 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004106 // FIXME. ivarLayout is currently null!
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004107 // Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4108 // : BuildIvarLayout(ID, true);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004109 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004110 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004111 // const struct _method_list_t * const baseMethods;
4112 std::vector<llvm::Constant*> Methods;
4113 std::string MethodListName("\01l_OBJC_$_");
4114 if (flags & CLS_META) {
4115 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4116 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4117 e = ID->classmeth_end(); i != e; ++i) {
4118 // Class methods should always be defined.
4119 Methods.push_back(GetMethodConstant(*i));
4120 }
4121 } else {
4122 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4123 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4124 e = ID->instmeth_end(); i != e; ++i) {
4125 // Instance methods should always be defined.
4126 Methods.push_back(GetMethodConstant(*i));
4127 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004128 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4129 e = ID->propimpl_end(); i != e; ++i) {
4130 ObjCPropertyImplDecl *PID = *i;
4131
4132 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4133 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4134
4135 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4136 if (llvm::Constant *C = GetMethodConstant(MD))
4137 Methods.push_back(C);
4138 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4139 if (llvm::Constant *C = GetMethodConstant(MD))
4140 Methods.push_back(C);
4141 }
4142 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004143 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004144 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004145 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004146
4147 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4148 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4149 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4150 + OID->getNameAsString(),
4151 OID->protocol_begin(),
4152 OID->protocol_end());
4153
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004154 if (flags & CLS_META)
4155 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4156 else
4157 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004158 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00004159 // Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4160 // : BuildIvarLayout(ID, false);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004161 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004162 if (flags & CLS_META)
4163 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4164 else
4165 Values[ 9] =
4166 EmitPropertyList(
4167 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4168 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004169 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4170 Values);
4171 llvm::GlobalVariable *CLASS_RO_GV =
4172 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4173 llvm::GlobalValue::InternalLinkage,
4174 Init,
4175 (flags & CLS_META) ?
4176 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4177 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4178 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004179 CLASS_RO_GV->setAlignment(
4180 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004181 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004182 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004183
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004184}
4185
4186/// BuildClassMetaData - This routine defines that to-level meta-data
4187/// for the given ClassName for:
4188/// struct _class_t {
4189/// struct _class_t *isa;
4190/// struct _class_t * const superclass;
4191/// void *cache;
4192/// IMP *vtable;
4193/// struct class_ro_t *ro;
4194/// }
4195///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004196llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4197 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004198 llvm::Constant *IsAGV,
4199 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004200 llvm::Constant *ClassRoGV,
4201 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004202 std::vector<llvm::Constant*> Values(5);
4203 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004204 Values[1] = SuperClassGV
4205 ? SuperClassGV
4206 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004207 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4208 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4209 Values[4] = ClassRoGV; // &CLASS_RO_GV
4210 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4211 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004212 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4213 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004214 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004215 GV->setAlignment(
4216 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004217 if (HiddenVisibility)
4218 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004219 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004220}
4221
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004222/// countInheritedIvars - count number of ivars in class and its super class(s)
4223///
4224static int countInheritedIvars(const ObjCInterfaceDecl *OI,
4225 ASTContext &Context) {
4226 int count = 0;
4227 if (!OI)
4228 return 0;
4229 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
4230 if (SuperClass)
4231 count += countInheritedIvars(SuperClass, Context);
4232 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
4233 E = OI->ivar_end(); I != E; ++I)
4234 ++count;
4235 // look into properties.
4236 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
4237 E = OI->prop_end(Context); I != E; ++I) {
4238 if ((*I)->getPropertyIvarDecl())
4239 ++count;
4240 }
4241 return count;
4242}
4243
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004244void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4245 uint32_t &InstanceStart,
4246 uint32_t &InstanceSize) {
Daniel Dunbar24c89912009-04-21 21:41:56 +00004247 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004248 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
4249
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004250 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(),
4251 CGM.getContext());
Daniel Dunbar6ec07162009-04-20 07:18:49 +00004252 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004253 RecordDecl::field_iterator firstField = RD->field_begin(CGM.getContext());
4254 RecordDecl::field_iterator lastField = RD->field_end(CGM.getContext());
4255 while (countSuperClassIvars-- > 0) {
4256 lastField = firstField;
4257 ++firstField;
4258 }
4259
4260 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()),
4261 ifield = firstField; ifield != e; ++ifield)
4262 lastField = ifield;
4263
4264 InstanceStart = InstanceSize = 0;
4265 if (lastField != RD->field_end(CGM.getContext())) {
4266 FieldDecl *Field = *lastField;
4267 const llvm::Type *FieldTy =
4268 CGM.getTypes().ConvertTypeForMem(Field->getType());
4269 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4270 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
4271 if (firstField == RD->field_end(CGM.getContext()))
4272 InstanceStart = InstanceSize;
4273 else {
4274 Field = *firstField;
4275 InstanceStart = GetIvarBaseOffset(Layout, Field);
4276 }
4277 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004278}
4279
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004280void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4281 std::string ClassName = ID->getNameAsString();
4282 if (!ObjCEmptyCacheVar) {
4283 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004284 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004285 false,
4286 llvm::GlobalValue::ExternalLinkage,
4287 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004288 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004289 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004290
4291 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004292 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004293 false,
4294 llvm::GlobalValue::ExternalLinkage,
4295 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004296 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004297 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004298 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004299 assert(ID->getClassInterface() &&
4300 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004301 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004302 uint32_t InstanceStart =
4303 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4304 uint32_t InstanceSize = InstanceStart;
4305 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004306 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4307 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004308
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004309 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004310
Daniel Dunbar04d40782009-04-14 06:00:08 +00004311 bool classIsHidden =
4312 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004313 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004314 flags |= OBJC2_CLS_HIDDEN;
4315 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004316 // class is root
4317 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004318 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004319 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004320 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004321 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004322 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4323 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4324 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004325 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004326 // work on super class metadata symbol.
4327 std::string SuperClassName =
4328 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004329 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004330 }
4331 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4332 InstanceStart,
4333 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004334 std::string TClassName = ObjCMetaClassName + ClassName;
4335 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004336 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4337 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004338
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004339 // Metadata for the class
4340 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004341 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004342 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004343
4344 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4345 flags |= CLS_EXCEPTION;
4346
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004347 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004348 flags |= CLS_ROOT;
4349 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004350 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004351 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004352 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004353 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004354 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004355 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004356 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004357 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004358 InstanceStart,
4359 InstanceSize,
4360 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004361
4362 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004363 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004364 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4365 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004366 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004367
4368 // Force the definition of the EHType if necessary.
4369 if (flags & CLS_EXCEPTION)
4370 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004371}
4372
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004373/// GenerateProtocolRef - This routine is called to generate code for
4374/// a protocol reference expression; as in:
4375/// @code
4376/// @protocol(Proto1);
4377/// @endcode
4378/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4379/// which will hold address of the protocol meta-data.
4380///
4381llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4382 const ObjCProtocolDecl *PD) {
4383
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004384 // This routine is called for @protocol only. So, we must build definition
4385 // of protocol's meta-data (not a reference to it!)
4386 //
4387 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004388 ObjCTypes.ExternalProtocolPtrTy);
4389
4390 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4391 ProtocolName += PD->getNameAsCString();
4392
4393 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4394 if (PTGV)
4395 return Builder.CreateLoad(PTGV, false, "tmp");
4396 PTGV = new llvm::GlobalVariable(
4397 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004398 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004399 Init,
4400 ProtocolName,
4401 &CGM.getModule());
4402 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4403 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4404 UsedGlobals.push_back(PTGV);
4405 return Builder.CreateLoad(PTGV, false, "tmp");
4406}
4407
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004408/// GenerateCategory - Build metadata for a category implementation.
4409/// struct _category_t {
4410/// const char * const name;
4411/// struct _class_t *const cls;
4412/// const struct _method_list_t * const instance_methods;
4413/// const struct _method_list_t * const class_methods;
4414/// const struct _protocol_list_t * const protocols;
4415/// const struct _prop_list_t * const properties;
4416/// }
4417///
4418void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4419{
4420 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004421 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4422 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004423 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004424 std::string ExtClassName(getClassSymbolPrefix() +
4425 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004426
4427 std::vector<llvm::Constant*> Values(6);
4428 Values[0] = GetClassName(OCD->getIdentifier());
4429 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004430 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004431 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004432 std::vector<llvm::Constant*> Methods;
4433 std::string MethodListName(Prefix);
4434 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4435 "_$_" + OCD->getNameAsString();
4436
4437 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4438 e = OCD->instmeth_end(); i != e; ++i) {
4439 // Instance methods should always be defined.
4440 Methods.push_back(GetMethodConstant(*i));
4441 }
4442
4443 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004444 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004445 Methods);
4446
4447 MethodListName = Prefix;
4448 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4449 OCD->getNameAsString();
4450 Methods.clear();
4451 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4452 e = OCD->classmeth_end(); i != e; ++i) {
4453 // Class methods should always be defined.
4454 Methods.push_back(GetMethodConstant(*i));
4455 }
4456
4457 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004458 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004459 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004460 const ObjCCategoryDecl *Category =
4461 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004462 if (Category) {
4463 std::string ExtName(Interface->getNameAsString() + "_$_" +
4464 OCD->getNameAsString());
4465 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4466 + Interface->getNameAsString() + "_$_"
4467 + Category->getNameAsString(),
4468 Category->protocol_begin(),
4469 Category->protocol_end());
4470 Values[5] =
4471 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4472 OCD, Category, ObjCTypes);
4473 }
4474 else {
4475 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4476 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4477 }
4478
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004479 llvm::Constant *Init =
4480 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4481 Values);
4482 llvm::GlobalVariable *GCATV
4483 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4484 false,
4485 llvm::GlobalValue::InternalLinkage,
4486 Init,
4487 ExtCatName,
4488 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004489 GCATV->setAlignment(
4490 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004491 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004492 UsedGlobals.push_back(GCATV);
4493 DefinedCategories.push_back(GCATV);
4494}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004495
4496/// GetMethodConstant - Return a struct objc_method constant for the
4497/// given method if it has been defined. The result is null if the
4498/// method has not been defined. The return value has type MethodPtrTy.
4499llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4500 const ObjCMethodDecl *MD) {
4501 // FIXME: Use DenseMap::lookup
4502 llvm::Function *Fn = MethodDefinitions[MD];
4503 if (!Fn)
4504 return 0;
4505
4506 std::vector<llvm::Constant*> Method(3);
4507 Method[0] =
4508 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4509 ObjCTypes.SelectorPtrTy);
4510 Method[1] = GetMethodVarType(MD);
4511 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4512 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4513}
4514
4515/// EmitMethodList - Build meta-data for method declarations
4516/// struct _method_list_t {
4517/// uint32_t entsize; // sizeof(struct _objc_method)
4518/// uint32_t method_count;
4519/// struct _objc_method method_list[method_count];
4520/// }
4521///
4522llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4523 const std::string &Name,
4524 const char *Section,
4525 const ConstantVector &Methods) {
4526 // Return null for empty list.
4527 if (Methods.empty())
4528 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4529
4530 std::vector<llvm::Constant*> Values(3);
4531 // sizeof(struct _objc_method)
4532 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4533 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4534 // method_count
4535 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4536 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4537 Methods.size());
4538 Values[2] = llvm::ConstantArray::get(AT, Methods);
4539 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4540
4541 llvm::GlobalVariable *GV =
4542 new llvm::GlobalVariable(Init->getType(), false,
4543 llvm::GlobalValue::InternalLinkage,
4544 Init,
4545 Name,
4546 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004547 GV->setAlignment(
4548 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004549 GV->setSection(Section);
4550 UsedGlobals.push_back(GV);
4551 return llvm::ConstantExpr::getBitCast(GV,
4552 ObjCTypes.MethodListnfABIPtrTy);
4553}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004554
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004555/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4556/// the given ivar.
4557///
4558llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004559 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004560 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004561 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004562 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4563 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004564 llvm::GlobalVariable *IvarOffsetGV =
4565 CGM.getModule().getGlobalVariable(Name);
4566 if (!IvarOffsetGV)
4567 IvarOffsetGV =
4568 new llvm::GlobalVariable(ObjCTypes.LongTy,
4569 false,
4570 llvm::GlobalValue::ExternalLinkage,
4571 0,
4572 Name,
4573 &CGM.getModule());
4574 return IvarOffsetGV;
4575}
4576
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004577llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004578 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004579 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004580 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004581 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4582 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4583 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004584 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004585 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004586
4587 // FIXME: This matches gcc, but shouldn't the visibility be set on
4588 // the use as well (i.e., in ObjCIvarOffsetVariable).
4589 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4590 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4591 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004592 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004593 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004594 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004595 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004596 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004597}
4598
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004599/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004600/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004601/// IvarListnfABIPtrTy.
4602/// struct _ivar_t {
4603/// unsigned long int *offset; // pointer to ivar offset location
4604/// char *name;
4605/// char *type;
4606/// uint32_t alignment;
4607/// uint32_t size;
4608/// }
4609/// struct _ivar_list_t {
4610/// uint32 entsize; // sizeof(struct _ivar_t)
4611/// uint32 count;
4612/// struct _iver_t list[count];
4613/// }
4614///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004615
4616void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4617 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4618 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4619 E = OID->ivar_end(); I != E; ++I) {
4620 // Ignore unnamed bit-fields.
4621 if (!(*I)->getDeclName())
4622 continue;
4623
4624 Res.push_back(*I);
4625 }
4626
4627 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4628 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4629 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4630 Res.push_back(IV);
4631}
4632
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004633llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4634 const ObjCImplementationDecl *ID) {
4635
4636 std::vector<llvm::Constant*> Ivars, Ivar(5);
4637
4638 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4639 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4640
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004641 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004642 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004643
Daniel Dunbar91636d62009-04-20 00:33:43 +00004644 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004645 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004646 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004647
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004648 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4649 ObjCIvarDecl *IVD = OIvars[i];
4650 const FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), IVD);
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004651 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar48fa0642009-04-19 02:03:42 +00004652 GetIvarBaseOffset(Layout, Field));
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004653 Ivar[1] = GetMethodVarName(Field->getIdentifier());
Devang Patel7794bb82009-03-04 18:21:39 +00004654 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004655 const llvm::Type *FieldTy =
4656 CGM.getTypes().ConvertTypeForMem(Field->getType());
4657 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4658 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4659 Field->getType().getTypePtr()) >> 3;
4660 Align = llvm::Log2_32(Align);
4661 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004662 // NOTE. Size of a bitfield does not match gcc's, because of the
4663 // way bitfields are treated special in each. But I am told that
4664 // 'size' for bitfield ivars is ignored by the runtime so it does
4665 // not matter. If it matters, there is enough info to get the
4666 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004667 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4668 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4669 }
4670 // Return null for empty list.
4671 if (Ivars.empty())
4672 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4673 std::vector<llvm::Constant*> Values(3);
4674 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4675 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4676 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4677 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4678 Ivars.size());
4679 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4680 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4681 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4682 llvm::GlobalVariable *GV =
4683 new llvm::GlobalVariable(Init->getType(), false,
4684 llvm::GlobalValue::InternalLinkage,
4685 Init,
4686 Prefix + OID->getNameAsString(),
4687 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004688 GV->setAlignment(
4689 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004690 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004691
4692 UsedGlobals.push_back(GV);
4693 return llvm::ConstantExpr::getBitCast(GV,
4694 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004695}
4696
4697llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4698 const ObjCProtocolDecl *PD) {
4699 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4700
4701 if (!Entry) {
4702 // We use the initializer as a marker of whether this is a forward
4703 // reference or not. At module finalization we add the empty
4704 // contents for protocols which were referenced but never defined.
4705 Entry =
4706 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4707 llvm::GlobalValue::ExternalLinkage,
4708 0,
4709 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4710 &CGM.getModule());
4711 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4712 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004713 }
4714
4715 return Entry;
4716}
4717
4718/// GetOrEmitProtocol - Generate the protocol meta-data:
4719/// @code
4720/// struct _protocol_t {
4721/// id isa; // NULL
4722/// const char * const protocol_name;
4723/// const struct _protocol_list_t * protocol_list; // super protocols
4724/// const struct method_list_t * const instance_methods;
4725/// const struct method_list_t * const class_methods;
4726/// const struct method_list_t *optionalInstanceMethods;
4727/// const struct method_list_t *optionalClassMethods;
4728/// const struct _prop_list_t * properties;
4729/// const uint32_t size; // sizeof(struct _protocol_t)
4730/// const uint32_t flags; // = 0
4731/// }
4732/// @endcode
4733///
4734
4735llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4736 const ObjCProtocolDecl *PD) {
4737 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4738
4739 // Early exit if a defining object has already been generated.
4740 if (Entry && Entry->hasInitializer())
4741 return Entry;
4742
4743 const char *ProtocolName = PD->getNameAsCString();
4744
4745 // Construct method lists.
4746 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4747 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004748 for (ObjCProtocolDecl::instmeth_iterator
4749 i = PD->instmeth_begin(CGM.getContext()),
4750 e = PD->instmeth_end(CGM.getContext());
4751 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004752 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004753 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004754 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4755 OptInstanceMethods.push_back(C);
4756 } else {
4757 InstanceMethods.push_back(C);
4758 }
4759 }
4760
Douglas Gregor6ab35242009-04-09 21:40:53 +00004761 for (ObjCProtocolDecl::classmeth_iterator
4762 i = PD->classmeth_begin(CGM.getContext()),
4763 e = PD->classmeth_end(CGM.getContext());
4764 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004765 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004766 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004767 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4768 OptClassMethods.push_back(C);
4769 } else {
4770 ClassMethods.push_back(C);
4771 }
4772 }
4773
4774 std::vector<llvm::Constant*> Values(10);
4775 // isa is NULL
4776 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4777 Values[1] = GetClassName(PD->getIdentifier());
4778 Values[2] = EmitProtocolList(
4779 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4780 PD->protocol_begin(),
4781 PD->protocol_end());
4782
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004783 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004784 + PD->getNameAsString(),
4785 "__DATA, __objc_const",
4786 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004787 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004788 + PD->getNameAsString(),
4789 "__DATA, __objc_const",
4790 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004791 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004792 + PD->getNameAsString(),
4793 "__DATA, __objc_const",
4794 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004795 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 + PD->getNameAsString(),
4797 "__DATA, __objc_const",
4798 OptClassMethods);
4799 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4800 0, PD, ObjCTypes);
4801 uint32_t Size =
4802 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4803 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4804 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4805 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4806 Values);
4807
4808 if (Entry) {
4809 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004810 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004811 Entry->setInitializer(Init);
4812 } else {
4813 Entry =
4814 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004815 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 Init,
4817 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4818 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004819 Entry->setAlignment(
4820 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004821 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004823 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4824
4825 // Use this protocol meta-data to build protocol list table in section
4826 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004827 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004828 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004829 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004830 Entry,
4831 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4832 +ProtocolName,
4833 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004834 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004835 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004836 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004837 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4838 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004839 return Entry;
4840}
4841
4842/// EmitProtocolList - Generate protocol list meta-data:
4843/// @code
4844/// struct _protocol_list_t {
4845/// long protocol_count; // Note, this is 32/64 bit
4846/// struct _protocol_t[protocol_count];
4847/// }
4848/// @endcode
4849///
4850llvm::Constant *
4851CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4852 ObjCProtocolDecl::protocol_iterator begin,
4853 ObjCProtocolDecl::protocol_iterator end) {
4854 std::vector<llvm::Constant*> ProtocolRefs;
4855
Fariborz Jahanianda320092009-01-29 19:24:30 +00004856 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004857 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004858 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4859
Daniel Dunbar948e2582009-02-15 07:36:20 +00004860 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4862 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004863 return llvm::ConstantExpr::getBitCast(GV,
4864 ObjCTypes.ProtocolListnfABIPtrTy);
4865
4866 for (; begin != end; ++begin)
4867 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4868
Fariborz Jahanianda320092009-01-29 19:24:30 +00004869 // This list is null terminated.
4870 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004871 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004872
4873 std::vector<llvm::Constant*> Values(2);
4874 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4875 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004876 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004877 ProtocolRefs.size()),
4878 ProtocolRefs);
4879
4880 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4881 GV = new llvm::GlobalVariable(Init->getType(), false,
4882 llvm::GlobalValue::InternalLinkage,
4883 Init,
4884 Name,
4885 &CGM.getModule());
4886 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004887 GV->setAlignment(
4888 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004889 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004890 return llvm::ConstantExpr::getBitCast(GV,
4891 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004892}
4893
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004894/// GetMethodDescriptionConstant - This routine build following meta-data:
4895/// struct _objc_method {
4896/// SEL _cmd;
4897/// char *method_type;
4898/// char *_imp;
4899/// }
4900
4901llvm::Constant *
4902CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4903 std::vector<llvm::Constant*> Desc(3);
4904 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4905 ObjCTypes.SelectorPtrTy);
4906 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004907 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004908 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4909 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4910}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004911
4912/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4913/// This code gen. amounts to generating code for:
4914/// @code
4915/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4916/// @encode
4917///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004918LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004919 CodeGen::CodeGenFunction &CGF,
4920 QualType ObjectTy,
4921 llvm::Value *BaseValue,
4922 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004923 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004924 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4925 const FieldDecl *Field = ID->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004926 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004927
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004928 // (char *) BaseValue
Chris Lattner51123fe2009-04-17 17:46:19 +00004929 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004930 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4931 // (char*)BaseValue + Offset_symbol
4932 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4933 // (type *)((char*)BaseValue + Offset_symbol)
4934 const llvm::Type *IvarTy =
Chris Lattner51123fe2009-04-17 17:46:19 +00004935 CGM.getTypes().ConvertTypeForMem(Ivar->getType());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004936 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4937 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004938
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004939 if (Ivar->isBitField()) {
Chris Lattner51123fe2009-04-17 17:46:19 +00004940 QualType FieldTy = Field->getType();
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004941 CodeGenTypes::BitFieldInfo bitFieldInfo =
4942 CGM.getTypes().getBitFieldInfo(Field);
4943 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
Chris Lattner51123fe2009-04-17 17:46:19 +00004944 FieldTy->isSignedIntegerType(),
4945 FieldTy.getCVRQualifiers()|CVRQualifiers);
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004946 }
4947
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004948 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004949 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4950 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004951 LValue::SetObjCIvar(LV, true);
4952 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004953}
4954
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004955llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4956 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004957 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004958 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004959 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4960 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004961}
4962
Fariborz Jahanian46551122009-02-04 00:22:57 +00004963CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4964 CodeGen::CodeGenFunction &CGF,
4965 QualType ResultType,
4966 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004967 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004968 QualType Arg0Ty,
4969 bool IsSuper,
4970 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004971 // FIXME. Even though IsSuper is passes. This function doese not
4972 // handle calls to 'super' receivers.
4973 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004974 llvm::Value *Arg0 = Receiver;
4975 if (!IsSuper)
4976 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977
4978 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004979 // FIXME. This is too much work to get the ABI-specific result type
4980 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004981 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4982 llvm::SmallVector<QualType, 16>());
4983 llvm::Constant *Fn;
4984 std::string Name("\01l_");
4985 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004986#if 0
4987 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004989 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004990 // FIXME. Is there a better way of getting these names.
4991 // They are available in RuntimeFunctions vector pair.
4992 Name += "objc_msgSendId_stret_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.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004998 Name += "objc_msgSendSuper2_stret_fixup";
4999 }
5000 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005001 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005002 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005003 Name += "objc_msgSend_stret_fixup";
5004 }
5005 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005006 else if (ResultType->isFloatingType() &&
5007 // Selection of frret API only happens in 32bit nonfragile ABI.
5008 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005009 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 Name += "objc_msgSend_fpret_fixup";
5011 }
5012 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005013#if 0
5014// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005015 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005016 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005017 Name += "objc_msgSendId_fixup";
5018 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005019 else
5020#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005021 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005022 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005023 Name += "objc_msgSendSuper2_fixup";
5024 }
5025 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005026 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005027 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005028 Name += "objc_msgSend_fixup";
5029 }
5030 }
5031 Name += '_';
5032 std::string SelName(Sel.getAsString());
5033 // Replace all ':' in selector name with '_' ouch!
5034 for(unsigned i = 0; i < SelName.size(); i++)
5035 if (SelName[i] == ':')
5036 SelName[i] = '_';
5037 Name += SelName;
5038 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5039 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005040 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005041 std::vector<llvm::Constant*> Values(2);
5042 Values[0] = Fn;
5043 Values[1] = GetMethodVarName(Sel);
5044 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5045 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005046 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 Init,
5048 Name,
5049 &CGM.getModule());
5050 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005051 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005052 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 }
5054 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005055
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005056 CallArgList ActualArgs;
5057 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5058 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5059 ObjCTypes.MessageRefCPtrTy));
5060 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005061 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5062 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5063 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005064 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005065 Callee = CGF.Builder.CreateBitCast(Callee,
5066 llvm::PointerType::getUnqual(FTy));
5067 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005068}
5069
5070/// Generate code for a message send expression in the nonfragile abi.
5071CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5072 CodeGen::CodeGenFunction &CGF,
5073 QualType ResultType,
5074 Selector Sel,
5075 llvm::Value *Receiver,
5076 bool IsClassMessage,
5077 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005078 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005079 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005080 false, CallArgs);
5081}
5082
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005083llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005084CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005085 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5086
Daniel Dunbardfff2302009-03-02 05:18:14 +00005087 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005088 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5089 llvm::GlobalValue::ExternalLinkage,
5090 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005091 }
5092
5093 return GV;
5094}
5095
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005096llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005097 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005098 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5099
5100 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005101 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005102 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005103 Entry =
5104 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5105 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005106 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005107 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005108 &CGM.getModule());
5109 Entry->setAlignment(
5110 CGM.getTargetData().getPrefTypeAlignment(
5111 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005112 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5113 UsedGlobals.push_back(Entry);
5114 }
5115
5116 return Builder.CreateLoad(Entry, false, "tmp");
5117}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005118
Daniel Dunbar11394522009-04-18 08:51:00 +00005119llvm::Value *
5120CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5121 const ObjCInterfaceDecl *ID) {
5122 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5123
5124 if (!Entry) {
5125 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5126 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5127 Entry =
5128 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5129 llvm::GlobalValue::InternalLinkage,
5130 ClassGV,
5131 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5132 &CGM.getModule());
5133 Entry->setAlignment(
5134 CGM.getTargetData().getPrefTypeAlignment(
5135 ObjCTypes.ClassnfABIPtrTy));
5136 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005137 UsedGlobals.push_back(Entry);
5138 }
5139
5140 return Builder.CreateLoad(Entry, false, "tmp");
5141}
5142
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005143/// EmitMetaClassRef - Return a Value * of the address of _class_t
5144/// meta-data
5145///
5146llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5147 const ObjCInterfaceDecl *ID) {
5148 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5149 if (Entry)
5150 return Builder.CreateLoad(Entry, false, "tmp");
5151
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005152 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005153 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005154 Entry =
5155 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5156 llvm::GlobalValue::InternalLinkage,
5157 MetaClassGV,
5158 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5159 &CGM.getModule());
5160 Entry->setAlignment(
5161 CGM.getTargetData().getPrefTypeAlignment(
5162 ObjCTypes.ClassnfABIPtrTy));
5163
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005164 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005165 UsedGlobals.push_back(Entry);
5166
5167 return Builder.CreateLoad(Entry, false, "tmp");
5168}
5169
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005170/// GetClass - Return a reference to the class for the given interface
5171/// decl.
5172llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5173 const ObjCInterfaceDecl *ID) {
5174 return EmitClassRef(Builder, ID);
5175}
5176
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005177/// Generates a message send where the super is the receiver. This is
5178/// a message send to self with special delivery semantics indicating
5179/// which class's method should be called.
5180CodeGen::RValue
5181CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5182 QualType ResultType,
5183 Selector Sel,
5184 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005185 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005186 llvm::Value *Receiver,
5187 bool IsClassMessage,
5188 const CodeGen::CallArgList &CallArgs) {
5189 // ...
5190 // Create and init a super structure; this is a (receiver, class)
5191 // pair we will pass to objc_msgSendSuper.
5192 llvm::Value *ObjCSuper =
5193 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5194
5195 llvm::Value *ReceiverAsObject =
5196 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5197 CGF.Builder.CreateStore(ReceiverAsObject,
5198 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5199
5200 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005201 llvm::Value *Target;
5202 if (IsClassMessage) {
5203 if (isCategoryImpl) {
5204 // Message sent to "super' in a class method defined in
5205 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005206 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005207 Target = CGF.Builder.CreateStructGEP(Target, 0);
5208 Target = CGF.Builder.CreateLoad(Target);
5209 }
5210 else
5211 Target = EmitMetaClassRef(CGF.Builder, Class);
5212 }
5213 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005214 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005215
5216 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5217 // and ObjCTypes types.
5218 const llvm::Type *ClassTy =
5219 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5220 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5221 CGF.Builder.CreateStore(Target,
5222 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5223
5224 return EmitMessageSend(CGF, ResultType, Sel,
5225 ObjCSuper, ObjCTypes.SuperPtrCTy,
5226 true, CallArgs);
5227}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005228
5229llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5230 Selector Sel) {
5231 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5232
5233 if (!Entry) {
5234 llvm::Constant *Casted =
5235 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5236 ObjCTypes.SelectorPtrTy);
5237 Entry =
5238 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5239 llvm::GlobalValue::InternalLinkage,
5240 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5241 &CGM.getModule());
5242 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5243 UsedGlobals.push_back(Entry);
5244 }
5245
5246 return Builder.CreateLoad(Entry, false, "tmp");
5247}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005248/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5249/// objc_assign_ivar (id src, id *dst)
5250///
5251void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5252 llvm::Value *src, llvm::Value *dst)
5253{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005254 const llvm::Type * SrcTy = src->getType();
5255 if (!isa<llvm::PointerType>(SrcTy)) {
5256 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5257 assert(Size <= 8 && "does not support size > 8");
5258 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5259 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005260 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5261 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005262 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5263 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005264 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005265 src, dst, "assignivar");
5266 return;
5267}
5268
5269/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5270/// objc_assign_strongCast (id src, id *dst)
5271///
5272void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5273 CodeGen::CodeGenFunction &CGF,
5274 llvm::Value *src, llvm::Value *dst)
5275{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005276 const llvm::Type * SrcTy = src->getType();
5277 if (!isa<llvm::PointerType>(SrcTy)) {
5278 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5279 assert(Size <= 8 && "does not support size > 8");
5280 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5281 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005282 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5283 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005284 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5285 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005286 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005287 src, dst, "weakassign");
5288 return;
5289}
5290
5291/// EmitObjCWeakRead - Code gen for loading value of a __weak
5292/// object: objc_read_weak (id *src)
5293///
5294llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5295 CodeGen::CodeGenFunction &CGF,
5296 llvm::Value *AddrWeakObj)
5297{
Eli Friedman8339b352009-03-07 03:57:15 +00005298 const llvm::Type* DestTy =
5299 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005300 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005301 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005302 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005303 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005304 return read_weak;
5305}
5306
5307/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5308/// objc_assign_weak (id src, id *dst)
5309///
5310void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5311 llvm::Value *src, llvm::Value *dst)
5312{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005313 const llvm::Type * SrcTy = src->getType();
5314 if (!isa<llvm::PointerType>(SrcTy)) {
5315 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5316 assert(Size <= 8 && "does not support size > 8");
5317 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5318 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005319 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5320 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005321 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5322 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005323 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005324 src, dst, "weakassign");
5325 return;
5326}
5327
5328/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5329/// objc_assign_global (id src, id *dst)
5330///
5331void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5332 llvm::Value *src, llvm::Value *dst)
5333{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005334 const llvm::Type * SrcTy = src->getType();
5335 if (!isa<llvm::PointerType>(SrcTy)) {
5336 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5337 assert(Size <= 8 && "does not support size > 8");
5338 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5339 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005340 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5341 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005342 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5343 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005344 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005345 src, dst, "globalassign");
5346 return;
5347}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005348
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005349void
5350CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5351 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005352 bool isTry = isa<ObjCAtTryStmt>(S);
5353 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5354 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005355 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005356 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005357 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005358 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5359
5360 // For @synchronized, call objc_sync_enter(sync.expr). The
5361 // evaluation of the expression must occur before we enter the
5362 // @synchronized. We can safely avoid a temp here because jumps into
5363 // @synchronized are illegal & this will dominate uses.
5364 llvm::Value *SyncArg = 0;
5365 if (!isTry) {
5366 SyncArg =
5367 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5368 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005369 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005370 }
5371
5372 // Push an EH context entry, used for handling rethrows and jumps
5373 // through finally.
5374 CGF.PushCleanupBlock(FinallyBlock);
5375
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005376 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005377
5378 CGF.EmitBlock(TryBlock);
5379 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5380 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5381 CGF.EmitBranchThroughCleanup(FinallyEnd);
5382
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005383 // Emit the exception handler.
5384
5385 CGF.EmitBlock(TryHandler);
5386
5387 llvm::Value *llvm_eh_exception =
5388 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5389 llvm::Value *llvm_eh_selector_i64 =
5390 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5391 llvm::Value *llvm_eh_typeid_for_i64 =
5392 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5393 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5394 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5395
5396 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5397 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005398 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005399
5400 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005401 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005402 bool HasCatchAll = false;
5403 if (isTry) {
5404 if (const ObjCAtCatchStmt* CatchStmt =
5405 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5406 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005407 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005408 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005409
5410 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005411 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005412 // Use i8* null here to signal this is a catch all, not a cleanup.
5413 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5414 SelectorArgs.push_back(Null);
5415 HasCatchAll = true;
5416 break;
5417 }
5418
Daniel Dunbarede8de92009-03-06 00:01:21 +00005419 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5420 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005421 llvm::Value *IDEHType =
5422 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5423 if (!IDEHType)
5424 IDEHType =
5425 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5426 llvm::GlobalValue::ExternalLinkage,
5427 0, "OBJC_EHTYPE_id", &CGM.getModule());
5428 SelectorArgs.push_back(IDEHType);
5429 HasCatchAll = true;
5430 break;
5431 }
5432
5433 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005434 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435 assert(PT && "Invalid @catch type.");
5436 const ObjCInterfaceType *IT =
5437 PT->getPointeeType()->getAsObjCInterfaceType();
5438 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005439 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005440 SelectorArgs.push_back(EHType);
5441 }
5442 }
5443 }
5444
5445 // We use a cleanup unless there was already a catch all.
5446 if (!HasCatchAll) {
5447 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005448 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005449 }
5450
5451 llvm::Value *Selector =
5452 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5453 SelectorArgs.begin(), SelectorArgs.end(),
5454 "selector");
5455 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005456 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005457 const Stmt *CatchBody = Handlers[i].second;
5458
5459 llvm::BasicBlock *Next = 0;
5460
5461 // The last handler always matches.
5462 if (i + 1 != e) {
5463 assert(CatchParam && "Only last handler can be a catch all.");
5464
5465 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5466 Next = CGF.createBasicBlock("catch.next");
5467 llvm::Value *Id =
5468 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5469 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5470 ObjCTypes.Int8PtrTy));
5471 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5472 Match, Next);
5473
5474 CGF.EmitBlock(Match);
5475 }
5476
5477 if (CatchBody) {
5478 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5479 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5480
5481 // Cleanups must call objc_end_catch.
5482 //
5483 // FIXME: It seems incorrect for objc_begin_catch to be inside
5484 // this context, but this matches gcc.
5485 CGF.PushCleanupBlock(MatchEnd);
5486 CGF.setInvokeDest(MatchHandler);
5487
5488 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005489 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005490
5491 // Bind the catch parameter if it exists.
5492 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005493 ExcObject =
5494 CGF.Builder.CreateBitCast(ExcObject,
5495 CGF.ConvertType(CatchParam->getType()));
5496 // CatchParam is a ParmVarDecl because of the grammar
5497 // construction used to handle this, but for codegen purposes
5498 // we treat this as a local decl.
5499 CGF.EmitLocalBlockVarDecl(*CatchParam);
5500 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005501 }
5502
5503 CGF.ObjCEHValueStack.push_back(ExcObject);
5504 CGF.EmitStmt(CatchBody);
5505 CGF.ObjCEHValueStack.pop_back();
5506
5507 CGF.EmitBranchThroughCleanup(FinallyEnd);
5508
5509 CGF.EmitBlock(MatchHandler);
5510
5511 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5512 // We are required to emit this call to satisfy LLVM, even
5513 // though we don't use the result.
5514 llvm::SmallVector<llvm::Value*, 8> Args;
5515 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005516 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005517 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5518 0));
5519 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5520 CGF.Builder.CreateStore(Exc, RethrowPtr);
5521 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5522
5523 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5524
5525 CGF.EmitBlock(MatchEnd);
5526
5527 // Unfortunately, we also have to generate another EH frame here
5528 // in case this throws.
5529 llvm::BasicBlock *MatchEndHandler =
5530 CGF.createBasicBlock("match.end.handler");
5531 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005532 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005533 Cont, MatchEndHandler,
5534 Args.begin(), Args.begin());
5535
5536 CGF.EmitBlock(Cont);
5537 if (Info.SwitchBlock)
5538 CGF.EmitBlock(Info.SwitchBlock);
5539 if (Info.EndBlock)
5540 CGF.EmitBlock(Info.EndBlock);
5541
5542 CGF.EmitBlock(MatchEndHandler);
5543 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5544 // We are required to emit this call to satisfy LLVM, even
5545 // though we don't use the result.
5546 Args.clear();
5547 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005548 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005549 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5550 0));
5551 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5552 CGF.Builder.CreateStore(Exc, RethrowPtr);
5553 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5554
5555 if (Next)
5556 CGF.EmitBlock(Next);
5557 } else {
5558 assert(!Next && "catchup should be last handler.");
5559
5560 CGF.Builder.CreateStore(Exc, RethrowPtr);
5561 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5562 }
5563 }
5564
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005565 // Pop the cleanup entry, the @finally is outside this cleanup
5566 // scope.
5567 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5568 CGF.setInvokeDest(PrevLandingPad);
5569
5570 CGF.EmitBlock(FinallyBlock);
5571
5572 if (isTry) {
5573 if (const ObjCAtFinallyStmt* FinallyStmt =
5574 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5575 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5576 } else {
5577 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5578 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005579 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005581
5582 if (Info.SwitchBlock)
5583 CGF.EmitBlock(Info.SwitchBlock);
5584 if (Info.EndBlock)
5585 CGF.EmitBlock(Info.EndBlock);
5586
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005587 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005588 CGF.EmitBranch(FinallyEnd);
5589
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005590 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005591 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005592 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005593 CGF.Builder.CreateUnreachable();
5594
5595 CGF.EmitBlock(FinallyEnd);
5596}
5597
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005598/// EmitThrowStmt - Generate code for a throw statement.
5599void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5600 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005601 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005602 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005603 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005604 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005605 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5606 "Unexpected rethrow outside @catch block.");
5607 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005608 }
5609
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005610 llvm::Value *ExceptionAsObject =
5611 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5612 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5613 if (InvokeDest) {
5614 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005615 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005616 Cont, InvokeDest,
5617 &ExceptionAsObject, &ExceptionAsObject + 1);
5618 CGF.EmitBlock(Cont);
5619 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005620 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005621 CGF.Builder.CreateUnreachable();
5622
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005623 // Clear the insertion point to indicate we are in unreachable code.
5624 CGF.Builder.ClearInsertionPoint();
5625}
Daniel Dunbare588b992009-03-01 04:46:24 +00005626
5627llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005628CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5629 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005630 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005631
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005632 // If we don't need a definition, return the entry if found or check
5633 // if we use an external reference.
5634 if (!ForDefinition) {
5635 if (Entry)
5636 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005637
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005638 // If this type (or a super class) has the __objc_exception__
5639 // attribute, emit an external reference.
5640 if (hasObjCExceptionAttribute(ID))
5641 return Entry =
5642 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5643 llvm::GlobalValue::ExternalLinkage,
5644 0,
5645 (std::string("OBJC_EHTYPE_$_") +
5646 ID->getIdentifier()->getName()),
5647 &CGM.getModule());
5648 }
5649
5650 // Otherwise we need to either make a new entry or fill in the
5651 // initializer.
5652 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005653 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005654 std::string VTableName = "objc_ehtype_vtable";
5655 llvm::GlobalVariable *VTableGV =
5656 CGM.getModule().getGlobalVariable(VTableName);
5657 if (!VTableGV)
5658 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5659 llvm::GlobalValue::ExternalLinkage,
5660 0, VTableName, &CGM.getModule());
5661
5662 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5663
5664 std::vector<llvm::Constant*> Values(3);
5665 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5666 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005667 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005668 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5669
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005670 if (Entry) {
5671 Entry->setInitializer(Init);
5672 } else {
5673 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5674 llvm::GlobalValue::WeakAnyLinkage,
5675 Init,
5676 (std::string("OBJC_EHTYPE_$_") +
5677 ID->getIdentifier()->getName()),
5678 &CGM.getModule());
5679 }
5680
Daniel Dunbar04d40782009-04-14 06:00:08 +00005681 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005682 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005683 Entry->setAlignment(8);
5684
5685 if (ForDefinition) {
5686 Entry->setSection("__DATA,__objc_const");
5687 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5688 } else {
5689 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5690 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005691
5692 return Entry;
5693}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005694
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005695/* *** */
5696
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005697CodeGen::CGObjCRuntime *
5698CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005699 return new CGObjCMac(CGM);
5700}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005701
5702CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005703CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005704 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005705}