blob: f1460bd0193537209da9ba563fd8b19cb69c3c81 [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 Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
Fariborz Jahanianee0af742009-01-21 22:04:16 +000038class ObjCCommonTypesHelper {
39protected:
40 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000041
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000043 const llvm::Type *ShortTy, *IntTy, *LongTy;
44 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000045
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000046 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
47 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000048
49 /// PtrObjectPtrTy - LLVM type for id *
50 const llvm::Type *PtrObjectPtrTy;
51
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000052 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000053 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000054 /// ProtocolPtrTy - LLVM type for external protocol handles
55 /// (typeof(Protocol))
56 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000057
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000058 // SuperCTy - clang type for struct objc_super.
59 QualType SuperCTy;
60 // SuperPtrCTy - clang type for struct objc_super *.
61 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000062
Daniel Dunbare8b470d2008-08-23 04:28:29 +000063 /// SuperTy - LLVM type for struct objc_super.
64 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000065 /// SuperPtrTy - LLVM type for struct objc_super *.
66 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000067
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000068 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
69 /// in GCC parlance).
70 const llvm::StructType *PropertyTy;
71
72 /// PropertyListTy - LLVM type for struct objc_property_list
73 /// (_prop_list_t in GCC parlance).
74 const llvm::StructType *PropertyListTy;
75 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
76 const llvm::Type *PropertyListPtrTy;
77
78 // MethodTy - LLVM type for struct objc_method.
79 const llvm::StructType *MethodTy;
80
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000081 /// CacheTy - LLVM type for struct objc_cache.
82 const llvm::Type *CacheTy;
83 /// CachePtrTy - LLVM type for struct objc_cache *.
84 const llvm::Type *CachePtrTy;
85
Fariborz Jahaniandb286862009-01-22 00:37:21 +000086 llvm::Function *GetPropertyFn, *SetPropertyFn;
87
88 llvm::Function *EnumerationMutationFn;
89
90 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
91 llvm::Function *GcReadWeakFn;
92
93 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
94 llvm::Function *GcAssignWeakFn;
95
96 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
97 llvm::Function *GcAssignGlobalFn;
98
99 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
100 llvm::Function *GcAssignIvarFn;
101
102 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
103 llvm::Function *GcAssignStrongCastFn;
104
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000105 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
106 ~ObjCCommonTypesHelper(){}
107};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000108
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000109/// ObjCTypesHelper - Helper class that encapsulates lazy
110/// construction of varies types used during ObjC generation.
111class ObjCTypesHelper : public ObjCCommonTypesHelper {
112private:
113
114 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
115 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
116 *MessageSendSuperFpretFn;
117
118public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000119 /// SymtabTy - LLVM type for struct objc_symtab.
120 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000121 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
122 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000123 /// ModuleTy - LLVM type for struct objc_module.
124 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000125
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000126 /// ProtocolTy - LLVM type for struct objc_protocol.
127 const llvm::StructType *ProtocolTy;
128 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
129 const llvm::Type *ProtocolPtrTy;
130 /// ProtocolExtensionTy - LLVM type for struct
131 /// objc_protocol_extension.
132 const llvm::StructType *ProtocolExtensionTy;
133 /// ProtocolExtensionTy - LLVM type for struct
134 /// objc_protocol_extension *.
135 const llvm::Type *ProtocolExtensionPtrTy;
136 /// MethodDescriptionTy - LLVM type for struct
137 /// objc_method_description.
138 const llvm::StructType *MethodDescriptionTy;
139 /// MethodDescriptionListTy - LLVM type for struct
140 /// objc_method_description_list.
141 const llvm::StructType *MethodDescriptionListTy;
142 /// MethodDescriptionListPtrTy - LLVM type for struct
143 /// objc_method_description_list *.
144 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000145 /// ProtocolListTy - LLVM type for struct objc_property_list.
146 const llvm::Type *ProtocolListTy;
147 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
148 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000149 /// CategoryTy - LLVM type for struct objc_category.
150 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000151 /// ClassTy - LLVM type for struct objc_class.
152 const llvm::StructType *ClassTy;
153 /// ClassPtrTy - LLVM type for struct objc_class *.
154 const llvm::Type *ClassPtrTy;
155 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
156 const llvm::StructType *ClassExtensionTy;
157 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
158 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000159 // IvarTy - LLVM type for struct objc_ivar.
160 const llvm::StructType *IvarTy;
161 /// IvarListTy - LLVM type for struct objc_ivar_list.
162 const llvm::Type *IvarListTy;
163 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
164 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000165 /// MethodListTy - LLVM type for struct objc_method_list.
166 const llvm::Type *MethodListTy;
167 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
168 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000169
170 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
171 const llvm::Type *ExceptionDataTy;
172
173 /// ExceptionThrowFn - LLVM objc_exception_throw function.
174 llvm::Function *ExceptionThrowFn;
175
176 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
177 llvm::Function *ExceptionTryEnterFn;
178
179 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
180 llvm::Function *ExceptionTryExitFn;
181
182 /// ExceptionExtractFn - LLVM objc_exception_extract function.
183 llvm::Function *ExceptionExtractFn;
184
185 /// ExceptionMatchFn - LLVM objc_exception_match function.
186 llvm::Function *ExceptionMatchFn;
187
188 /// SetJmpFn - LLVM _setjmp function.
189 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000190
191 /// SyncEnterFn - LLVM object_sync_enter function.
192 llvm::Function *SyncEnterFn;
193
194 /// SyncExitFn - LLVM object_sync_exit function.
195 llvm::Function *SyncExitFn;
196
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000197public:
198 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000199 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000200
201
202 llvm::Function *getSendFn(bool IsSuper) {
203 return IsSuper ? MessageSendSuperFn : MessageSendFn;
204 }
205
206 llvm::Function *getSendStretFn(bool IsSuper) {
207 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
208 }
209
210 llvm::Function *getSendFpretFn(bool IsSuper) {
211 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
212 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000213};
214
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000215/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000216/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000217class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000218public:
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000219 // MethodListnfABITy - LLVM for struct _method_list_t
220 const llvm::StructType *MethodListnfABITy;
221
222 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
223 const llvm::Type *MethodListnfABIPtrTy;
224
225 // ProtocolnfABITy = LLVM for struct _protocol_t
226 const llvm::StructType *ProtocolnfABITy;
227
228 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
229 const llvm::StructType *ProtocolListnfABITy;
230
231 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
232 const llvm::Type *ProtocolListnfABIPtrTy;
233
234 // ClassnfABITy - LLVM for struct _class_t
235 const llvm::StructType *ClassnfABITy;
236
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000237 // ClassnfABIPtrTy - LLVM for struct _class_t*
238 const llvm::Type *ClassnfABIPtrTy;
239
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000240 // IvarnfABITy - LLVM for struct _ivar_t
241 const llvm::StructType *IvarnfABITy;
242
243 // IvarListnfABITy - LLVM for struct _ivar_list_t
244 const llvm::StructType *IvarListnfABITy;
245
246 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
247 const llvm::Type *IvarListnfABIPtrTy;
248
249 // ClassRonfABITy - LLVM for struct _class_ro_t
250 const llvm::StructType *ClassRonfABITy;
251
252 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
253 const llvm::Type *ImpnfABITy;
254
255 // CategorynfABITy - LLVM for struct _category_t
256 const llvm::StructType *CategorynfABITy;
257
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000258 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
259 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000260};
261
262class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
263protected:
264 CodeGen::CodeGenModule &CGM;
265 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000266 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000267
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000268 /// LazySymbols - Symbols to generate a lazy reference for. See
269 /// DefinedSymbols and FinishModule().
270 std::set<IdentifierInfo*> LazySymbols;
271
272 /// DefinedSymbols - External symbols which are defined by this
273 /// module. The symbols in this list and LazySymbols are used to add
274 /// special linker symbols which ensure that Objective-C modules are
275 /// linked properly.
276 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000277
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000278 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000279 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000280
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000281 /// MethodVarNames - uniqued method variable names.
282 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000283
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000284 /// MethodVarTypes - uniqued method type signatures. We have to use
285 /// a StringMap here because have no other unique reference.
286 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000287
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000288 /// MethodDefinitions - map of methods which have been defined in
289 /// this translation unit.
290 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000291
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000292 /// PropertyNames - uniqued method variable names.
293 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000294
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000295 /// ClassReferences - uniqued class references.
296 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000297
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000298 /// SelectorReferences - uniqued selector references.
299 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000300
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000301 /// Protocols - Protocols for which an objc_protocol structure has
302 /// been emitted. Forward declarations are handled by creating an
303 /// empty structure whose initializer is filled in when/if defined.
304 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000305
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000306 /// DefinedProtocols - Protocols which have actually been
307 /// defined. We should not need this, see FIXME in GenerateProtocol.
308 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000309
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000310 /// DefinedClasses - List of defined classes.
311 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000312
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000313 /// DefinedCategories - List of defined categories.
314 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000315
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000316 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000317 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000318 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000319
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000320 /// GetNameForMethod - Return a name for the given method.
321 /// \param[out] NameOut - The return value.
322 void GetNameForMethod(const ObjCMethodDecl *OMD,
323 const ObjCContainerDecl *CD,
324 std::string &NameOut);
325
326 /// GetMethodVarName - Return a unique constant for the given
327 /// selector's name. The return value has type char *.
328 llvm::Constant *GetMethodVarName(Selector Sel);
329 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
330 llvm::Constant *GetMethodVarName(const std::string &Name);
331
332 /// GetMethodVarType - Return a unique constant for the given
333 /// selector's name. The return value has type char *.
334
335 // FIXME: This is a horrible name.
336 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
337 llvm::Constant *GetMethodVarType(const std::string &Name);
338
339 /// GetPropertyName - Return a unique constant for the given
340 /// name. The return value has type char *.
341 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
342
343 // FIXME: This can be dropped once string functions are unified.
344 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
345 const Decl *Container);
346
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000347 /// GetClassName - Return a unique constant for the given selector's
348 /// name. The return value has type char *.
349 llvm::Constant *GetClassName(IdentifierInfo *Ident);
350
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000351public:
352 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
353 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000354
355 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000356
357 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
358 const ObjCContainerDecl *CD=0);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359};
360
361class CGObjCMac : public CGObjCCommonMac {
362private:
363 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000364 /// EmitImageInfo - Emit the image info marker used to encode some module
365 /// level information.
366 void EmitImageInfo();
367
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000368 /// EmitModuleInfo - Another marker encoding module level
369 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000370 void EmitModuleInfo();
371
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000372 /// EmitModuleSymols - Emit module symbols, the list of defined
373 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000374 llvm::Constant *EmitModuleSymbols();
375
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000376 /// FinishModule - Write out global data structures at the end of
377 /// processing a translation unit.
378 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000379
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000380 /// EmitClassExtension - Generate the class extension structure used
381 /// to store the weak ivar layout and properties. The return value
382 /// has type ClassExtensionPtrTy.
383 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
384
385 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
386 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000387 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 const ObjCInterfaceDecl *ID);
389
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000390 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000391 QualType ResultType,
392 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000393 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000394 QualType Arg0Ty,
395 bool IsSuper,
396 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// EmitIvarList - Emit the ivar list for the given
399 /// implementation. If ForClass is true the list of class ivars
400 /// (i.e. metaclass ivars) is emitted, otherwise the list of
401 /// interface ivars will be emitted. The return value has type
402 /// IvarListPtrTy.
403 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
404 bool ForClass,
405 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000406
407 /// EmitMetaClass - Emit a forward reference to the class structure
408 /// for the metaclass of the given interface. The return value has
409 /// type ClassPtrTy.
410 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
411
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000412 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000413 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000414 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
415 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000416 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000417 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000418
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000419 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000420
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000421 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000422
423 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000424 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000425 llvm::Constant *EmitMethodList(const std::string &Name,
426 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000427 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000428
429 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000430 /// method declarations.
431 /// - TypeName: The name for the type containing the methods.
432 /// - IsProtocol: True iff these methods are for a protocol.
433 /// - ClassMethds: True iff these are class methods.
434 /// - Required: When true, only "required" methods are
435 /// listed. Similarly, when false only "optional" methods are
436 /// listed. For classes this should always be true.
437 /// - begin, end: The method list to output.
438 ///
439 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000440 llvm::Constant *EmitMethodDescList(const std::string &Name,
441 const char *Section,
442 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000443
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000444 /// EmitPropertyList - Emit the given property list. The return
445 /// value has type PropertyListPtrTy.
446 llvm::Constant *EmitPropertyList(const std::string &Name,
Steve Naroff93983f82009-01-11 12:47:58 +0000447 const Decl *Container,
448 const ObjCContainerDecl *OCD);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000449
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000450 /// GetOrEmitProtocol - Get the protocol object for the given
451 /// declaration, emitting it if necessary. The return value has type
452 /// ProtocolPtrTy.
453 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
454
455 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
456 /// object for the given declaration, emitting it if needed. These
457 /// forward references will be filled in with empty bodies if no
458 /// definition is seen. The return value has type ProtocolPtrTy.
459 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
460
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000461 /// EmitProtocolExtension - Generate the protocol extension
462 /// structure used to store optional instance and class methods, and
463 /// protocol properties. The return value has type
464 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000465 llvm::Constant *
466 EmitProtocolExtension(const ObjCProtocolDecl *PD,
467 const ConstantVector &OptInstanceMethods,
468 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000469
470 /// EmitProtocolList - Generate the list of referenced
471 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000472 llvm::Constant *EmitProtocolList(const std::string &Name,
473 ObjCProtocolDecl::protocol_iterator begin,
474 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000475
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000476 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
477 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000478 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000479
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000480 /// GetProtocolRef - Return a reference to the internal protocol
481 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000482 /// defined. The return value has type ProtocolPtrTy.
483 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000484
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000485public:
486 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000487
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000488 virtual llvm::Function *ModuleInitFunction();
489
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000490 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000491 QualType ResultType,
492 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000493 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000494 bool IsClassMessage,
495 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000496
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000497 virtual CodeGen::RValue
498 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000499 QualType ResultType,
500 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000501 const ObjCInterfaceDecl *Class,
502 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000503 bool IsClassMessage,
504 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000505
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000506 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000507 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000508
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000509 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000510
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000511 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000512
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000513 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000514
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000515 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000516 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000517
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000518 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000519
Daniel Dunbar49f66022008-09-24 03:38:44 +0000520 virtual llvm::Function *GetPropertyGetFunction();
521 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000522 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000523
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000524 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
525 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000526 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
527 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000528 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000529 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000530 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
531 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000532 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
533 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000534 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
535 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000536 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
537 llvm::Value *src, llvm::Value *dest);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000538};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000539
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000540class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000541private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000542 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000543 llvm::GlobalVariable* ObjCEmptyCacheVar;
544 llvm::GlobalVariable* ObjCEmptyVtableVar;
545
546 /// FinishNonFragileABIModule - Write out global data structures at the end of
547 /// processing a translation unit.
548 void FinishNonFragileABIModule();
549
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000550 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
551 unsigned InstanceStart,
552 unsigned InstanceSize,
553 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000554 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
555 llvm::Constant *IsAGV,
556 llvm::Constant *SuperClassGV,
557 llvm::Constant *ClassRoGV);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000558
559 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
560
561 /// EmitMethodList - Emit the method list for the given
562 /// implementation. The return value has type MethodListnfABITy.
563 llvm::Constant *EmitMethodList(const std::string &Name,
564 const char *Section,
565 const ConstantVector &Methods);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000566
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000567public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000568 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000569 // FIXME. All stubs for now!
570 virtual llvm::Function *ModuleInitFunction();
571
572 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
573 QualType ResultType,
574 Selector Sel,
575 llvm::Value *Receiver,
576 bool IsClassMessage,
577 const CallArgList &CallArgs)
578 {return RValue::get(0);}
579
580 virtual CodeGen::RValue
581 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
582 QualType ResultType,
583 Selector Sel,
584 const ObjCInterfaceDecl *Class,
585 llvm::Value *Receiver,
586 bool IsClassMessage,
587 const CallArgList &CallArgs){ return RValue::get(0);}
588
589 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
590 const ObjCInterfaceDecl *ID){ return 0; }
591
592 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
593 { return 0; }
594
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000595 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000596
597 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
598
599 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
600 const ObjCProtocolDecl *PD)
601 { return 0; }
602
603 virtual void GenerateProtocol(const ObjCProtocolDecl *PD){ return; }
604
605 virtual llvm::Function *GetPropertyGetFunction(){ return 0; }
606 virtual llvm::Function *GetPropertySetFunction()
607 { return 0; }
608 virtual llvm::Function *EnumerationMutationFunction()
609 { return 0; }
610
611 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
612 const Stmt &S)
613 { return; }
614 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
615 const ObjCAtThrowStmt &S)
616 { return; }
617 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
618 llvm::Value *AddrWeakObj)
619 { return 0; }
620 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
621 llvm::Value *src, llvm::Value *dst)
622 { return; }
623 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
624 llvm::Value *src, llvm::Value *dest)
625 { return; }
626 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
627 llvm::Value *src, llvm::Value *dest)
628 { return; }
629 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
630 llvm::Value *src, llvm::Value *dest)
631 { return; }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000632};
633
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000634} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000635
636/* *** Helper Functions *** */
637
638/// getConstantGEP() - Help routine to construct simple GEPs.
639static llvm::Constant *getConstantGEP(llvm::Constant *C,
640 unsigned idx0,
641 unsigned idx1) {
642 llvm::Value *Idxs[] = {
643 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
644 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
645 };
646 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
647}
648
649/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000650
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000651CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
652 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000653{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000654 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000655 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000656}
657
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000658/// GetClass - Return a reference to the class for the given interface
659/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000660llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000661 const ObjCInterfaceDecl *ID) {
662 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000663}
664
665/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000666llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000667 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000668}
669
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000670/// Generate a constant CFString object.
671/*
672 struct __builtin_CFString {
673 const int *isa; // point to __CFConstantStringClassReference
674 int flags;
675 const char *str;
676 long length;
677 };
678*/
679
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000680llvm::Constant *CGObjCCommonMac::GenerateConstantString(
681 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000682 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000683}
684
685/// Generates a message send where the super is the receiver. This is
686/// a message send to self with special delivery semantics indicating
687/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000688CodeGen::RValue
689CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000690 QualType ResultType,
691 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000692 const ObjCInterfaceDecl *Class,
693 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000694 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000695 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000696 // Create and init a super structure; this is a (receiver, class)
697 // pair we will pass to objc_msgSendSuper.
698 llvm::Value *ObjCSuper =
699 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
700 llvm::Value *ReceiverAsObject =
701 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
702 CGF.Builder.CreateStore(ReceiverAsObject,
703 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000704
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000705 // If this is a class message the metaclass is passed as the target.
706 llvm::Value *Target;
707 if (IsClassMessage) {
708 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
709 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
710 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
711 Target = Super;
712 } else {
713 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
714 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000715 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
716 // and ObjCTypes types.
717 const llvm::Type *ClassTy =
718 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000719 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000720 CGF.Builder.CreateStore(Target,
721 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
722
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000723 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000724 ObjCSuper, ObjCTypes.SuperPtrCTy,
725 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000726}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000727
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000728/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000729CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000730 QualType ResultType,
731 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000732 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000733 bool IsClassMessage,
734 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000735 llvm::Value *Arg0 =
736 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000737 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000738 Arg0, CGF.getContext().getObjCIdType(),
739 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000740}
741
742CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000743 QualType ResultType,
744 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000745 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000746 QualType Arg0Ty,
747 bool IsSuper,
748 const CallArgList &CallArgs) {
749 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000750 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
751 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
752 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000753 CGF.getContext().getObjCSelType()));
754 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000755
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000756 const llvm::FunctionType *FTy =
757 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
758 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000759
760 llvm::Constant *Fn;
761 if (CGM.ReturnTypeUsesSret(ResultType)) {
762 Fn = ObjCTypes.getSendStretFn(IsSuper);
763 } else if (ResultType->isFloatingType()) {
764 // FIXME: Sadly, this is wrong. This actually depends on the
765 // architecture. This happens to be right for x86-32 though.
766 Fn = ObjCTypes.getSendFpretFn(IsSuper);
767 } else {
768 Fn = ObjCTypes.getSendFn(IsSuper);
769 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000770 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000771 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000772}
773
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000774llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000775 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000776 // FIXME: I don't understand why gcc generates this, or where it is
777 // resolved. Investigate. Its also wasteful to look this up over and
778 // over.
779 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
780
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000781 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
782 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000783}
784
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000785void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
786 // FIXME: We shouldn't need this, the protocol decl should contain
787 // enough information to tell us whether this was a declaration or a
788 // definition.
789 DefinedProtocols.insert(PD->getIdentifier());
790
791 // If we have generated a forward reference to this protocol, emit
792 // it now. Otherwise do nothing, the protocol objects are lazily
793 // emitted.
794 if (Protocols.count(PD->getIdentifier()))
795 GetOrEmitProtocol(PD);
796}
797
798llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
799 if (DefinedProtocols.count(PD->getIdentifier()))
800 return GetOrEmitProtocol(PD);
801 return GetOrEmitProtocolRef(PD);
802}
803
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000804/*
805 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
806 struct _objc_protocol {
807 struct _objc_protocol_extension *isa;
808 char *protocol_name;
809 struct _objc_protocol_list *protocol_list;
810 struct _objc__method_prototype_list *instance_methods;
811 struct _objc__method_prototype_list *class_methods
812 };
813
814 See EmitProtocolExtension().
815*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000816llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
817 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
818
819 // Early exit if a defining object has already been generated.
820 if (Entry && Entry->hasInitializer())
821 return Entry;
822
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000823 // FIXME: I don't understand why gcc generates this, or where it is
824 // resolved. Investigate. Its also wasteful to look this up over and
825 // over.
826 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
827
Chris Lattner8ec03f52008-11-24 03:54:41 +0000828 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000829
830 // Construct method lists.
831 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
832 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
833 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
834 e = PD->instmeth_end(); i != e; ++i) {
835 ObjCMethodDecl *MD = *i;
836 llvm::Constant *C = GetMethodDescriptionConstant(MD);
837 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
838 OptInstanceMethods.push_back(C);
839 } else {
840 InstanceMethods.push_back(C);
841 }
842 }
843
844 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
845 e = PD->classmeth_end(); i != e; ++i) {
846 ObjCMethodDecl *MD = *i;
847 llvm::Constant *C = GetMethodDescriptionConstant(MD);
848 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
849 OptClassMethods.push_back(C);
850 } else {
851 ClassMethods.push_back(C);
852 }
853 }
854
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000855 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000856 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000857 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000858 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000859 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +0000860 PD->protocol_begin(),
861 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000862 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000863 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
864 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000865 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
866 InstanceMethods);
867 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000868 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
869 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000870 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
871 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000872 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
873 Values);
874
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000875 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000876 // Already created, fix the linkage and update the initializer.
877 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000878 Entry->setInitializer(Init);
879 } else {
880 Entry =
881 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
882 llvm::GlobalValue::InternalLinkage,
883 Init,
884 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
885 &CGM.getModule());
886 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
887 UsedGlobals.push_back(Entry);
888 // FIXME: Is this necessary? Why only for protocol?
889 Entry->setAlignment(4);
890 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000891
892 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000893}
894
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000895llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000896 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
897
898 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000899 // We use the initializer as a marker of whether this is a forward
900 // reference or not. At module finalization we add the empty
901 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000902 Entry =
903 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000904 llvm::GlobalValue::ExternalLinkage,
905 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000906 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000907 &CGM.getModule());
908 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
909 UsedGlobals.push_back(Entry);
910 // FIXME: Is this necessary? Why only for protocol?
911 Entry->setAlignment(4);
912 }
913
914 return Entry;
915}
916
917/*
918 struct _objc_protocol_extension {
919 uint32_t size;
920 struct objc_method_description_list *optional_instance_methods;
921 struct objc_method_description_list *optional_class_methods;
922 struct objc_property_list *instance_properties;
923 };
924*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000925llvm::Constant *
926CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
927 const ConstantVector &OptInstanceMethods,
928 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000929 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +0000930 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000931 std::vector<llvm::Constant*> Values(4);
932 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000933 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000934 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
935 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000936 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
937 OptInstanceMethods);
938 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000939 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
940 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000941 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
942 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000943 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
944 PD->getNameAsString(),
Steve Naroff93983f82009-01-11 12:47:58 +0000945 0, PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000946
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000947 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000948 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
949 Values[3]->isNullValue())
950 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
951
952 llvm::Constant *Init =
953 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
954 llvm::GlobalVariable *GV =
955 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
956 llvm::GlobalValue::InternalLinkage,
957 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000958 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000959 &CGM.getModule());
960 // No special section, but goes in llvm.used
961 UsedGlobals.push_back(GV);
962
963 return GV;
964}
965
966/*
967 struct objc_protocol_list {
968 struct objc_protocol_list *next;
969 long count;
970 Protocol *list[];
971 };
972*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000973llvm::Constant *
974CGObjCMac::EmitProtocolList(const std::string &Name,
975 ObjCProtocolDecl::protocol_iterator begin,
976 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000977 std::vector<llvm::Constant*> ProtocolRefs;
978
Daniel Dunbardbc933702008-08-21 21:57:41 +0000979 for (; begin != end; ++begin)
980 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000981
982 // Just return null for empty protocol lists
983 if (ProtocolRefs.empty())
984 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
985
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000986 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000987 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
988
989 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000990 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000991 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
992 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
993 Values[2] =
994 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
995 ProtocolRefs.size()),
996 ProtocolRefs);
997
998 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
999 llvm::GlobalVariable *GV =
1000 new llvm::GlobalVariable(Init->getType(), false,
1001 llvm::GlobalValue::InternalLinkage,
1002 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001003 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001004 &CGM.getModule());
1005 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1006 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1007}
1008
1009/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001010 struct _objc_property {
1011 const char * const name;
1012 const char * const attributes;
1013 };
1014
1015 struct _objc_property_list {
1016 uint32_t entsize; // sizeof (struct _objc_property)
1017 uint32_t prop_count;
1018 struct _objc_property[prop_count];
1019 };
1020*/
1021llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001022 const Decl *Container,
Steve Naroff93983f82009-01-11 12:47:58 +00001023 const ObjCContainerDecl *OCD) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001024 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001025 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1026 E = OCD->prop_end(); I != E; ++I) {
1027 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001028 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001029 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001030 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1031 Prop));
1032 }
1033
1034 // Return null for empty list.
1035 if (Properties.empty())
1036 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1037
1038 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001039 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001040 std::vector<llvm::Constant*> Values(3);
1041 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1042 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1043 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1044 Properties.size());
1045 Values[2] = llvm::ConstantArray::get(AT, Properties);
1046 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1047
1048 llvm::GlobalVariable *GV =
1049 new llvm::GlobalVariable(Init->getType(), false,
1050 llvm::GlobalValue::InternalLinkage,
1051 Init,
1052 Name,
1053 &CGM.getModule());
1054 // No special section on property lists?
1055 UsedGlobals.push_back(GV);
1056 return llvm::ConstantExpr::getBitCast(GV,
1057 ObjCTypes.PropertyListPtrTy);
1058
1059}
1060
1061/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001062 struct objc_method_description_list {
1063 int count;
1064 struct objc_method_description list[];
1065 };
1066*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001067llvm::Constant *
1068CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1069 std::vector<llvm::Constant*> Desc(2);
1070 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1071 ObjCTypes.SelectorPtrTy);
1072 Desc[1] = GetMethodVarType(MD);
1073 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1074 Desc);
1075}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001076
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001077llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1078 const char *Section,
1079 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001080 // Return null for empty list.
1081 if (Methods.empty())
1082 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1083
1084 std::vector<llvm::Constant*> Values(2);
1085 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1086 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1087 Methods.size());
1088 Values[1] = llvm::ConstantArray::get(AT, Methods);
1089 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1090
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001091 llvm::GlobalVariable *GV =
1092 new llvm::GlobalVariable(Init->getType(), false,
1093 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001094 Init, Name, &CGM.getModule());
1095 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001096 UsedGlobals.push_back(GV);
1097 return llvm::ConstantExpr::getBitCast(GV,
1098 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001099}
1100
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001101/*
1102 struct _objc_category {
1103 char *category_name;
1104 char *class_name;
1105 struct _objc_method_list *instance_methods;
1106 struct _objc_method_list *class_methods;
1107 struct _objc_protocol_list *protocols;
1108 uint32_t size; // <rdar://4585769>
1109 struct _objc_property_list *instance_properties;
1110 };
1111 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001112void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001113 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001114
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001115 // FIXME: This is poor design, the OCD should have a pointer to the
1116 // category decl. Additionally, note that Category can be null for
1117 // the @implementation w/o an @interface case. Sema should just
1118 // create one for us as it does for @implementation so everyone else
1119 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001120 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001121 const ObjCCategoryDecl *Category =
1122 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001123 std::string ExtName(Interface->getNameAsString() + "_" +
1124 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001125
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001126 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1127 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1128 e = OCD->instmeth_end(); i != e; ++i) {
1129 // Instance methods should always be defined.
1130 InstanceMethods.push_back(GetMethodConstant(*i));
1131 }
1132 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1133 e = OCD->classmeth_end(); i != e; ++i) {
1134 // Class methods should always be defined.
1135 ClassMethods.push_back(GetMethodConstant(*i));
1136 }
1137
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001138 std::vector<llvm::Constant*> Values(7);
1139 Values[0] = GetClassName(OCD->getIdentifier());
1140 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001141 Values[2] =
1142 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1143 ExtName,
1144 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001145 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001146 Values[3] =
1147 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1148 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001149 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001150 if (Category) {
1151 Values[4] =
1152 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1153 Category->protocol_begin(),
1154 Category->protocol_end());
1155 } else {
1156 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1157 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001158 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001159
1160 // If there is no category @interface then there can be no properties.
1161 if (Category) {
1162 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Steve Naroff93983f82009-01-11 12:47:58 +00001163 OCD, Category);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001164 } else {
1165 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1166 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001167
1168 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1169 Values);
1170
1171 llvm::GlobalVariable *GV =
1172 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1173 llvm::GlobalValue::InternalLinkage,
1174 Init,
1175 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1176 &CGM.getModule());
1177 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1178 UsedGlobals.push_back(GV);
1179 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001180}
1181
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001182// FIXME: Get from somewhere?
1183enum ClassFlags {
1184 eClassFlags_Factory = 0x00001,
1185 eClassFlags_Meta = 0x00002,
1186 // <rdr://5142207>
1187 eClassFlags_HasCXXStructors = 0x02000,
1188 eClassFlags_Hidden = 0x20000,
1189 eClassFlags_ABI2_Hidden = 0x00010,
1190 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1191};
1192
1193// <rdr://5142207&4705298&4843145>
1194static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1195 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1196 // FIXME: Support -fvisibility
1197 switch (attr->getVisibility()) {
1198 default:
1199 assert(0 && "Unknown visibility");
1200 return false;
1201 case VisibilityAttr::DefaultVisibility:
1202 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1203 return false;
1204 case VisibilityAttr::HiddenVisibility:
1205 return true;
1206 }
1207 } else {
1208 return false; // FIXME: Support -fvisibility
1209 }
1210}
1211
1212/*
1213 struct _objc_class {
1214 Class isa;
1215 Class super_class;
1216 const char *name;
1217 long version;
1218 long info;
1219 long instance_size;
1220 struct _objc_ivar_list *ivars;
1221 struct _objc_method_list *methods;
1222 struct _objc_cache *cache;
1223 struct _objc_protocol_list *protocols;
1224 // Objective-C 1.0 extensions (<rdr://4585769>)
1225 const char *ivar_layout;
1226 struct _objc_class_ext *ext;
1227 };
1228
1229 See EmitClassExtension();
1230 */
1231void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001232 DefinedSymbols.insert(ID->getIdentifier());
1233
Chris Lattner8ec03f52008-11-24 03:54:41 +00001234 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001235 // FIXME: Gross
1236 ObjCInterfaceDecl *Interface =
1237 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001238 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001239 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001240 Interface->protocol_begin(),
1241 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001242 const llvm::Type *InterfaceTy =
1243 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1244 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001245 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001246
1247 // FIXME: Set CXX-structors flag.
1248 if (IsClassHidden(ID->getClassInterface()))
1249 Flags |= eClassFlags_Hidden;
1250
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001251 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1252 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1253 e = ID->instmeth_end(); i != e; ++i) {
1254 // Instance methods should always be defined.
1255 InstanceMethods.push_back(GetMethodConstant(*i));
1256 }
1257 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1258 e = ID->classmeth_end(); i != e; ++i) {
1259 // Class methods should always be defined.
1260 ClassMethods.push_back(GetMethodConstant(*i));
1261 }
1262
1263 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1264 e = ID->propimpl_end(); i != e; ++i) {
1265 ObjCPropertyImplDecl *PID = *i;
1266
1267 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1268 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1269
1270 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1271 if (llvm::Constant *C = GetMethodConstant(MD))
1272 InstanceMethods.push_back(C);
1273 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1274 if (llvm::Constant *C = GetMethodConstant(MD))
1275 InstanceMethods.push_back(C);
1276 }
1277 }
1278
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001279 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001280 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001281 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001282 // Record a reference to the super class.
1283 LazySymbols.insert(Super->getIdentifier());
1284
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001285 Values[ 1] =
1286 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1287 ObjCTypes.ClassPtrTy);
1288 } else {
1289 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1290 }
1291 Values[ 2] = GetClassName(ID->getIdentifier());
1292 // Version is always 0.
1293 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1294 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1295 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1296 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001297 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001298 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001299 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001300 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001301 // cache is always NULL.
1302 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1303 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001304 // FIXME: Set ivar_layout
1305 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001306 Values[11] = EmitClassExtension(ID);
1307 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1308 Values);
1309
1310 llvm::GlobalVariable *GV =
1311 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1312 llvm::GlobalValue::InternalLinkage,
1313 Init,
1314 std::string("\01L_OBJC_CLASS_")+ClassName,
1315 &CGM.getModule());
1316 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1317 UsedGlobals.push_back(GV);
1318 // FIXME: Why?
1319 GV->setAlignment(32);
1320 DefinedClasses.push_back(GV);
1321}
1322
1323llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1324 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001325 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001326 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001327 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001328 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001329
1330 if (IsClassHidden(ID->getClassInterface()))
1331 Flags |= eClassFlags_Hidden;
1332
1333 std::vector<llvm::Constant*> Values(12);
1334 // The isa for the metaclass is the root of the hierarchy.
1335 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1336 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1337 Root = Super;
1338 Values[ 0] =
1339 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1340 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001341 // The super class for the metaclass is emitted as the name of the
1342 // super class. The runtime fixes this up to point to the
1343 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001344 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1345 Values[ 1] =
1346 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1347 ObjCTypes.ClassPtrTy);
1348 } else {
1349 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1350 }
1351 Values[ 2] = GetClassName(ID->getIdentifier());
1352 // Version is always 0.
1353 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1354 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1355 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1356 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001357 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001358 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001359 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001360 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001361 // cache is always NULL.
1362 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1363 Values[ 9] = Protocols;
1364 // ivar_layout for metaclass is always NULL.
1365 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1366 // The class extension is always unused for metaclasses.
1367 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1368 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1369 Values);
1370
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001371 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001372 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001373
1374 // Check for a forward reference.
1375 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1376 if (GV) {
1377 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1378 "Forward metaclass reference has incorrect type.");
1379 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1380 GV->setInitializer(Init);
1381 } else {
1382 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1383 llvm::GlobalValue::InternalLinkage,
1384 Init, Name,
1385 &CGM.getModule());
1386 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001387 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1388 UsedGlobals.push_back(GV);
1389 // FIXME: Why?
1390 GV->setAlignment(32);
1391
1392 return GV;
1393}
1394
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001395llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001396 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001397
1398 // FIXME: Should we look these up somewhere other than the
1399 // module. Its a bit silly since we only generate these while
1400 // processing an implementation, so exactly one pointer would work
1401 // if know when we entered/exitted an implementation block.
1402
1403 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001404 // Previously, metaclass with internal linkage may have been defined.
1405 // pass 'true' as 2nd argument so it is returned.
1406 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001407 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1408 "Forward metaclass reference has incorrect type.");
1409 return GV;
1410 } else {
1411 // Generate as an external reference to keep a consistent
1412 // module. This will be patched up when we emit the metaclass.
1413 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1414 llvm::GlobalValue::ExternalLinkage,
1415 0,
1416 Name,
1417 &CGM.getModule());
1418 }
1419}
1420
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001421/*
1422 struct objc_class_ext {
1423 uint32_t size;
1424 const char *weak_ivar_layout;
1425 struct _objc_property_list *properties;
1426 };
1427*/
1428llvm::Constant *
1429CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1430 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001431 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001432
1433 std::vector<llvm::Constant*> Values(3);
1434 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001435 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001436 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001437 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Steve Naroff93983f82009-01-11 12:47:58 +00001438 ID, ID->getClassInterface());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001439
1440 // Return null if no extension bits are used.
1441 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1442 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1443
1444 llvm::Constant *Init =
1445 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1446 llvm::GlobalVariable *GV =
1447 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1448 llvm::GlobalValue::InternalLinkage,
1449 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001450 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001451 &CGM.getModule());
1452 // No special section, but goes in llvm.used
1453 UsedGlobals.push_back(GV);
1454
1455 return GV;
1456}
1457
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001458/// countInheritedIvars - count number of ivars in class and its super class(s)
1459///
1460static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1461 int count = 0;
1462 if (!OI)
1463 return 0;
1464 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1465 if (SuperClass)
1466 count += countInheritedIvars(SuperClass);
1467 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1468 E = OI->ivar_end(); I != E; ++I)
1469 ++count;
1470 return count;
1471}
1472
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473/*
1474 struct objc_ivar {
1475 char *ivar_name;
1476 char *ivar_type;
1477 int ivar_offset;
1478 };
1479
1480 struct objc_ivar_list {
1481 int ivar_count;
1482 struct objc_ivar list[count];
1483 };
1484 */
1485llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1486 bool ForClass,
1487 const llvm::Type *InterfaceTy) {
1488 std::vector<llvm::Constant*> Ivars, Ivar(3);
1489
1490 // When emitting the root class GCC emits ivar entries for the
1491 // actual class structure. It is not clear if we need to follow this
1492 // behavior; for now lets try and get away with not doing it. If so,
1493 // the cleanest solution would be to make up an ObjCInterfaceDecl
1494 // for the class.
1495 if (ForClass)
1496 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1497
1498 const llvm::StructLayout *Layout =
1499 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001500 ObjCInterfaceDecl *OID =
1501 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1502 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
1503 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
1504 RecordDecl::field_iterator ifield = RD->field_begin();
1505 while (countSuperClassIvars-- > 0)
1506 ++ifield;
1507 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1508 FieldDecl *Field = *ifield;
1509 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1510 getLLVMFieldNo(Field));
1511 if (Field->getIdentifier())
1512 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1513 else
1514 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001515 std::string TypeStr;
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001516 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001517 Ivar[1] = GetMethodVarType(TypeStr);
1518 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001519 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001520 }
1521
1522 // Return null for empty list.
1523 if (Ivars.empty())
1524 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1525
1526 std::vector<llvm::Constant*> Values(2);
1527 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1528 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1529 Ivars.size());
1530 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1531 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1532
1533 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1534 "\01L_OBJC_INSTANCE_VARIABLES_");
1535 llvm::GlobalVariable *GV =
1536 new llvm::GlobalVariable(Init->getType(), false,
1537 llvm::GlobalValue::InternalLinkage,
1538 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001539 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001540 &CGM.getModule());
1541 if (ForClass) {
1542 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1543 // FIXME: Why is this only here?
1544 GV->setAlignment(32);
1545 } else {
1546 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1547 }
1548 UsedGlobals.push_back(GV);
1549 return llvm::ConstantExpr::getBitCast(GV,
1550 ObjCTypes.IvarListPtrTy);
1551}
1552
1553/*
1554 struct objc_method {
1555 SEL method_name;
1556 char *method_types;
1557 void *method;
1558 };
1559
1560 struct objc_method_list {
1561 struct objc_method_list *obsolete;
1562 int count;
1563 struct objc_method methods_list[count];
1564 };
1565*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001566
1567/// GetMethodConstant - Return a struct objc_method constant for the
1568/// given method if it has been defined. The result is null if the
1569/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001570llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001571 // FIXME: Use DenseMap::lookup
1572 llvm::Function *Fn = MethodDefinitions[MD];
1573 if (!Fn)
1574 return 0;
1575
1576 std::vector<llvm::Constant*> Method(3);
1577 Method[0] =
1578 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1579 ObjCTypes.SelectorPtrTy);
1580 Method[1] = GetMethodVarType(MD);
1581 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1582 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1583}
1584
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001585llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1586 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001587 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001588 // Return null for empty list.
1589 if (Methods.empty())
1590 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1591
1592 std::vector<llvm::Constant*> Values(3);
1593 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1594 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1595 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1596 Methods.size());
1597 Values[2] = llvm::ConstantArray::get(AT, Methods);
1598 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1599
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001600 llvm::GlobalVariable *GV =
1601 new llvm::GlobalVariable(Init->getType(), false,
1602 llvm::GlobalValue::InternalLinkage,
1603 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001604 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001605 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001606 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001607 UsedGlobals.push_back(GV);
1608 return llvm::ConstantExpr::getBitCast(GV,
1609 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001610}
1611
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001612llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001613 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001614 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001615 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001616
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001617 const llvm::FunctionType *MethodTy =
1618 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001619 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001620 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001621 llvm::GlobalValue::InternalLinkage,
1622 Name,
1623 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001624 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001625
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001626 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001627}
1628
1629llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001630 // Abuse this interface function as a place to finalize.
1631 FinishModule();
1632
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001633 return NULL;
1634}
1635
Daniel Dunbar49f66022008-09-24 03:38:44 +00001636llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1637 return ObjCTypes.GetPropertyFn;
1638}
1639
1640llvm::Function *CGObjCMac::GetPropertySetFunction() {
1641 return ObjCTypes.SetPropertyFn;
1642}
1643
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001644llvm::Function *CGObjCMac::EnumerationMutationFunction()
1645{
1646 return ObjCTypes.EnumerationMutationFn;
1647}
1648
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001649/*
1650
1651Objective-C setjmp-longjmp (sjlj) Exception Handling
1652--
1653
1654The basic framework for a @try-catch-finally is as follows:
1655{
1656 objc_exception_data d;
1657 id _rethrow = null;
1658
1659 objc_exception_try_enter(&d);
1660 if (!setjmp(d.jmp_buf)) {
1661 ... try body ...
1662 } else {
1663 // exception path
1664 id _caught = objc_exception_extract(&d);
1665
1666 // enter new try scope for handlers
1667 if (!setjmp(d.jmp_buf)) {
1668 ... match exception and execute catch blocks ...
1669
1670 // fell off end, rethrow.
1671 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001672 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001673 } else {
1674 // exception in catch block
1675 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001676 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001677 }
1678 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001679 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001680
1681finally:
1682 // match either the initial try_enter or the catch try_enter,
1683 // depending on the path followed.
1684 objc_exception_try_exit(&d);
1685finally_no_exit:
1686 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001687 ... dispatch to finally destination ...
1688
1689finally_rethrow:
1690 objc_exception_throw(_rethrow);
1691
1692finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001693}
1694
1695This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001696uses _rethrow to determine if objc_exception_try_exit should be called
1697and if the object should be rethrown. This breaks in the face of
1698throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001699
1700We specialize this framework for a few particular circumstances:
1701
1702 - If there are no catch blocks, then we avoid emitting the second
1703 exception handling context.
1704
1705 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1706 e)) we avoid emitting the code to rethrow an uncaught exception.
1707
1708 - FIXME: If there is no @finally block we can do a few more
1709 simplifications.
1710
1711Rethrows and Jumps-Through-Finally
1712--
1713
1714Support for implicit rethrows and jumping through the finally block is
1715handled by storing the current exception-handling context in
1716ObjCEHStack.
1717
Daniel Dunbar898d5082008-09-30 01:06:03 +00001718In order to implement proper @finally semantics, we support one basic
1719mechanism for jumping through the finally block to an arbitrary
1720destination. Constructs which generate exits from a @try or @catch
1721block use this mechanism to implement the proper semantics by chaining
1722jumps, as necessary.
1723
1724This mechanism works like the one used for indirect goto: we
1725arbitrarily assign an ID to each destination and store the ID for the
1726destination in a variable prior to entering the finally block. At the
1727end of the finally block we simply create a switch to the proper
1728destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001729
1730Code gen for @synchronized(expr) stmt;
1731Effectively generating code for:
1732objc_sync_enter(expr);
1733@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001734*/
1735
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001736void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1737 const Stmt &S) {
1738 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001739 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001740 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1741 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1742 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1743 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001744 llvm::Value *DestCode =
1745 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1746
1747 // Generate jump code. Done here so we can directly add things to
1748 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001749 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001750 llvm::SwitchInst *FinallySwitch =
1751 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1752 FinallyEnd, 10, FinallyJump);
1753
1754 // Push an EH context entry, used for handling rethrows and jumps
1755 // through finally.
1756 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1757 FinallySwitch, DestCode);
1758 CGF.ObjCEHStack.push_back(&EHEntry);
1759
1760 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001761 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1762 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001763 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1764 "_rethrow");
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001765 if (!isTry) {
1766 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001767 llvm::Value *Arg = CGF.EmitScalarExpr(
1768 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1769 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1770 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001771 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001772
1773 // Enter a new try block and call setjmp.
1774 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1775 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1776 "jmpbufarray");
1777 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1778 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1779 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001780
Daniel Dunbar55e87422008-11-11 02:29:29 +00001781 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1782 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001783 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001784 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001785
1786 // Emit the @try block.
1787 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001788 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1789 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001790 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001791
1792 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001793 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001794
1795 // Retrieve the exception object. We may emit multiple blocks but
1796 // nothing can cross this so the value is already in SSA form.
1797 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1798 ExceptionData,
1799 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001800 EHEntry.Exception = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001801 if (!isTry)
1802 {
1803 CGF.Builder.CreateStore(Caught, RethrowPtr);
1804 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1805 }
1806 else if (const ObjCAtCatchStmt* CatchStmt =
1807 cast<ObjCAtTryStmt>(S).getCatchStmts())
1808 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001809 // Enter a new exception try block (in case a @catch block throws
1810 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001811 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001812
Anders Carlsson80f25672008-09-09 17:59:25 +00001813 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1814 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001815 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001816
Daniel Dunbar55e87422008-11-11 02:29:29 +00001817 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1818 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001819 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001820
1821 CGF.EmitBlock(CatchBlock);
1822
Daniel Dunbar55e40722008-09-27 07:03:52 +00001823 // Handle catch list. As a special case we check if everything is
1824 // matched and avoid generating code for falling off the end if
1825 // so.
1826 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001827 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001828 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001829
Anders Carlssondde0a942008-09-11 09:15:33 +00001830 const DeclStmt *CatchParam =
1831 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001832 const VarDecl *VD = 0;
1833 const PointerType *PT = 0;
1834
Anders Carlsson80f25672008-09-09 17:59:25 +00001835 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001836 if (!CatchParam) {
1837 AllMatched = true;
1838 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001839 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001840 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001841
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001842 // catch(id e) always matches.
1843 // FIXME: For the time being we also match id<X>; this should
1844 // be rejected by Sema instead.
1845 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1846 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001847 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001848 }
1849
Daniel Dunbar55e40722008-09-27 07:03:52 +00001850 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001851 if (CatchParam) {
1852 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001853 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001854 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001855 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001856
Anders Carlssondde0a942008-09-11 09:15:33 +00001857 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001858 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001859 break;
1860 }
1861
Daniel Dunbar129271a2008-09-27 07:36:24 +00001862 assert(PT && "Unexpected non-pointer type in @catch");
1863 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001864 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001865 assert(ObjCType && "Catch parameter must have Objective-C type!");
1866
1867 // Check if the @catch block matches the exception object.
1868 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1869
Anders Carlsson80f25672008-09-09 17:59:25 +00001870 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1871 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001872
Daniel Dunbar55e87422008-11-11 02:29:29 +00001873 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001874
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001875 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001876 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001877
1878 // Emit the @catch block.
1879 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001880 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001881 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001882
1883 llvm::Value *Tmp =
1884 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1885 "tmp");
1886 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001887
1888 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001889 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001890
1891 CGF.EmitBlock(NextCatchBlock);
1892 }
1893
Daniel Dunbar55e40722008-09-27 07:03:52 +00001894 if (!AllMatched) {
1895 // None of the handlers caught the exception, so store it to be
1896 // rethrown at the end of the @finally block.
1897 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001898 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001899 }
1900
1901 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001902 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001903 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1904 ExceptionData),
1905 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001906 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001907 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001908 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001909 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001910 }
1911
Daniel Dunbar898d5082008-09-30 01:06:03 +00001912 // Pop the exception-handling stack entry. It is important to do
1913 // this now, because the code in the @finally block is not in this
1914 // context.
1915 CGF.ObjCEHStack.pop_back();
1916
Anders Carlsson80f25672008-09-09 17:59:25 +00001917 // Emit the @finally block.
1918 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001919 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001920
1921 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001922 if (isTry) {
1923 if (const ObjCAtFinallyStmt* FinallyStmt =
1924 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1925 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1926 }
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001927 else {
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001928 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001929 // For @synchronized, call objc_sync_enter(sync.expr)
1930 llvm::Value *Arg = CGF.EmitScalarExpr(
1931 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1932 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1933 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1934 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001935
Daniel Dunbar898d5082008-09-30 01:06:03 +00001936 CGF.EmitBlock(FinallyJump);
1937
1938 CGF.EmitBlock(FinallyRethrow);
1939 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1940 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001941 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001942
1943 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001944}
1945
1946void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001947 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001948 llvm::Value *ExceptionAsObject;
1949
1950 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1951 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1952 ExceptionAsObject =
1953 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1954 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001955 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001956 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001957 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001958 }
1959
1960 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001961 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001962
1963 // Clear the insertion point to indicate we are in unreachable code.
1964 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001965}
1966
Daniel Dunbar898d5082008-09-30 01:06:03 +00001967void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1968 llvm::BasicBlock *Dst,
1969 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001970 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001971 return;
1972
1973 // Find the destination code for this block. We always use 0 for the
1974 // fallthrough block (default destination).
1975 llvm::SwitchInst *SI = E->FinallySwitch;
1976 llvm::ConstantInt *ID;
1977 if (Dst == SI->getDefaultDest()) {
1978 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1979 } else {
1980 ID = SI->findCaseDest(Dst);
1981 if (!ID) {
1982 // No code found, get a new unique one by just using the number
1983 // of switch successors.
1984 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1985 SI->addCase(ID, Dst);
1986 }
1987 }
1988
1989 // Set the destination code and branch.
1990 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001991 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001992}
1993
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001994/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001995/// object: objc_read_weak (id *src)
1996///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001997llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001998 llvm::Value *AddrWeakObj)
1999{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002000 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002001 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002002 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002003 return read_weak;
2004}
2005
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002006/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2007/// objc_assign_weak (id src, id *dst)
2008///
2009void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2010 llvm::Value *src, llvm::Value *dst)
2011{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002012 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2013 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002014 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2015 src, dst, "weakassign");
2016 return;
2017}
2018
Fariborz Jahanian58626502008-11-19 00:59:10 +00002019/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2020/// objc_assign_global (id src, id *dst)
2021///
2022void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2023 llvm::Value *src, llvm::Value *dst)
2024{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002025 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2026 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002027 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2028 src, dst, "globalassign");
2029 return;
2030}
2031
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002032/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2033/// objc_assign_ivar (id src, id *dst)
2034///
2035void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2036 llvm::Value *src, llvm::Value *dst)
2037{
2038 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2039 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2040 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2041 src, dst, "assignivar");
2042 return;
2043}
2044
Fariborz Jahanian58626502008-11-19 00:59:10 +00002045/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2046/// objc_assign_strongCast (id src, id *dst)
2047///
2048void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2049 llvm::Value *src, llvm::Value *dst)
2050{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002051 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2052 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002053 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2054 src, dst, "weakassign");
2055 return;
2056}
2057
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002058/* *** Private Interface *** */
2059
2060/// EmitImageInfo - Emit the image info marker used to encode some module
2061/// level information.
2062///
2063/// See: <rdr://4810609&4810587&4810587>
2064/// struct IMAGE_INFO {
2065/// unsigned version;
2066/// unsigned flags;
2067/// };
2068enum ImageInfoFlags {
2069 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2070 eImageInfo_GarbageCollected = (1 << 1),
2071 eImageInfo_GCOnly = (1 << 2)
2072};
2073
2074void CGObjCMac::EmitImageInfo() {
2075 unsigned version = 0; // Version is unused?
2076 unsigned flags = 0;
2077
2078 // FIXME: Fix and continue?
2079 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2080 flags |= eImageInfo_GarbageCollected;
2081 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2082 flags |= eImageInfo_GCOnly;
2083
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002084 // Emitted as int[2];
2085 llvm::Constant *values[2] = {
2086 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2087 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2088 };
2089 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002090 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002091 new llvm::GlobalVariable(AT, true,
2092 llvm::GlobalValue::InternalLinkage,
2093 llvm::ConstantArray::get(AT, values, 2),
2094 "\01L_OBJC_IMAGE_INFO",
2095 &CGM.getModule());
2096
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002097 if (ObjCABI == 1) {
2098 GV->setSection("__OBJC, __image_info,regular");
2099 } else {
2100 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2101 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002102
2103 UsedGlobals.push_back(GV);
2104}
2105
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002106
2107// struct objc_module {
2108// unsigned long version;
2109// unsigned long size;
2110// const char *name;
2111// Symtab symtab;
2112// };
2113
2114// FIXME: Get from somewhere
2115static const int ModuleVersion = 7;
2116
2117void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002118 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002119
2120 std::vector<llvm::Constant*> Values(4);
2121 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2122 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002123 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002124 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002125 Values[3] = EmitModuleSymbols();
2126
2127 llvm::GlobalVariable *GV =
2128 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2129 llvm::GlobalValue::InternalLinkage,
2130 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2131 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002132 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002133 &CGM.getModule());
2134 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2135 UsedGlobals.push_back(GV);
2136}
2137
2138llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002139 unsigned NumClasses = DefinedClasses.size();
2140 unsigned NumCategories = DefinedCategories.size();
2141
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002142 // Return null if no symbols were defined.
2143 if (!NumClasses && !NumCategories)
2144 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2145
2146 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002147 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2148 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2149 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2150 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2151
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002152 // The runtime expects exactly the list of defined classes followed
2153 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002154 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002155 for (unsigned i=0; i<NumClasses; i++)
2156 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2157 ObjCTypes.Int8PtrTy);
2158 for (unsigned i=0; i<NumCategories; i++)
2159 Symbols[NumClasses + i] =
2160 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2161 ObjCTypes.Int8PtrTy);
2162
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002163 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002164 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002165 NumClasses + NumCategories),
2166 Symbols);
2167
2168 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2169
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002170 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002171 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002172 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002173 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002174 "\01L_OBJC_SYMBOLS",
2175 &CGM.getModule());
2176 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2177 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002178 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2179}
2180
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002181llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002182 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002183 LazySymbols.insert(ID->getIdentifier());
2184
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002185 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2186
2187 if (!Entry) {
2188 llvm::Constant *Casted =
2189 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2190 ObjCTypes.ClassPtrTy);
2191 Entry =
2192 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2193 llvm::GlobalValue::InternalLinkage,
2194 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2195 &CGM.getModule());
2196 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2197 UsedGlobals.push_back(Entry);
2198 }
2199
2200 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002201}
2202
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002203llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002204 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2205
2206 if (!Entry) {
2207 llvm::Constant *Casted =
2208 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2209 ObjCTypes.SelectorPtrTy);
2210 Entry =
2211 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2212 llvm::GlobalValue::InternalLinkage,
2213 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2214 &CGM.getModule());
2215 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2216 UsedGlobals.push_back(Entry);
2217 }
2218
2219 return Builder.CreateLoad(Entry, false, "tmp");
2220}
2221
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002222llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002223 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002224
2225 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002226 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002227 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002228 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002229 llvm::GlobalValue::InternalLinkage,
2230 C, "\01L_OBJC_CLASS_NAME_",
2231 &CGM.getModule());
2232 Entry->setSection("__TEXT,__cstring,cstring_literals");
2233 UsedGlobals.push_back(Entry);
2234 }
2235
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002236 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002237}
2238
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002239llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002240 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2241
2242 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002243 // FIXME: Avoid std::string copying.
2244 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002245 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002246 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002247 llvm::GlobalValue::InternalLinkage,
2248 C, "\01L_OBJC_METH_VAR_NAME_",
2249 &CGM.getModule());
2250 Entry->setSection("__TEXT,__cstring,cstring_literals");
2251 UsedGlobals.push_back(Entry);
2252 }
2253
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002254 return getConstantGEP(Entry, 0, 0);
2255}
2256
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002257// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002258llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002259 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2260}
2261
2262// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002263llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002264 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2265}
2266
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002267llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002268 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002269
2270 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002271 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002272 Entry =
2273 new llvm::GlobalVariable(C->getType(), false,
2274 llvm::GlobalValue::InternalLinkage,
2275 C, "\01L_OBJC_METH_VAR_TYPE_",
2276 &CGM.getModule());
2277 Entry->setSection("__TEXT,__cstring,cstring_literals");
2278 UsedGlobals.push_back(Entry);
2279 }
2280
2281 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002282}
2283
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002284// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002285llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002286 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002287 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2288 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002289 return GetMethodVarType(TypeStr);
2290}
2291
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002292// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002293llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002294 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2295
2296 if (!Entry) {
2297 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2298 Entry =
2299 new llvm::GlobalVariable(C->getType(), false,
2300 llvm::GlobalValue::InternalLinkage,
2301 C, "\01L_OBJC_PROP_NAME_ATTR_",
2302 &CGM.getModule());
2303 Entry->setSection("__TEXT,__cstring,cstring_literals");
2304 UsedGlobals.push_back(Entry);
2305 }
2306
2307 return getConstantGEP(Entry, 0, 0);
2308}
2309
2310// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002311// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002312llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002313 const Decl *Container) {
2314 std::string TypeStr;
2315 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002316 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2317}
2318
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002319void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2320 const ObjCContainerDecl *CD,
2321 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002322 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002323 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002324 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002325 assert (CD && "Missing container decl in GetNameForMethod");
2326 NameOut += CD->getNameAsString();
Chris Lattner077bf5e2008-11-24 03:33:13 +00002327 NameOut += ' ';
2328 NameOut += D->getSelector().getAsString();
2329 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002330}
2331
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002332void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002333 EmitModuleInfo();
2334
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002335 // Emit the dummy bodies for any protocols which were referenced but
2336 // never defined.
2337 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2338 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2339 if (i->second->hasInitializer())
2340 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002341
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002342 std::vector<llvm::Constant*> Values(5);
2343 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2344 Values[1] = GetClassName(i->first);
2345 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2346 Values[3] = Values[4] =
2347 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2348 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2349 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2350 Values));
2351 }
2352
2353 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002354 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002355 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002356 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002357 }
2358
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002359 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002360 llvm::GlobalValue *GV =
2361 new llvm::GlobalVariable(AT, false,
2362 llvm::GlobalValue::AppendingLinkage,
2363 llvm::ConstantArray::get(AT, Used),
2364 "llvm.used",
2365 &CGM.getModule());
2366
2367 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002368
2369 // Add assembler directives to add lazy undefined symbol references
2370 // for classes which are referenced but not defined. This is
2371 // important for correct linker interaction.
2372
2373 // FIXME: Uh, this isn't particularly portable.
2374 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002375
2376 if (!CGM.getModule().getModuleInlineAsm().empty())
2377 s << "\n";
2378
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002379 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2380 e = LazySymbols.end(); i != e; ++i) {
2381 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2382 }
2383 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2384 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002385 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002386 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2387 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002388
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002389 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002390}
2391
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002392CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002393 : CGObjCCommonMac(cgm),
2394 ObjCTypes(cgm)
2395{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002396 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002397 ObjCABI = 2;
2398}
2399
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002400/* *** */
2401
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002402ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2403: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002404{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002405 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2406 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002407
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002408 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002409 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002410 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002411 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2412
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002413 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002414 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002415 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002416
2417 // FIXME: It would be nice to unify this with the opaque type, so
2418 // that the IR comes out a bit cleaner.
2419 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2420 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002421
2422 // I'm not sure I like this. The implicit coordination is a bit
2423 // gross. We should solve this in a reasonable fashion because this
2424 // is a pretty common task (match some runtime data structure with
2425 // an LLVM data structure).
2426
2427 // FIXME: This is leaked.
2428 // FIXME: Merge with rewriter code?
2429
2430 // struct _objc_super {
2431 // id self;
2432 // Class cls;
2433 // }
2434 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2435 SourceLocation(),
2436 &Ctx.Idents.get("_objc_super"));
2437 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2438 Ctx.getObjCIdType(), 0, false));
2439 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2440 Ctx.getObjCClassType(), 0, false));
2441 RD->completeDefinition(Ctx);
2442
2443 SuperCTy = Ctx.getTagDeclType(RD);
2444 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2445
2446 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002447 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2448
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002449 // struct _prop_t {
2450 // char *name;
2451 // char *attributes;
2452 // }
2453 PropertyTy = llvm::StructType::get(Int8PtrTy,
2454 Int8PtrTy,
2455 NULL);
2456 CGM.getModule().addTypeName("struct._prop_t",
2457 PropertyTy);
2458
2459 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002460 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002461 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002462 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002463 // }
2464 PropertyListTy = llvm::StructType::get(IntTy,
2465 IntTy,
2466 llvm::ArrayType::get(PropertyTy, 0),
2467 NULL);
2468 CGM.getModule().addTypeName("struct._prop_list_t",
2469 PropertyListTy);
2470 // struct _prop_list_t *
2471 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2472
2473 // struct _objc_method {
2474 // SEL _cmd;
2475 // char *method_type;
2476 // char *_imp;
2477 // }
2478 MethodTy = llvm::StructType::get(SelectorPtrTy,
2479 Int8PtrTy,
2480 Int8PtrTy,
2481 NULL);
2482 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002483
2484 // struct _objc_cache *
2485 CacheTy = llvm::OpaqueType::get();
2486 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2487 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002488
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002489 // Property manipulation functions.
2490
2491 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
2492 std::vector<const llvm::Type*> Params;
2493 Params.push_back(ObjectPtrTy);
2494 Params.push_back(SelectorPtrTy);
2495 Params.push_back(LongTy);
2496 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2497 GetPropertyFn =
2498 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2499 Params,
2500 false),
2501 "objc_getProperty");
2502
2503 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2504 Params.clear();
2505 Params.push_back(ObjectPtrTy);
2506 Params.push_back(SelectorPtrTy);
2507 Params.push_back(LongTy);
2508 Params.push_back(ObjectPtrTy);
2509 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2510 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2511 SetPropertyFn =
2512 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2513 Params,
2514 false),
2515 "objc_setProperty");
2516 // Enumeration mutation.
2517
2518 Params.clear();
2519 Params.push_back(ObjectPtrTy);
2520 EnumerationMutationFn =
2521 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2522 Params,
2523 false),
2524 "objc_enumerationMutation");
2525
2526 // gc's API
2527 // id objc_read_weak (id *)
2528 Params.clear();
2529 Params.push_back(PtrObjectPtrTy);
2530 GcReadWeakFn =
2531 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2532 Params,
2533 false),
2534 "objc_read_weak");
2535 // id objc_assign_weak (id, id *)
2536 Params.clear();
2537 Params.push_back(ObjectPtrTy);
2538 Params.push_back(PtrObjectPtrTy);
2539 GcAssignWeakFn =
2540 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2541 Params,
2542 false),
2543 "objc_assign_weak");
2544 GcAssignGlobalFn =
2545 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2546 Params,
2547 false),
2548 "objc_assign_global");
2549 GcAssignIvarFn =
2550 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2551 Params,
2552 false),
2553 "objc_assign_ivar");
2554 GcAssignStrongCastFn =
2555 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2556 Params,
2557 false),
2558 "objc_assign_strongCast");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002559}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002560
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002561ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2562 : ObjCCommonTypesHelper(cgm)
2563{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002564 // struct _objc_method_description {
2565 // SEL name;
2566 // char *types;
2567 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002568 MethodDescriptionTy =
2569 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002570 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002571 NULL);
2572 CGM.getModule().addTypeName("struct._objc_method_description",
2573 MethodDescriptionTy);
2574
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002575 // struct _objc_method_description_list {
2576 // int count;
2577 // struct _objc_method_description[1];
2578 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002579 MethodDescriptionListTy =
2580 llvm::StructType::get(IntTy,
2581 llvm::ArrayType::get(MethodDescriptionTy, 0),
2582 NULL);
2583 CGM.getModule().addTypeName("struct._objc_method_description_list",
2584 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002585
2586 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002587 MethodDescriptionListPtrTy =
2588 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2589
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002590 // Protocol description structures
2591
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002592 // struct _objc_protocol_extension {
2593 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2594 // struct _objc_method_description_list *optional_instance_methods;
2595 // struct _objc_method_description_list *optional_class_methods;
2596 // struct _objc_property_list *instance_properties;
2597 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002598 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002599 llvm::StructType::get(IntTy,
2600 MethodDescriptionListPtrTy,
2601 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002602 PropertyListPtrTy,
2603 NULL);
2604 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2605 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002606
2607 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002608 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2609
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002610 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002611
2612 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2613 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2614
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002615 const llvm::Type *T =
2616 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2617 LongTy,
2618 llvm::ArrayType::get(ProtocolTyHolder, 0),
2619 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002620 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2621
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002622 // struct _objc_protocol {
2623 // struct _objc_protocol_extension *isa;
2624 // char *protocol_name;
2625 // struct _objc_protocol **_objc_protocol_list;
2626 // struct _objc_method_description_list *instance_methods;
2627 // struct _objc_method_description_list *class_methods;
2628 // }
2629 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002630 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002631 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2632 MethodDescriptionListPtrTy,
2633 MethodDescriptionListPtrTy,
2634 NULL);
2635 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2636
2637 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2638 CGM.getModule().addTypeName("struct._objc_protocol_list",
2639 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002640 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002641 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2642
2643 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002644 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002645 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002646
2647 // Class description structures
2648
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002649 // struct _objc_ivar {
2650 // char *ivar_name;
2651 // char *ivar_type;
2652 // int ivar_offset;
2653 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002654 IvarTy = llvm::StructType::get(Int8PtrTy,
2655 Int8PtrTy,
2656 IntTy,
2657 NULL);
2658 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2659
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002660 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002661 IvarListTy = llvm::OpaqueType::get();
2662 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2663 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2664
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002665 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002666 MethodListTy = llvm::OpaqueType::get();
2667 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2668 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2669
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002670 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002671 ClassExtensionTy =
2672 llvm::StructType::get(IntTy,
2673 Int8PtrTy,
2674 PropertyListPtrTy,
2675 NULL);
2676 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2677 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2678
2679 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2680
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002681 // struct _objc_class {
2682 // Class isa;
2683 // Class super_class;
2684 // char *name;
2685 // long version;
2686 // long info;
2687 // long instance_size;
2688 // struct _objc_ivar_list *ivars;
2689 // struct _objc_method_list *methods;
2690 // struct _objc_cache *cache;
2691 // struct _objc_protocol_list *protocols;
2692 // char *ivar_layout;
2693 // struct _objc_class_ext *ext;
2694 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002695 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2696 llvm::PointerType::getUnqual(ClassTyHolder),
2697 Int8PtrTy,
2698 LongTy,
2699 LongTy,
2700 LongTy,
2701 IvarListPtrTy,
2702 MethodListPtrTy,
2703 CachePtrTy,
2704 ProtocolListPtrTy,
2705 Int8PtrTy,
2706 ClassExtensionPtrTy,
2707 NULL);
2708 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2709
2710 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2711 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2712 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2713
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002714 // struct _objc_category {
2715 // char *category_name;
2716 // char *class_name;
2717 // struct _objc_method_list *instance_method;
2718 // struct _objc_method_list *class_method;
2719 // uint32_t size; // sizeof(struct _objc_category)
2720 // struct _objc_property_list *instance_properties;// category's @property
2721 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002722 CategoryTy = llvm::StructType::get(Int8PtrTy,
2723 Int8PtrTy,
2724 MethodListPtrTy,
2725 MethodListPtrTy,
2726 ProtocolListPtrTy,
2727 IntTy,
2728 PropertyListPtrTy,
2729 NULL);
2730 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2731
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002732 // Global metadata structures
2733
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002734 // struct _objc_symtab {
2735 // long sel_ref_cnt;
2736 // SEL *refs;
2737 // short cls_def_cnt;
2738 // short cat_def_cnt;
2739 // char *defs[cls_def_cnt + cat_def_cnt];
2740 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002741 SymtabTy = llvm::StructType::get(LongTy,
2742 SelectorPtrTy,
2743 ShortTy,
2744 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002745 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002746 NULL);
2747 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2748 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2749
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002750 // struct _objc_module {
2751 // long version;
2752 // long size; // sizeof(struct _objc_module)
2753 // char *name;
2754 // struct _objc_symtab* symtab;
2755 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002756 ModuleTy =
2757 llvm::StructType::get(LongTy,
2758 LongTy,
2759 Int8PtrTy,
2760 SymtabPtrTy,
2761 NULL);
2762 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002763
Daniel Dunbar49f66022008-09-24 03:38:44 +00002764 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002765
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002766 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002767 std::vector<const llvm::Type*> Params;
2768 Params.push_back(ObjectPtrTy);
2769 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002770 MessageSendFn =
2771 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2772 Params,
2773 true),
2774 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002775
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002776 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002777 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002778 Params.push_back(ObjectPtrTy);
2779 Params.push_back(SelectorPtrTy);
2780 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002781 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2782 Params,
2783 true),
2784 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002785
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002786 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00002787 Params.clear();
2788 Params.push_back(ObjectPtrTy);
2789 Params.push_back(SelectorPtrTy);
2790 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002791 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00002792 MessageSendFpretFn =
2793 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2794 Params,
2795 true),
2796 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002797
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002798 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002799 Params.clear();
2800 Params.push_back(SuperPtrTy);
2801 Params.push_back(SelectorPtrTy);
2802 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002803 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2804 Params,
2805 true),
2806 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002807
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002808 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
2809 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002810 Params.clear();
2811 Params.push_back(Int8PtrTy);
2812 Params.push_back(SuperPtrTy);
2813 Params.push_back(SelectorPtrTy);
2814 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002815 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2816 Params,
2817 true),
2818 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002819
2820 // There is no objc_msgSendSuper_fpret? How can that work?
2821 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002822
Anders Carlsson124526b2008-09-09 10:10:21 +00002823 // FIXME: This is the size of the setjmp buffer and should be
2824 // target specific. 18 is what's used on 32-bit X86.
2825 uint64_t SetJmpBufferSize = 18;
2826
2827 // Exceptions
2828 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002829 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002830
2831 ExceptionDataTy =
2832 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2833 SetJmpBufferSize),
2834 StackPtrTy, NULL);
2835 CGM.getModule().addTypeName("struct._objc_exception_data",
2836 ExceptionDataTy);
2837
2838 Params.clear();
2839 Params.push_back(ObjectPtrTy);
2840 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002841 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2842 Params,
2843 false),
2844 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002845
2846 Params.clear();
2847 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2848 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002849 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2850 Params,
2851 false),
2852 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002853 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002854 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2855 Params,
2856 false),
2857 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002858 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002859 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2860 Params,
2861 false),
2862 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002863
2864 Params.clear();
2865 Params.push_back(ClassPtrTy);
2866 Params.push_back(ObjectPtrTy);
2867 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002868 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2869 Params,
2870 false),
2871 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002872
2873 // synchronized APIs
2874 // void objc_sync_enter (id)
2875 Params.clear();
2876 Params.push_back(ObjectPtrTy);
2877 SyncEnterFn =
2878 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2879 Params,
2880 false),
2881 "objc_sync_enter");
2882 // void objc_sync_exit (id)
2883 SyncExitFn =
2884 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2885 Params,
2886 false),
2887 "objc_sync_exit");
2888
Anders Carlsson124526b2008-09-09 10:10:21 +00002889
2890 Params.clear();
2891 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2892 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002893 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2894 Params,
2895 false),
2896 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002897
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002898}
2899
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002900ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002901: ObjCCommonTypesHelper(cgm)
2902{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002903 // struct _method_list_t {
2904 // uint32_t entsize; // sizeof(struct _objc_method)
2905 // uint32_t method_count;
2906 // struct _objc_method method_list[method_count];
2907 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002908 MethodListnfABITy = llvm::StructType::get(IntTy,
2909 IntTy,
2910 llvm::ArrayType::get(MethodTy, 0),
2911 NULL);
2912 CGM.getModule().addTypeName("struct.__method_list_t",
2913 MethodListnfABITy);
2914 // struct method_list_t *
2915 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002916
2917 // struct _protocol_t {
2918 // id isa; // NULL
2919 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002920 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002921 // const struct method_list_t * const instance_methods;
2922 // const struct method_list_t * const class_methods;
2923 // const struct method_list_t *optionalInstanceMethods;
2924 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002925 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002926 // const uint32_t size; // sizeof(struct _protocol_t)
2927 // const uint32_t flags; // = 0
2928 // }
2929
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002930 // Holder for struct _protocol_list_t *
2931 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2932
2933 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
2934 Int8PtrTy,
2935 llvm::PointerType::getUnqual(
2936 ProtocolListTyHolder),
2937 MethodListnfABIPtrTy,
2938 MethodListnfABIPtrTy,
2939 MethodListnfABIPtrTy,
2940 MethodListnfABIPtrTy,
2941 PropertyListPtrTy,
2942 IntTy,
2943 IntTy,
2944 NULL);
2945 CGM.getModule().addTypeName("struct._protocol_t",
2946 ProtocolnfABITy);
2947
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002948 // struct _objc_protocol_list {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002949 // long protocol_count; // Note, this is 32/64 bit
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002950 // struct _protocol_t[protocol_count];
2951 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002952 ProtocolListnfABITy = llvm::StructType::get(LongTy,
2953 llvm::ArrayType::get(
2954 ProtocolnfABITy, 0),
2955 NULL);
2956 CGM.getModule().addTypeName("struct._objc_protocol_list",
2957 ProtocolListnfABITy);
2958
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002959 // struct _objc_protocol_list*
2960 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002961
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002962 // FIXME! Is this doing the right thing?
2963 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
2964 ProtocolListnfABIPtrTy);
2965
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002966 // struct _ivar_t {
2967 // unsigned long int *offset; // pointer to ivar offset location
2968 // char *name;
2969 // char *type;
2970 // uint32_t alignment;
2971 // uint32_t size;
2972 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002973 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
2974 Int8PtrTy,
2975 Int8PtrTy,
2976 IntTy,
2977 IntTy,
2978 NULL);
2979 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
2980
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002981 // struct _ivar_list_t {
2982 // uint32 entsize; // sizeof(struct _ivar_t)
2983 // uint32 count;
2984 // struct _iver_t list[count];
2985 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002986 IvarListnfABITy = llvm::StructType::get(IntTy,
2987 IntTy,
2988 llvm::ArrayType::get(
2989 IvarnfABITy, 0),
2990 NULL);
2991 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
2992
2993 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002994
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002995 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002996 // uint32_t const flags;
2997 // uint32_t const instanceStart;
2998 // uint32_t const instanceSize;
2999 // uint32_t const reserved; // only when building for 64bit targets
3000 // const uint8_t * const ivarLayout;
3001 // const char *const name;
3002 // const struct _method_list_t * const baseMethods;
3003 // const struct _objc_protocol_list *const baseProtocols;
3004 // const struct _ivar_list_t *const ivars;
3005 // const uint8_t * const weakIvarLayout;
3006 // const struct _prop_list_t * const properties;
3007 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003008
3009 // FIXME. Add 'reserved' field in 64bit abi mode!
3010 ClassRonfABITy = llvm::StructType::get(IntTy,
3011 IntTy,
3012 IntTy,
3013 Int8PtrTy,
3014 Int8PtrTy,
3015 MethodListnfABIPtrTy,
3016 ProtocolListnfABIPtrTy,
3017 IvarListnfABIPtrTy,
3018 Int8PtrTy,
3019 PropertyListPtrTy,
3020 NULL);
3021 CGM.getModule().addTypeName("struct._class_ro_t",
3022 ClassRonfABITy);
3023
3024 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3025 std::vector<const llvm::Type*> Params;
3026 Params.push_back(ObjectPtrTy);
3027 Params.push_back(SelectorPtrTy);
3028 ImpnfABITy = llvm::PointerType::getUnqual(
3029 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3030
3031 // struct _class_t {
3032 // struct _class_t *isa;
3033 // struct _class_t * const superclass;
3034 // void *cache;
3035 // IMP *vtable;
3036 // struct class_ro_t *ro;
3037 // }
3038
3039 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3040 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3041 llvm::PointerType::getUnqual(ClassTyHolder),
3042 CachePtrTy,
3043 llvm::PointerType::getUnqual(ImpnfABITy),
3044 llvm::PointerType::getUnqual(
3045 ClassRonfABITy),
3046 NULL);
3047 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3048
3049 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3050 ClassnfABITy);
3051
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003052 // LLVM for struct _class_t *
3053 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3054
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003055 // struct _category_t {
3056 // const char * const name;
3057 // struct _class_t *const cls;
3058 // const struct _method_list_t * const instance_methods;
3059 // const struct _method_list_t * const class_methods;
3060 // const struct _protocol_list_t * const protocols;
3061 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003062 // }
3063 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003064 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003065 MethodListnfABIPtrTy,
3066 MethodListnfABIPtrTy,
3067 ProtocolListnfABIPtrTy,
3068 PropertyListPtrTy,
3069 NULL);
3070 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
3071
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003072}
3073
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003074llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3075 FinishNonFragileABIModule();
3076
3077 return NULL;
3078}
3079
3080void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3081 // nonfragile abi has no module definition.
3082 std::vector<llvm::Constant*> Used;
3083 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3084 e = UsedGlobals.end(); i != e; ++i) {
3085 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3086 }
3087
3088 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3089 llvm::GlobalValue *GV =
3090 new llvm::GlobalVariable(AT, false,
3091 llvm::GlobalValue::AppendingLinkage,
3092 llvm::ConstantArray::get(AT, Used),
3093 "llvm.used",
3094 &CGM.getModule());
3095
3096 GV->setSection("llvm.metadata");
3097
3098}
3099
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003100// Metadata flags
3101enum MetaDataDlags {
3102 CLS = 0x0,
3103 CLS_META = 0x1,
3104 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003105 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003106 CLS_EXCEPTION = 0x20
3107};
3108/// BuildClassRoTInitializer - generate meta-data for:
3109/// struct _class_ro_t {
3110/// uint32_t const flags;
3111/// uint32_t const instanceStart;
3112/// uint32_t const instanceSize;
3113/// uint32_t const reserved; // only when building for 64bit targets
3114/// const uint8_t * const ivarLayout;
3115/// const char *const name;
3116/// const struct _method_list_t * const baseMethods;
3117/// const struct _objc_protocol_list *const baseProtocols;
3118/// const struct _ivar_list_t *const ivars;
3119/// const uint8_t * const weakIvarLayout;
3120/// const struct _prop_list_t * const properties;
3121/// }
3122///
3123llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3124 unsigned flags,
3125 unsigned InstanceStart,
3126 unsigned InstanceSize,
3127 const ObjCImplementationDecl *ID) {
3128 std::string ClassName = ID->getNameAsString();
3129 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3130 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3131 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3132 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3133 // FIXME. For 64bit targets add 0 here.
3134 Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3135 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003136 // const struct _method_list_t * const baseMethods;
3137 std::vector<llvm::Constant*> Methods;
3138 std::string MethodListName("\01l_OBJC_$_");
3139 if (flags & CLS_META) {
3140 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3141 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3142 e = ID->classmeth_end(); i != e; ++i) {
3143 // Class methods should always be defined.
3144 Methods.push_back(GetMethodConstant(*i));
3145 }
3146 } else {
3147 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3148 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3149 e = ID->instmeth_end(); i != e; ++i) {
3150 // Instance methods should always be defined.
3151 Methods.push_back(GetMethodConstant(*i));
3152 }
3153 }
3154 // FIXME. Section may always be .data
3155 Values[ 5] = EmitMethodList(MethodListName,
3156 ".section __DATA,__data,regular,no_dead_strip", Methods);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003157 Values[ 6] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3158 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3159 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3160 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3161 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3162 Values);
3163 llvm::GlobalVariable *CLASS_RO_GV =
3164 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3165 llvm::GlobalValue::InternalLinkage,
3166 Init,
3167 (flags & CLS_META) ?
3168 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3169 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3170 &CGM.getModule());
3171 CLASS_RO_GV->setSection(".section __DATA,__data,regular,no_dead_strip");
3172 UsedGlobals.push_back(CLASS_RO_GV);
3173 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003174
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003175}
3176
3177/// BuildClassMetaData - This routine defines that to-level meta-data
3178/// for the given ClassName for:
3179/// struct _class_t {
3180/// struct _class_t *isa;
3181/// struct _class_t * const superclass;
3182/// void *cache;
3183/// IMP *vtable;
3184/// struct class_ro_t *ro;
3185/// }
3186///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003187llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3188 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003189 llvm::Constant *IsAGV,
3190 llvm::Constant *SuperClassGV,
3191 llvm::Constant *ClassRoGV) {
3192 std::vector<llvm::Constant*> Values(5);
3193 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003194 Values[1] = SuperClassGV
3195 ? SuperClassGV
3196 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003197 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3198 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3199 Values[4] = ClassRoGV; // &CLASS_RO_GV
3200 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3201 Values);
3202 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(ClassName);
3203 if (GV)
3204 GV->setInitializer(Init);
3205 else
3206 GV =
3207 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3208 llvm::GlobalValue::ExternalLinkage,
3209 Init,
3210 ClassName,
3211 &CGM.getModule());
3212 GV->setSection(".section __DATA,__data,regular,no_dead_strip");
3213 UsedGlobals.push_back(GV);
3214 // FIXME! why?
3215 GV->setAlignment(32);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003216 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003217}
3218
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003219void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3220 std::string ClassName = ID->getNameAsString();
3221 if (!ObjCEmptyCacheVar) {
3222 ObjCEmptyCacheVar = new llvm::GlobalVariable(
3223 ObjCTypes.CachePtrTy,
3224 false,
3225 llvm::GlobalValue::ExternalLinkage,
3226 0,
3227 "\01_objc_empty_cache",
3228 &CGM.getModule());
3229 UsedGlobals.push_back(ObjCEmptyCacheVar);
3230
3231 ObjCEmptyVtableVar = new llvm::GlobalVariable(
3232 llvm::PointerType::getUnqual(
3233 ObjCTypes.ImpnfABITy),
3234 false,
3235 llvm::GlobalValue::ExternalLinkage,
3236 0,
3237 "\01_objc_empty_vtable",
3238 &CGM.getModule());
3239 UsedGlobals.push_back(ObjCEmptyVtableVar);
3240 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003241 assert(ID->getClassInterface() &&
3242 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003243 uint32_t InstanceStart =
3244 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3245 uint32_t InstanceSize = InstanceStart;
3246 uint32_t flags = CLS_META;
3247 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3248 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003249
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003250 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003251
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003252 if (IsClassHidden(ID->getClassInterface()))
3253 flags |= OBJC2_CLS_HIDDEN;
3254 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003255 // class is root
3256 flags |= CLS_ROOT;
3257 std::string SuperClassName = ObjCClassName + ClassName;
3258 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3259 if (!SuperClassGV)
3260 SuperClassGV =
3261 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3262 llvm::GlobalValue::ExternalLinkage,
3263 0,
3264 SuperClassName,
3265 &CGM.getModule());
3266 UsedGlobals.push_back(SuperClassGV);
3267 std::string IsAClassName = ObjCMetaClassName + ClassName;
3268 IsAGV = CGM.getModule().getGlobalVariable(IsAClassName);
3269 if (!IsAGV)
3270 IsAGV =
3271 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3272 llvm::GlobalValue::ExternalLinkage,
3273 0,
3274 IsAClassName,
3275 &CGM.getModule());
3276 UsedGlobals.push_back(IsAGV);
3277 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003278 // Has a root. Current class is not a root.
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003279 std::string RootClassName =
3280 ID->getClassInterface()->getSuperClass()->getNameAsString();
3281 std::string SuperClassName = ObjCMetaClassName + RootClassName;
3282 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3283 if (!SuperClassGV)
3284 SuperClassGV =
3285 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3286 llvm::GlobalValue::ExternalLinkage,
3287 0,
3288 SuperClassName,
3289 &CGM.getModule());
3290 UsedGlobals.push_back(SuperClassGV);
3291 IsAGV = SuperClassGV;
3292 }
3293 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3294 InstanceStart,
3295 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003296 std::string TClassName = ObjCMetaClassName + ClassName;
3297 llvm::GlobalVariable *MetaTClass =
3298 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV);
3299
3300 // Metadata for the class
3301 flags = CLS;
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003302 if (IsClassHidden(ID->getClassInterface()))
3303 flags |= OBJC2_CLS_HIDDEN;
3304 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003305 flags |= CLS_ROOT;
3306 SuperClassGV = 0;
3307 }
3308 else {
3309 // Has a root. Current class is not a root.
3310 std::string RootClassName =
3311 ID->getClassInterface()->getSuperClass()->getNameAsString();
3312 std::string SuperClassName = ObjCClassName + RootClassName;
3313 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3314 if (!SuperClassGV)
3315 SuperClassGV =
3316 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3317 llvm::GlobalValue::ExternalLinkage,
3318 0,
3319 SuperClassName,
3320 &CGM.getModule());
3321 UsedGlobals.push_back(SuperClassGV);
3322
3323 }
3324
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003325 InstanceStart = InstanceSize = 0;
3326 if (ObjCInterfaceDecl *OID =
3327 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3328 // FIXME. Share this with the one in EmitIvarList.
3329 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3330 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3331 RecordDecl::field_iterator firstField = RD->field_begin();
3332 RecordDecl::field_iterator lastField = RD->field_end();
3333
3334 while (countSuperClassIvars-- > 0) {
3335 lastField = firstField;
3336 ++firstField;
3337 }
3338
3339 for (RecordDecl::field_iterator e = RD->field_end(),
3340 ifield = firstField; ifield != e; ++ifield)
3341 lastField = ifield;
3342
3343 const llvm::Type *InterfaceTy =
3344 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
3345 const llvm::StructLayout *Layout =
3346 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
3347
3348 if (lastField != RD->field_end()) {
3349 FieldDecl *Field = *lastField;
3350 const llvm::Type *FieldTy =
3351 CGM.getTypes().ConvertTypeForMem(Field->getType());
3352 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3353 InstanceSize = Layout->getElementOffset(
3354 CGM.getTypes().getLLVMFieldNo(Field)) +
3355 Size;
3356 if (firstField == RD->field_end())
3357 InstanceStart = InstanceSize;
3358 else
3359 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3360 getLLVMFieldNo(*firstField));
3361 }
3362 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003363 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003364 InstanceStart,
3365 InstanceSize,
3366 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003367
3368 TClassName = ObjCClassName + ClassName;
3369 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003370}
3371
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003372/// GenerateCategory - Build metadata for a category implementation.
3373/// struct _category_t {
3374/// const char * const name;
3375/// struct _class_t *const cls;
3376/// const struct _method_list_t * const instance_methods;
3377/// const struct _method_list_t * const class_methods;
3378/// const struct _protocol_list_t * const protocols;
3379/// const struct _prop_list_t * const properties;
3380/// }
3381///
3382void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3383{
3384 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003385 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3386 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003387 "_$_" + OCD->getNameAsString());
3388 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3389
3390 std::vector<llvm::Constant*> Values(6);
3391 Values[0] = GetClassName(OCD->getIdentifier());
3392 // meta-class entry symbol
3393 llvm::GlobalVariable *ClassGV =
3394 CGM.getModule().getGlobalVariable(ExtClassName);
3395 if (!ClassGV)
3396 ClassGV =
3397 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3398 llvm::GlobalValue::ExternalLinkage,
3399 0,
3400 ExtClassName,
3401 &CGM.getModule());
3402 UsedGlobals.push_back(ClassGV);
3403 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003404 std::vector<llvm::Constant*> Methods;
3405 std::string MethodListName(Prefix);
3406 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3407 "_$_" + OCD->getNameAsString();
3408
3409 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3410 e = OCD->instmeth_end(); i != e; ++i) {
3411 // Instance methods should always be defined.
3412 Methods.push_back(GetMethodConstant(*i));
3413 }
3414
3415 Values[2] = EmitMethodList(MethodListName,
3416 ".section __DATA,__data,regular,no_dead_strip",
3417 Methods);
3418
3419 MethodListName = Prefix;
3420 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3421 OCD->getNameAsString();
3422 Methods.clear();
3423 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3424 e = OCD->classmeth_end(); i != e; ++i) {
3425 // Class methods should always be defined.
3426 Methods.push_back(GetMethodConstant(*i));
3427 }
3428
3429 Values[3] = EmitMethodList(MethodListName,
3430 ".section __DATA,__data,regular,no_dead_strip",
3431 Methods);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003432 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3433 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3434
3435 llvm::Constant *Init =
3436 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3437 Values);
3438 llvm::GlobalVariable *GCATV
3439 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3440 false,
3441 llvm::GlobalValue::InternalLinkage,
3442 Init,
3443 ExtCatName,
3444 &CGM.getModule());
3445 GCATV->setSection(".section __DATA,__data,regular,no_dead_strip");
3446 UsedGlobals.push_back(GCATV);
3447 DefinedCategories.push_back(GCATV);
3448}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003449
3450/// GetMethodConstant - Return a struct objc_method constant for the
3451/// given method if it has been defined. The result is null if the
3452/// method has not been defined. The return value has type MethodPtrTy.
3453llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3454 const ObjCMethodDecl *MD) {
3455 // FIXME: Use DenseMap::lookup
3456 llvm::Function *Fn = MethodDefinitions[MD];
3457 if (!Fn)
3458 return 0;
3459
3460 std::vector<llvm::Constant*> Method(3);
3461 Method[0] =
3462 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3463 ObjCTypes.SelectorPtrTy);
3464 Method[1] = GetMethodVarType(MD);
3465 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3466 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3467}
3468
3469/// EmitMethodList - Build meta-data for method declarations
3470/// struct _method_list_t {
3471/// uint32_t entsize; // sizeof(struct _objc_method)
3472/// uint32_t method_count;
3473/// struct _objc_method method_list[method_count];
3474/// }
3475///
3476llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3477 const std::string &Name,
3478 const char *Section,
3479 const ConstantVector &Methods) {
3480 // Return null for empty list.
3481 if (Methods.empty())
3482 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3483
3484 std::vector<llvm::Constant*> Values(3);
3485 // sizeof(struct _objc_method)
3486 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3487 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3488 // method_count
3489 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3490 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3491 Methods.size());
3492 Values[2] = llvm::ConstantArray::get(AT, Methods);
3493 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3494
3495 llvm::GlobalVariable *GV =
3496 new llvm::GlobalVariable(Init->getType(), false,
3497 llvm::GlobalValue::InternalLinkage,
3498 Init,
3499 Name,
3500 &CGM.getModule());
3501 GV->setSection(Section);
3502 UsedGlobals.push_back(GV);
3503 return llvm::ConstantExpr::getBitCast(GV,
3504 ObjCTypes.MethodListnfABIPtrTy);
3505}
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003506/* *** */
3507
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003508CodeGen::CGObjCRuntime *
3509CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00003510 return new CGObjCMac(CGM);
3511}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003512
3513CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003514CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003515 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003516}