blob: 2b1ffc0d8ecf5bff1c8e38c0c7d34f61039bd571 [file] [log] [blame]
Daniel Dunbar8c85fac2008-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 Dunbar1be1df32008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000024#include "llvm/Support/IRBuilder.h"
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000032
Daniel Dunbarfe131f02008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbarcffcdac2008-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
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000038/// ObjCTypesHelper - Helper class that encapsulates lazy
39/// construction of varies types used during ObjC generation.
40class ObjCTypesHelper {
41private:
42 CodeGen::CodeGenModule &CGM;
43
Daniel Dunbaraecef4c2008-10-17 03:24:53 +000044 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46 *MessageSendSuperFpretFn;
Daniel Dunbar5eec6142008-08-12 03:39:23 +000047
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000048public:
Daniel Dunbarb050fa62008-08-21 04:36:09 +000049 const llvm::Type *ShortTy, *IntTy, *LongTy;
50 const llvm::Type *Int8PtrTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +000051
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000052 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53 const llvm::Type *ObjectPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000054 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000055 const llvm::Type *SelectorPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000056 /// ProtocolPtrTy - LLVM type for external protocol handles
57 /// (typeof(Protocol))
58 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000059
Daniel Dunbar0ed60b02008-08-30 03:02:31 +000060 // SuperCTy - clang type for struct objc_super.
61 QualType SuperCTy;
62 // SuperPtrCTy - clang type for struct objc_super *.
63 QualType SuperPtrCTy;
64
Daniel Dunbar15245e52008-08-23 04:28:29 +000065 /// SuperTy - LLVM type for struct objc_super.
66 const llvm::StructType *SuperTy;
Daniel Dunbar87062ff2008-08-23 09:25:55 +000067 /// SuperPtrTy - LLVM type for struct objc_super *.
68 const llvm::Type *SuperPtrTy;
Daniel Dunbar15245e52008-08-23 04:28:29 +000069
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000070 /// SymtabTy - LLVM type for struct objc_symtab.
71 const llvm::StructType *SymtabTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +000072 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
73 const llvm::Type *SymtabPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000074 /// ModuleTy - LLVM type for struct objc_module.
75 const llvm::StructType *ModuleTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +000076
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000077 /// ProtocolTy - LLVM type for struct objc_protocol.
78 const llvm::StructType *ProtocolTy;
79 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
80 const llvm::Type *ProtocolPtrTy;
81 /// ProtocolExtensionTy - LLVM type for struct
82 /// objc_protocol_extension.
83 const llvm::StructType *ProtocolExtensionTy;
84 /// ProtocolExtensionTy - LLVM type for struct
85 /// objc_protocol_extension *.
86 const llvm::Type *ProtocolExtensionPtrTy;
87 /// MethodDescriptionTy - LLVM type for struct
88 /// objc_method_description.
89 const llvm::StructType *MethodDescriptionTy;
90 /// MethodDescriptionListTy - LLVM type for struct
91 /// objc_method_description_list.
92 const llvm::StructType *MethodDescriptionListTy;
93 /// MethodDescriptionListPtrTy - LLVM type for struct
94 /// objc_method_description_list *.
95 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +000096 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
97 /// in GCC parlance).
98 const llvm::StructType *PropertyTy;
99 /// PropertyListTy - LLVM type for struct objc_property_list
100 /// (_prop_list_t in GCC parlance).
101 const llvm::StructType *PropertyListTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000102 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
103 const llvm::Type *PropertyListPtrTy;
104 /// ProtocolListTy - LLVM type for struct objc_property_list.
105 const llvm::Type *ProtocolListTy;
106 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
107 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000108 /// CategoryTy - LLVM type for struct objc_category.
109 const llvm::StructType *CategoryTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000110 /// ClassTy - LLVM type for struct objc_class.
111 const llvm::StructType *ClassTy;
112 /// ClassPtrTy - LLVM type for struct objc_class *.
113 const llvm::Type *ClassPtrTy;
114 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
115 const llvm::StructType *ClassExtensionTy;
116 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
117 const llvm::Type *ClassExtensionPtrTy;
118 /// CacheTy - LLVM type for struct objc_cache.
119 const llvm::Type *CacheTy;
120 /// CachePtrTy - LLVM type for struct objc_cache *.
121 const llvm::Type *CachePtrTy;
122 // IvarTy - LLVM type for struct objc_ivar.
123 const llvm::StructType *IvarTy;
124 /// IvarListTy - LLVM type for struct objc_ivar_list.
125 const llvm::Type *IvarListTy;
126 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
127 const llvm::Type *IvarListPtrTy;
128 // MethodTy - LLVM type for struct objc_method.
129 const llvm::StructType *MethodTy;
130 /// MethodListTy - LLVM type for struct objc_method_list.
131 const llvm::Type *MethodListTy;
132 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
133 const llvm::Type *MethodListPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000134
Daniel Dunbarf7103722008-09-24 03:38:44 +0000135 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson58d16242008-08-31 04:05:03 +0000136 llvm::Function *EnumerationMutationFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000137
138 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
139 const llvm::Type *ExceptionDataTy;
140
141 /// ExceptionThrowFn - LLVM objc_exception_throw function.
142 llvm::Function *ExceptionThrowFn;
143
144 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
145 llvm::Function *ExceptionTryEnterFn;
146
147 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
148 llvm::Function *ExceptionTryExitFn;
149
150 /// ExceptionExtractFn - LLVM objc_exception_extract function.
151 llvm::Function *ExceptionExtractFn;
152
153 /// ExceptionMatchFn - LLVM objc_exception_match function.
154 llvm::Function *ExceptionMatchFn;
155
156 /// SetJmpFn - LLVM _setjmp function.
157 llvm::Function *SetJmpFn;
158
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000159public:
160 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
161 ~ObjCTypesHelper();
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000162
163
164 llvm::Function *getSendFn(bool IsSuper) {
165 return IsSuper ? MessageSendSuperFn : MessageSendFn;
166 }
167
168 llvm::Function *getSendStretFn(bool IsSuper) {
169 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
170 }
171
172 llvm::Function *getSendFpretFn(bool IsSuper) {
173 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
174 }
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000175};
176
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000177class CGObjCMac : public CodeGen::CGObjCRuntime {
178private:
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000179 CodeGen::CodeGenModule &CGM;
180 ObjCTypesHelper ObjCTypes;
181 /// ObjCABI - FIXME: Not sure yet.
182 unsigned ObjCABI;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000183
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000184 /// LazySymbols - Symbols to generate a lazy reference for. See
185 /// DefinedSymbols and FinishModule().
186 std::set<IdentifierInfo*> LazySymbols;
187
188 /// DefinedSymbols - External symbols which are defined by this
189 /// module. The symbols in this list and LazySymbols are used to add
190 /// special linker symbols which ensure that Objective-C modules are
191 /// linked properly.
192 std::set<IdentifierInfo*> DefinedSymbols;
193
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000194 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000195 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000196
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000197 /// MethodVarNames - uniqued method variable names.
198 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
199
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000200 /// MethodVarTypes - uniqued method type signatures. We have to use
201 /// a StringMap here because have no other unique reference.
202 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
203
Daniel Dunbar12996f52008-08-26 21:51:14 +0000204 /// MethodDefinitions - map of methods which have been defined in
205 /// this translation unit.
206 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
207
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000208 /// PropertyNames - uniqued method variable names.
209 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
210
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000211 /// ClassReferences - uniqued class references.
212 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
213
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000214 /// SelectorReferences - uniqued selector references.
215 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
216
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000217 /// Protocols - Protocols for which an objc_protocol structure has
218 /// been emitted. Forward declarations are handled by creating an
219 /// empty structure whose initializer is filled in when/if defined.
220 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
221
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000222 /// DefinedClasses - List of defined classes.
223 std::vector<llvm::GlobalValue*> DefinedClasses;
224
225 /// DefinedCategories - List of defined categories.
226 std::vector<llvm::GlobalValue*> DefinedCategories;
227
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000228 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000229 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000230 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000231
232 /// EmitImageInfo - Emit the image info marker used to encode some module
233 /// level information.
234 void EmitImageInfo();
235
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000236 /// EmitModuleInfo - Another marker encoding module level
237 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000238 void EmitModuleInfo();
239
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000240 /// EmitModuleSymols - Emit module symbols, the list of defined
241 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000242 llvm::Constant *EmitModuleSymbols();
243
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000244 /// FinishModule - Write out global data structures at the end of
245 /// processing a translation unit.
246 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000247
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000248 /// EmitClassExtension - Generate the class extension structure used
249 /// to store the weak ivar layout and properties. The return value
250 /// has type ClassExtensionPtrTy.
251 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
252
253 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
254 /// for the given class.
255 llvm::Value *EmitClassRef(llvm::IRBuilder<> &Builder,
256 const ObjCInterfaceDecl *ID);
257
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000258 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000259 QualType ResultType,
260 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000261 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000262 QualType Arg0Ty,
263 bool IsSuper,
264 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000265
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000266 /// EmitIvarList - Emit the ivar list for the given
267 /// implementation. If ForClass is true the list of class ivars
268 /// (i.e. metaclass ivars) is emitted, otherwise the list of
269 /// interface ivars will be emitted. The return value has type
270 /// IvarListPtrTy.
271 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
272 bool ForClass,
273 const llvm::Type *InterfaceTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000274
275 /// EmitMetaClass - Emit a forward reference to the class structure
276 /// for the metaclass of the given interface. The return value has
277 /// type ClassPtrTy.
278 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
279
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000280 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000281 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000282 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
283 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000284 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000285 const ConstantVector &Methods);
286
287 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
288
289 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000290
291 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000292 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000293 llvm::Constant *EmitMethodList(const std::string &Name,
294 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000295 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000296
297 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000298 /// method declarations.
299 /// - TypeName: The name for the type containing the methods.
300 /// - IsProtocol: True iff these methods are for a protocol.
301 /// - ClassMethds: True iff these are class methods.
302 /// - Required: When true, only "required" methods are
303 /// listed. Similarly, when false only "optional" methods are
304 /// listed. For classes this should always be true.
305 /// - begin, end: The method list to output.
306 ///
307 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000308 llvm::Constant *EmitMethodDescList(const std::string &Name,
309 const char *Section,
310 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000311
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000312 /// EmitPropertyList - Emit the given property list. The return
313 /// value has type PropertyListPtrTy.
314 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000315 const Decl *Container,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000316 ObjCPropertyDecl * const *begin,
317 ObjCPropertyDecl * const *end);
318
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000319 /// EmitProtocolExtension - Generate the protocol extension
320 /// structure used to store optional instance and class methods, and
321 /// protocol properties. The return value has type
322 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000323 llvm::Constant *
324 EmitProtocolExtension(const ObjCProtocolDecl *PD,
325 const ConstantVector &OptInstanceMethods,
326 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000327
328 /// EmitProtocolList - Generate the list of referenced
329 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000330 llvm::Constant *EmitProtocolList(const std::string &Name,
331 ObjCProtocolDecl::protocol_iterator begin,
332 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000333
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000334 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
335 /// for the given selector.
336 llvm::Value *EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel);
337
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000338 /// GetProtocolRef - Return a reference to the internal protocol
339 /// description, creating an empty one if it has not been
340 /// defined. The return value has type pointer-to ProtocolTy.
341 llvm::GlobalVariable *GetProtocolRef(const ObjCProtocolDecl *PD);
342
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000343 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000344 /// name. The return value has type char *.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000345 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000346
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000347 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000348 /// selector's name. The return value has type char *.
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000349 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000350 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000351 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000352
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000353 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000354 /// selector's name. The return value has type char *.
355
356 // FIXME: This is a horrible name.
Daniel Dunbar12996f52008-08-26 21:51:14 +0000357 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000358 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000359
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000360 /// GetPropertyName - Return a unique constant for the given
361 /// name. The return value has type char *.
362 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
363
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000364 // FIXME: This can be dropped once string functions are unified.
365 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
366 const Decl *Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000367
Daniel Dunbarace33292008-08-16 03:19:19 +0000368 /// GetNameForMethod - Return a name for the given method.
369 /// \param[out] NameOut - The return value.
370 void GetNameForMethod(const ObjCMethodDecl *OMD,
371 std::string &NameOut);
372
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000373public:
374 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000375 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000376
Daniel Dunbara04840b2008-08-23 03:46:30 +0000377 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000378 QualType ResultType,
379 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000380 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000381 bool IsClassMessage,
382 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000383
Daniel Dunbara04840b2008-08-23 03:46:30 +0000384 virtual CodeGen::RValue
385 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000386 QualType ResultType,
387 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000388 const ObjCInterfaceDecl *Class,
389 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000390 bool IsClassMessage,
391 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000392
393 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000394 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000395
396 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
397
Daniel Dunbarac93e472008-08-15 22:20:32 +0000398 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000399
Daniel Dunbarac93e472008-08-15 22:20:32 +0000400 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000401
Daniel Dunbarac93e472008-08-15 22:20:32 +0000402 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000403
404 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000405 const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000406
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000407 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000408
409 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbarf7103722008-09-24 03:38:44 +0000410 virtual llvm::Function *GetPropertyGetFunction();
411 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson58d16242008-08-31 04:05:03 +0000412 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000413
414 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
415 const ObjCAtTryStmt &S);
416 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
417 const ObjCAtThrowStmt &S);
418
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000419};
420} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000421
422/* *** Helper Functions *** */
423
424/// getConstantGEP() - Help routine to construct simple GEPs.
425static llvm::Constant *getConstantGEP(llvm::Constant *C,
426 unsigned idx0,
427 unsigned idx1) {
428 llvm::Value *Idxs[] = {
429 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
430 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
431 };
432 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
433}
434
435/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000436
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000437CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
438 : CGM(cgm),
439 ObjCTypes(cgm),
440 ObjCABI(1)
441{
442 // FIXME: How does this get set in GCC? And what does it even mean?
443 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
444 ObjCABI = 2;
445
446 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000447}
448
Daniel Dunbar434627a2008-08-16 00:25:02 +0000449/// GetClass - Return a reference to the class for the given interface
450/// decl.
451llvm::Value *CGObjCMac::GetClass(llvm::IRBuilder<> &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000452 const ObjCInterfaceDecl *ID) {
453 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000454}
455
456/// GetSelector - Return the pointer to the unique'd string for this selector.
457llvm::Value *CGObjCMac::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000458 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000459}
460
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000461/// Generate a constant CFString object.
462/*
463 struct __builtin_CFString {
464 const int *isa; // point to __CFConstantStringClassReference
465 int flags;
466 const char *str;
467 long length;
468 };
469*/
470
471llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000472 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000473}
474
475/// Generates a message send where the super is the receiver. This is
476/// a message send to self with special delivery semantics indicating
477/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000478CodeGen::RValue
479CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000480 QualType ResultType,
481 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000482 const ObjCInterfaceDecl *Class,
483 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000484 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000485 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000486 // Create and init a super structure; this is a (receiver, class)
487 // pair we will pass to objc_msgSendSuper.
488 llvm::Value *ObjCSuper =
489 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
490 llvm::Value *ReceiverAsObject =
491 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
492 CGF.Builder.CreateStore(ReceiverAsObject,
493 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000494
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000495 // If this is a class message the metaclass is passed as the target.
496 llvm::Value *Target;
497 if (IsClassMessage) {
498 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
499 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
500 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
501 Target = Super;
502 } else {
503 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
504 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000505 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
506 // and ObjCTypes types.
507 const llvm::Type *ClassTy =
508 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
509 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000510 CGF.Builder.CreateStore(Target,
511 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
512
Daniel Dunbardd851282008-08-30 05:35:15 +0000513 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000514 ObjCSuper, ObjCTypes.SuperPtrCTy,
515 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000516}
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000517
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000518/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000519CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000520 QualType ResultType,
521 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000522 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000523 bool IsClassMessage,
524 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000525 llvm::Value *Arg0 =
526 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +0000527 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000528 Arg0, CGF.getContext().getObjCIdType(),
529 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000530}
531
532CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000533 QualType ResultType,
534 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000535 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000536 QualType Arg0Ty,
537 bool IsSuper,
538 const CallArgList &CallArgs) {
539 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000540 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
541 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
542 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000543 CGF.getContext().getObjCSelType()));
544 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +0000545
Daniel Dunbara9976a22008-09-10 07:00:50 +0000546 const llvm::FunctionType *FTy =
547 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
548 false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000549
550 llvm::Constant *Fn;
551 if (CGM.ReturnTypeUsesSret(ResultType)) {
552 Fn = ObjCTypes.getSendStretFn(IsSuper);
553 } else if (ResultType->isFloatingType()) {
554 // FIXME: Sadly, this is wrong. This actually depends on the
555 // architecture. This happens to be right for x86-32 though.
556 Fn = ObjCTypes.getSendFpretFn(IsSuper);
557 } else {
558 Fn = ObjCTypes.getSendFn(IsSuper);
559 }
Daniel Dunbara9976a22008-09-10 07:00:50 +0000560 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +0000561 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000562}
563
564llvm::Value *CGObjCMac::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000565 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +0000566 // FIXME: I don't understand why gcc generates this, or where it is
567 // resolved. Investigate. Its also wasteful to look this up over and
568 // over.
569 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
570
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000571 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
572 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000573}
574
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000575/*
576 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
577 struct _objc_protocol {
578 struct _objc_protocol_extension *isa;
579 char *protocol_name;
580 struct _objc_protocol_list *protocol_list;
581 struct _objc__method_prototype_list *instance_methods;
582 struct _objc__method_prototype_list *class_methods
583 };
584
585 See EmitProtocolExtension().
586*/
587void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000588 // FIXME: I don't understand why gcc generates this, or where it is
589 // resolved. Investigate. Its also wasteful to look this up over and
590 // over.
591 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
592
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000593 const char *ProtocolName = PD->getName();
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000594
595 // Construct method lists.
596 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
597 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
598 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
599 e = PD->instmeth_end(); i != e; ++i) {
600 ObjCMethodDecl *MD = *i;
601 llvm::Constant *C = GetMethodDescriptionConstant(MD);
602 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
603 OptInstanceMethods.push_back(C);
604 } else {
605 InstanceMethods.push_back(C);
606 }
607 }
608
609 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
610 e = PD->classmeth_end(); i != e; ++i) {
611 ObjCMethodDecl *MD = *i;
612 llvm::Constant *C = GetMethodDescriptionConstant(MD);
613 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
614 OptClassMethods.push_back(C);
615 } else {
616 ClassMethods.push_back(C);
617 }
618 }
619
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000620 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000621 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000622 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000623 Values[2] =
624 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
625 PD->protocol_begin(),
626 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000627 Values[3] =
628 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
629 + PD->getName(),
630 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
631 InstanceMethods);
632 Values[4] =
633 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
634 + PD->getName(),
635 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
636 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000637 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
638 Values);
639
640 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
641 if (Entry) {
642 // Already created, just update the initializer
643 Entry->setInitializer(Init);
644 } else {
645 Entry =
646 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
647 llvm::GlobalValue::InternalLinkage,
648 Init,
649 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
650 &CGM.getModule());
651 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
652 UsedGlobals.push_back(Entry);
653 // FIXME: Is this necessary? Why only for protocol?
654 Entry->setAlignment(4);
655 }
656}
657
658llvm::GlobalVariable *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
659 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
660
661 if (!Entry) {
662 std::vector<llvm::Constant*> Values(5);
663 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
664 Values[1] = GetClassName(PD->getIdentifier());
665 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
666 Values[3] = Values[4] =
667 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
668 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
669 Values);
670
671 Entry =
672 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
673 llvm::GlobalValue::InternalLinkage,
674 Init,
675 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
676 &CGM.getModule());
677 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
678 UsedGlobals.push_back(Entry);
679 // FIXME: Is this necessary? Why only for protocol?
680 Entry->setAlignment(4);
681 }
682
683 return Entry;
684}
685
686/*
687 struct _objc_protocol_extension {
688 uint32_t size;
689 struct objc_method_description_list *optional_instance_methods;
690 struct objc_method_description_list *optional_class_methods;
691 struct objc_property_list *instance_properties;
692 };
693*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000694llvm::Constant *
695CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
696 const ConstantVector &OptInstanceMethods,
697 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000698 uint64_t Size =
699 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
700 std::vector<llvm::Constant*> Values(4);
701 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000702 Values[1] =
703 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
704 + PD->getName(),
705 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
706 OptInstanceMethods);
707 Values[2] =
708 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
709 + PD->getName(),
710 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
711 OptClassMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000712 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
713 PD->getName(),
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000714 0,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000715 PD->classprop_begin(),
716 PD->classprop_end());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000717
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000718 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000719 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
720 Values[3]->isNullValue())
721 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
722
723 llvm::Constant *Init =
724 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
725 llvm::GlobalVariable *GV =
726 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
727 llvm::GlobalValue::InternalLinkage,
728 Init,
729 (std::string("\01L_OBJC_PROTOCOLEXT_") +
730 PD->getName()),
731 &CGM.getModule());
732 // No special section, but goes in llvm.used
733 UsedGlobals.push_back(GV);
734
735 return GV;
736}
737
738/*
739 struct objc_protocol_list {
740 struct objc_protocol_list *next;
741 long count;
742 Protocol *list[];
743 };
744*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000745llvm::Constant *
746CGObjCMac::EmitProtocolList(const std::string &Name,
747 ObjCProtocolDecl::protocol_iterator begin,
748 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000749 std::vector<llvm::Constant*> ProtocolRefs;
750
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000751 for (; begin != end; ++begin)
752 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000753
754 // Just return null for empty protocol lists
755 if (ProtocolRefs.empty())
756 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
757
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000758 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000759 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
760
761 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000762 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000763 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
764 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
765 Values[2] =
766 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
767 ProtocolRefs.size()),
768 ProtocolRefs);
769
770 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
771 llvm::GlobalVariable *GV =
772 new llvm::GlobalVariable(Init->getType(), false,
773 llvm::GlobalValue::InternalLinkage,
774 Init,
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000775 Name,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000776 &CGM.getModule());
777 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
778 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
779}
780
781/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000782 struct _objc_property {
783 const char * const name;
784 const char * const attributes;
785 };
786
787 struct _objc_property_list {
788 uint32_t entsize; // sizeof (struct _objc_property)
789 uint32_t prop_count;
790 struct _objc_property[prop_count];
791 };
792*/
793llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000794 const Decl *Container,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000795 ObjCPropertyDecl * const *begin,
796 ObjCPropertyDecl * const *end) {
797 std::vector<llvm::Constant*> Properties, Prop(2);
798 for (; begin != end; ++begin) {
799 const ObjCPropertyDecl *PD = *begin;
800 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000801 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000802 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
803 Prop));
804 }
805
806 // Return null for empty list.
807 if (Properties.empty())
808 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
809
810 unsigned PropertySize =
811 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
812 std::vector<llvm::Constant*> Values(3);
813 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
814 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
815 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
816 Properties.size());
817 Values[2] = llvm::ConstantArray::get(AT, Properties);
818 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
819
820 llvm::GlobalVariable *GV =
821 new llvm::GlobalVariable(Init->getType(), false,
822 llvm::GlobalValue::InternalLinkage,
823 Init,
824 Name,
825 &CGM.getModule());
826 // No special section on property lists?
827 UsedGlobals.push_back(GV);
828 return llvm::ConstantExpr::getBitCast(GV,
829 ObjCTypes.PropertyListPtrTy);
830
831}
832
833/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000834 struct objc_method_description_list {
835 int count;
836 struct objc_method_description list[];
837 };
838*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000839llvm::Constant *
840CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
841 std::vector<llvm::Constant*> Desc(2);
842 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
843 ObjCTypes.SelectorPtrTy);
844 Desc[1] = GetMethodVarType(MD);
845 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
846 Desc);
847}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000848
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000849llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
850 const char *Section,
851 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000852 // Return null for empty list.
853 if (Methods.empty())
854 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
855
856 std::vector<llvm::Constant*> Values(2);
857 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
858 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
859 Methods.size());
860 Values[1] = llvm::ConstantArray::get(AT, Methods);
861 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
862
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000863 llvm::GlobalVariable *GV =
864 new llvm::GlobalVariable(Init->getType(), false,
865 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000866 Init, Name, &CGM.getModule());
867 GV->setSection(Section);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000868 UsedGlobals.push_back(GV);
869 return llvm::ConstantExpr::getBitCast(GV,
870 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000871}
872
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000873/*
874 struct _objc_category {
875 char *category_name;
876 char *class_name;
877 struct _objc_method_list *instance_methods;
878 struct _objc_method_list *class_methods;
879 struct _objc_protocol_list *protocols;
880 uint32_t size; // <rdar://4585769>
881 struct _objc_property_list *instance_properties;
882 };
883 */
Daniel Dunbarac93e472008-08-15 22:20:32 +0000884void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000885 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
886
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000887 // FIXME: This is poor design, the OCD should have a pointer to the
888 // category decl. Additionally, note that Category can be null for
889 // the @implementation w/o an @interface case. Sema should just
890 // create one for us as it does for @implementation so everyone else
891 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000892 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000893 const ObjCCategoryDecl *Category =
894 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000895 std::string ExtName(std::string(Interface->getName()) +
896 "_" +
897 OCD->getName());
898
Daniel Dunbar12996f52008-08-26 21:51:14 +0000899 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
900 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
901 e = OCD->instmeth_end(); i != e; ++i) {
902 // Instance methods should always be defined.
903 InstanceMethods.push_back(GetMethodConstant(*i));
904 }
905 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
906 e = OCD->classmeth_end(); i != e; ++i) {
907 // Class methods should always be defined.
908 ClassMethods.push_back(GetMethodConstant(*i));
909 }
910
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000911 std::vector<llvm::Constant*> Values(7);
912 Values[0] = GetClassName(OCD->getIdentifier());
913 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000914 Values[2] =
915 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
916 ExtName,
917 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000918 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000919 Values[3] =
920 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
921 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000922 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000923 if (Category) {
924 Values[4] =
925 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
926 Category->protocol_begin(),
927 Category->protocol_end());
928 } else {
929 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
930 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000931 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000932
933 // If there is no category @interface then there can be no properties.
934 if (Category) {
935 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000936 OCD,
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000937 Category->classprop_begin(),
938 Category->classprop_end());
939 } else {
940 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
941 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000942
943 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
944 Values);
945
946 llvm::GlobalVariable *GV =
947 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
948 llvm::GlobalValue::InternalLinkage,
949 Init,
950 std::string("\01L_OBJC_CATEGORY_")+ExtName,
951 &CGM.getModule());
952 GV->setSection("__OBJC,__category,regular,no_dead_strip");
953 UsedGlobals.push_back(GV);
954 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000955}
956
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000957// FIXME: Get from somewhere?
958enum ClassFlags {
959 eClassFlags_Factory = 0x00001,
960 eClassFlags_Meta = 0x00002,
961 // <rdr://5142207>
962 eClassFlags_HasCXXStructors = 0x02000,
963 eClassFlags_Hidden = 0x20000,
964 eClassFlags_ABI2_Hidden = 0x00010,
965 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
966};
967
968// <rdr://5142207&4705298&4843145>
969static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
970 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
971 // FIXME: Support -fvisibility
972 switch (attr->getVisibility()) {
973 default:
974 assert(0 && "Unknown visibility");
975 return false;
976 case VisibilityAttr::DefaultVisibility:
977 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
978 return false;
979 case VisibilityAttr::HiddenVisibility:
980 return true;
981 }
982 } else {
983 return false; // FIXME: Support -fvisibility
984 }
985}
986
987/*
988 struct _objc_class {
989 Class isa;
990 Class super_class;
991 const char *name;
992 long version;
993 long info;
994 long instance_size;
995 struct _objc_ivar_list *ivars;
996 struct _objc_method_list *methods;
997 struct _objc_cache *cache;
998 struct _objc_protocol_list *protocols;
999 // Objective-C 1.0 extensions (<rdr://4585769>)
1000 const char *ivar_layout;
1001 struct _objc_class_ext *ext;
1002 };
1003
1004 See EmitClassExtension();
1005 */
1006void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001007 DefinedSymbols.insert(ID->getIdentifier());
1008
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001009 const char *ClassName = ID->getName();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001010 // FIXME: Gross
1011 ObjCInterfaceDecl *Interface =
1012 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001013 llvm::Constant *Protocols =
1014 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1015 Interface->protocol_begin(),
1016 Interface->protocol_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001017 const llvm::Type *InterfaceTy =
1018 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1019 unsigned Flags = eClassFlags_Factory;
1020 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1021
1022 // FIXME: Set CXX-structors flag.
1023 if (IsClassHidden(ID->getClassInterface()))
1024 Flags |= eClassFlags_Hidden;
1025
Daniel Dunbar12996f52008-08-26 21:51:14 +00001026 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1027 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1028 e = ID->instmeth_end(); i != e; ++i) {
1029 // Instance methods should always be defined.
1030 InstanceMethods.push_back(GetMethodConstant(*i));
1031 }
1032 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1033 e = ID->classmeth_end(); i != e; ++i) {
1034 // Class methods should always be defined.
1035 ClassMethods.push_back(GetMethodConstant(*i));
1036 }
1037
1038 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1039 e = ID->propimpl_end(); i != e; ++i) {
1040 ObjCPropertyImplDecl *PID = *i;
1041
1042 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1043 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1044
1045 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1046 if (llvm::Constant *C = GetMethodConstant(MD))
1047 InstanceMethods.push_back(C);
1048 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1049 if (llvm::Constant *C = GetMethodConstant(MD))
1050 InstanceMethods.push_back(C);
1051 }
1052 }
1053
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001054 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001055 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001056 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001057 // Record a reference to the super class.
1058 LazySymbols.insert(Super->getIdentifier());
1059
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001060 Values[ 1] =
1061 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1062 ObjCTypes.ClassPtrTy);
1063 } else {
1064 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1065 }
1066 Values[ 2] = GetClassName(ID->getIdentifier());
1067 // Version is always 0.
1068 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1069 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1070 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1071 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001072 Values[ 7] =
1073 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1074 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001075 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001076 // cache is always NULL.
1077 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1078 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001079 // FIXME: Set ivar_layout
1080 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001081 Values[11] = EmitClassExtension(ID);
1082 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1083 Values);
1084
1085 llvm::GlobalVariable *GV =
1086 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1087 llvm::GlobalValue::InternalLinkage,
1088 Init,
1089 std::string("\01L_OBJC_CLASS_")+ClassName,
1090 &CGM.getModule());
1091 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1092 UsedGlobals.push_back(GV);
1093 // FIXME: Why?
1094 GV->setAlignment(32);
1095 DefinedClasses.push_back(GV);
1096}
1097
1098llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1099 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001100 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001101 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001102 const char *ClassName = ID->getName();
1103 unsigned Flags = eClassFlags_Meta;
1104 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1105
1106 if (IsClassHidden(ID->getClassInterface()))
1107 Flags |= eClassFlags_Hidden;
1108
1109 std::vector<llvm::Constant*> Values(12);
1110 // The isa for the metaclass is the root of the hierarchy.
1111 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1112 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1113 Root = Super;
1114 Values[ 0] =
1115 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1116 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001117 // The super class for the metaclass is emitted as the name of the
1118 // super class. The runtime fixes this up to point to the
1119 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001120 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1121 Values[ 1] =
1122 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1123 ObjCTypes.ClassPtrTy);
1124 } else {
1125 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1126 }
1127 Values[ 2] = GetClassName(ID->getIdentifier());
1128 // Version is always 0.
1129 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1130 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1131 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1132 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001133 Values[ 7] =
1134 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1135 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001136 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001137 // cache is always NULL.
1138 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1139 Values[ 9] = Protocols;
1140 // ivar_layout for metaclass is always NULL.
1141 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1142 // The class extension is always unused for metaclasses.
1143 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1144 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1145 Values);
1146
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001147 std::string Name("\01L_OBJC_METACLASS_");
1148 Name += ClassName;
1149
1150 // Check for a forward reference.
1151 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1152 if (GV) {
1153 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1154 "Forward metaclass reference has incorrect type.");
1155 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1156 GV->setInitializer(Init);
1157 } else {
1158 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1159 llvm::GlobalValue::InternalLinkage,
1160 Init, Name,
1161 &CGM.getModule());
1162 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001163 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1164 UsedGlobals.push_back(GV);
1165 // FIXME: Why?
1166 GV->setAlignment(32);
1167
1168 return GV;
1169}
1170
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001171llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1172 std::string Name("\01L_OBJC_METACLASS_");
1173 Name += ID->getName();
1174
1175 // FIXME: Should we look these up somewhere other than the
1176 // module. Its a bit silly since we only generate these while
1177 // processing an implementation, so exactly one pointer would work
1178 // if know when we entered/exitted an implementation block.
1179
1180 // Check for an existing forward reference.
1181 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1182 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1183 "Forward metaclass reference has incorrect type.");
1184 return GV;
1185 } else {
1186 // Generate as an external reference to keep a consistent
1187 // module. This will be patched up when we emit the metaclass.
1188 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1189 llvm::GlobalValue::ExternalLinkage,
1190 0,
1191 Name,
1192 &CGM.getModule());
1193 }
1194}
1195
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001196/*
1197 struct objc_class_ext {
1198 uint32_t size;
1199 const char *weak_ivar_layout;
1200 struct _objc_property_list *properties;
1201 };
1202*/
1203llvm::Constant *
1204CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1205 uint64_t Size =
1206 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1207
1208 std::vector<llvm::Constant*> Values(3);
1209 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001210 // FIXME: Output weak_ivar_layout string.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001211 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001212 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1213 ID->getName(),
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001214 ID,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001215 ID->getClassInterface()->classprop_begin(),
1216 ID->getClassInterface()->classprop_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001217
1218 // Return null if no extension bits are used.
1219 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1220 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1221
1222 llvm::Constant *Init =
1223 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1224 llvm::GlobalVariable *GV =
1225 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1226 llvm::GlobalValue::InternalLinkage,
1227 Init,
1228 (std::string("\01L_OBJC_CLASSEXT_") +
1229 ID->getName()),
1230 &CGM.getModule());
1231 // No special section, but goes in llvm.used
1232 UsedGlobals.push_back(GV);
1233
1234 return GV;
1235}
1236
1237/*
1238 struct objc_ivar {
1239 char *ivar_name;
1240 char *ivar_type;
1241 int ivar_offset;
1242 };
1243
1244 struct objc_ivar_list {
1245 int ivar_count;
1246 struct objc_ivar list[count];
1247 };
1248 */
1249llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1250 bool ForClass,
1251 const llvm::Type *InterfaceTy) {
1252 std::vector<llvm::Constant*> Ivars, Ivar(3);
1253
1254 // When emitting the root class GCC emits ivar entries for the
1255 // actual class structure. It is not clear if we need to follow this
1256 // behavior; for now lets try and get away with not doing it. If so,
1257 // the cleanest solution would be to make up an ObjCInterfaceDecl
1258 // for the class.
1259 if (ForClass)
1260 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1261
1262 const llvm::StructLayout *Layout =
1263 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1264 for (ObjCInterfaceDecl::ivar_iterator
1265 i = ID->getClassInterface()->ivar_begin(),
1266 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1267 ObjCIvarDecl *V = *i;
1268 unsigned Offset =
1269 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1270 std::string TypeStr;
1271 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1272 Ivar[0] = GetMethodVarName(V->getIdentifier());
1273 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr,
Daniel Dunbaraa913102008-10-17 16:17:37 +00001274 EncodingRecordTypes,
1275 true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001276 Ivar[1] = GetMethodVarType(TypeStr);
1277 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
1278 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy,
1279 Ivar));
1280 }
1281
1282 // Return null for empty list.
1283 if (Ivars.empty())
1284 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1285
1286 std::vector<llvm::Constant*> Values(2);
1287 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1288 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1289 Ivars.size());
1290 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1291 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1292
1293 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1294 "\01L_OBJC_INSTANCE_VARIABLES_");
1295 llvm::GlobalVariable *GV =
1296 new llvm::GlobalVariable(Init->getType(), false,
1297 llvm::GlobalValue::InternalLinkage,
1298 Init,
1299 std::string(Prefix) + ID->getName(),
1300 &CGM.getModule());
1301 if (ForClass) {
1302 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1303 // FIXME: Why is this only here?
1304 GV->setAlignment(32);
1305 } else {
1306 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1307 }
1308 UsedGlobals.push_back(GV);
1309 return llvm::ConstantExpr::getBitCast(GV,
1310 ObjCTypes.IvarListPtrTy);
1311}
1312
1313/*
1314 struct objc_method {
1315 SEL method_name;
1316 char *method_types;
1317 void *method;
1318 };
1319
1320 struct objc_method_list {
1321 struct objc_method_list *obsolete;
1322 int count;
1323 struct objc_method methods_list[count];
1324 };
1325*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001326
1327/// GetMethodConstant - Return a struct objc_method constant for the
1328/// given method if it has been defined. The result is null if the
1329/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001330llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001331 // FIXME: Use DenseMap::lookup
1332 llvm::Function *Fn = MethodDefinitions[MD];
1333 if (!Fn)
1334 return 0;
1335
1336 std::vector<llvm::Constant*> Method(3);
1337 Method[0] =
1338 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1339 ObjCTypes.SelectorPtrTy);
1340 Method[1] = GetMethodVarType(MD);
1341 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1342 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1343}
1344
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001345llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1346 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001347 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001348 // Return null for empty list.
1349 if (Methods.empty())
1350 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1351
1352 std::vector<llvm::Constant*> Values(3);
1353 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1354 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1355 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1356 Methods.size());
1357 Values[2] = llvm::ConstantArray::get(AT, Methods);
1358 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1359
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001360 llvm::GlobalVariable *GV =
1361 new llvm::GlobalVariable(Init->getType(), false,
1362 llvm::GlobalValue::InternalLinkage,
1363 Init,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001364 Name,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001365 &CGM.getModule());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001366 GV->setSection(Section);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001367 UsedGlobals.push_back(GV);
1368 return llvm::ConstantExpr::getBitCast(GV,
1369 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001370}
1371
1372llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001373 std::string Name;
1374 GetNameForMethod(OMD, Name);
1375
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001376 const llvm::FunctionType *MethodTy =
1377 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarace33292008-08-16 03:19:19 +00001378 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001379 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001380 llvm::GlobalValue::InternalLinkage,
1381 Name,
1382 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001383 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001384
Daniel Dunbarace33292008-08-16 03:19:19 +00001385 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001386}
1387
1388llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001389 // Abuse this interface function as a place to finalize.
1390 FinishModule();
1391
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001392 return NULL;
1393}
1394
Daniel Dunbarf7103722008-09-24 03:38:44 +00001395llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1396 return ObjCTypes.GetPropertyFn;
1397}
1398
1399llvm::Function *CGObjCMac::GetPropertySetFunction() {
1400 return ObjCTypes.SetPropertyFn;
1401}
1402
Anders Carlsson58d16242008-08-31 04:05:03 +00001403llvm::Function *CGObjCMac::EnumerationMutationFunction()
1404{
1405 return ObjCTypes.EnumerationMutationFn;
1406}
1407
Daniel Dunbar83544842008-09-28 01:03:14 +00001408/*
1409
1410Objective-C setjmp-longjmp (sjlj) Exception Handling
1411--
1412
1413The basic framework for a @try-catch-finally is as follows:
1414{
1415 objc_exception_data d;
1416 id _rethrow = null;
1417
1418 objc_exception_try_enter(&d);
1419 if (!setjmp(d.jmp_buf)) {
1420 ... try body ...
1421 } else {
1422 // exception path
1423 id _caught = objc_exception_extract(&d);
1424
1425 // enter new try scope for handlers
1426 if (!setjmp(d.jmp_buf)) {
1427 ... match exception and execute catch blocks ...
1428
1429 // fell off end, rethrow.
1430 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001431 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001432 } else {
1433 // exception in catch block
1434 _rethrow = objc_exception_extract(&d);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001435 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001436 }
1437 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001438 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001439
1440finally:
1441 // match either the initial try_enter or the catch try_enter,
1442 // depending on the path followed.
1443 objc_exception_try_exit(&d);
1444finally_no_exit:
1445 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001446 ... dispatch to finally destination ...
1447
1448finally_rethrow:
1449 objc_exception_throw(_rethrow);
1450
1451finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00001452}
1453
1454This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001455uses _rethrow to determine if objc_exception_try_exit should be called
1456and if the object should be rethrown. This breaks in the face of
1457throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00001458
1459We specialize this framework for a few particular circumstances:
1460
1461 - If there are no catch blocks, then we avoid emitting the second
1462 exception handling context.
1463
1464 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1465 e)) we avoid emitting the code to rethrow an uncaught exception.
1466
1467 - FIXME: If there is no @finally block we can do a few more
1468 simplifications.
1469
1470Rethrows and Jumps-Through-Finally
1471--
1472
1473Support for implicit rethrows and jumping through the finally block is
1474handled by storing the current exception-handling context in
1475ObjCEHStack.
1476
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001477In order to implement proper @finally semantics, we support one basic
1478mechanism for jumping through the finally block to an arbitrary
1479destination. Constructs which generate exits from a @try or @catch
1480block use this mechanism to implement the proper semantics by chaining
1481jumps, as necessary.
1482
1483This mechanism works like the one used for indirect goto: we
1484arbitrarily assign an ID to each destination and store the ID for the
1485destination in a variable prior to entering the finally block. At the
1486end of the finally block we simply create a switch to the proper
1487destination.
1488
Daniel Dunbar83544842008-09-28 01:03:14 +00001489*/
1490
Anders Carlssonb01a2112008-09-09 10:04:29 +00001491void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001492 const ObjCAtTryStmt &S) {
1493 // Create various blocks we refer to for handling @finally.
1494 llvm::BasicBlock *FinallyBlock = llvm::BasicBlock::Create("finally");
1495 llvm::BasicBlock *FinallyNoExit = llvm::BasicBlock::Create("finally.noexit");
1496 llvm::BasicBlock *FinallyRethrow = llvm::BasicBlock::Create("finally.throw");
1497 llvm::BasicBlock *FinallyEnd = llvm::BasicBlock::Create("finally.end");
1498 llvm::Value *DestCode =
1499 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1500
1501 // Generate jump code. Done here so we can directly add things to
1502 // the switch instruction.
1503 llvm::BasicBlock *FinallyJump = llvm::BasicBlock::Create("finally.jump");
1504 llvm::SwitchInst *FinallySwitch =
1505 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1506 FinallyEnd, 10, FinallyJump);
1507
1508 // Push an EH context entry, used for handling rethrows and jumps
1509 // through finally.
1510 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1511 FinallySwitch, DestCode);
1512 CGF.ObjCEHStack.push_back(&EHEntry);
1513
1514 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00001515 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1516 "exceptiondata.ptr");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001517 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, "_rethrow");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001518
1519 // Enter a new try block and call setjmp.
1520 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1521 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1522 "jmpbufarray");
1523 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1524 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1525 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001526
Anders Carlssonfca6c292008-09-09 17:59:25 +00001527 llvm::BasicBlock *TryBlock = llvm::BasicBlock::Create("try");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001528 llvm::BasicBlock *TryHandler = llvm::BasicBlock::Create("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001529 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001530 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001531
1532 // Emit the @try block.
1533 CGF.EmitBlock(TryBlock);
1534 CGF.EmitStmt(S.getTryBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001535 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001536
1537 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001538 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001539
1540 // Retrieve the exception object. We may emit multiple blocks but
1541 // nothing can cross this so the value is already in SSA form.
1542 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1543 ExceptionData,
1544 "caught");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001545 EHEntry.Exception = Caught;
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001546 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1547 // Enter a new exception try block (in case a @catch block throws
1548 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00001549 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001550
Anders Carlssonfca6c292008-09-09 17:59:25 +00001551 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1552 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001553 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001554
1555 llvm::BasicBlock *CatchBlock = llvm::BasicBlock::Create("catch");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001556 llvm::BasicBlock *CatchHandler = llvm::BasicBlock::Create("catch.handler");
1557 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001558
1559 CGF.EmitBlock(CatchBlock);
1560
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001561 // Handle catch list. As a special case we check if everything is
1562 // matched and avoid generating code for falling off the end if
1563 // so.
1564 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001565 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001566 llvm::BasicBlock *NextCatchBlock = llvm::BasicBlock::Create("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001567
Anders Carlsson75d86732008-09-11 09:15:33 +00001568 const DeclStmt *CatchParam =
1569 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001570 const VarDecl *VD = 0;
1571 const PointerType *PT = 0;
1572
Anders Carlssonfca6c292008-09-09 17:59:25 +00001573 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001574 if (!CatchParam) {
1575 AllMatched = true;
1576 } else {
Ted Kremenekf41e9f72008-10-06 20:58:56 +00001577 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001578 PT = VD->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001579
Daniel Dunbard04c9352008-09-27 22:21:14 +00001580 // catch(id e) always matches.
1581 // FIXME: For the time being we also match id<X>; this should
1582 // be rejected by Sema instead.
1583 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1584 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001585 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001586 }
1587
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001588 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00001589 if (CatchParam) {
1590 CGF.EmitStmt(CatchParam);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001591 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001592 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00001593
Anders Carlsson75d86732008-09-11 09:15:33 +00001594 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001595 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001596 break;
1597 }
1598
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001599 assert(PT && "Unexpected non-pointer type in @catch");
1600 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00001601 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001602 assert(ObjCType && "Catch parameter must have Objective-C type!");
1603
1604 // Check if the @catch block matches the exception object.
1605 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1606
Anders Carlssonfca6c292008-09-09 17:59:25 +00001607 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1608 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001609
1610 llvm::BasicBlock *MatchedBlock = llvm::BasicBlock::Create("matched");
1611
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001612 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001613 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001614
1615 // Emit the @catch block.
1616 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar83544842008-09-28 01:03:14 +00001617 CGF.EmitStmt(CatchParam);
1618
1619 llvm::Value *Tmp =
1620 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1621 "tmp");
1622 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001623
1624 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001625 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001626
1627 CGF.EmitBlock(NextCatchBlock);
1628 }
1629
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001630 if (!AllMatched) {
1631 // None of the handlers caught the exception, so store it to be
1632 // rethrown at the end of the @finally block.
1633 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001634 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001635 }
1636
1637 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001638 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001639 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1640 ExceptionData),
1641 RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001642 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001643 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00001644 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001645 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001646 }
1647
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001648 // Pop the exception-handling stack entry. It is important to do
1649 // this now, because the code in the @finally block is not in this
1650 // context.
1651 CGF.ObjCEHStack.pop_back();
1652
Anders Carlssonfca6c292008-09-09 17:59:25 +00001653 // Emit the @finally block.
1654 CGF.EmitBlock(FinallyBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001655 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001656
1657 CGF.EmitBlock(FinallyNoExit);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001658 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1659 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1660
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001661 CGF.EmitBlock(FinallyJump);
1662
1663 CGF.EmitBlock(FinallyRethrow);
1664 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1665 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001666 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001667
1668 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001669}
1670
1671void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001672 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00001673 llvm::Value *ExceptionAsObject;
1674
1675 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1676 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1677 ExceptionAsObject =
1678 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1679 } else {
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001680 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00001681 "Unexpected rethrow outside @catch block.");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001682 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson05d7be72008-09-09 16:16:55 +00001683 }
1684
1685 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001686 CGF.Builder.CreateUnreachable();
1687 CGF.EmitBlock(llvm::BasicBlock::Create("bb"));
Anders Carlssonb01a2112008-09-09 10:04:29 +00001688}
1689
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001690void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1691 llvm::BasicBlock *Dst,
1692 bool ExecuteTryExit) {
1693 llvm::BasicBlock *Src = Builder.GetInsertBlock();
1694
1695 if (isDummyBlock(Src))
1696 return;
1697
1698 // Find the destination code for this block. We always use 0 for the
1699 // fallthrough block (default destination).
1700 llvm::SwitchInst *SI = E->FinallySwitch;
1701 llvm::ConstantInt *ID;
1702 if (Dst == SI->getDefaultDest()) {
1703 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1704 } else {
1705 ID = SI->findCaseDest(Dst);
1706 if (!ID) {
1707 // No code found, get a new unique one by just using the number
1708 // of switch successors.
1709 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1710 SI->addCase(ID, Dst);
1711 }
1712 }
1713
1714 // Set the destination code and branch.
1715 Builder.CreateStore(ID, E->DestCode);
1716 Builder.CreateBr(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
1717}
1718
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001719/* *** Private Interface *** */
1720
1721/// EmitImageInfo - Emit the image info marker used to encode some module
1722/// level information.
1723///
1724/// See: <rdr://4810609&4810587&4810587>
1725/// struct IMAGE_INFO {
1726/// unsigned version;
1727/// unsigned flags;
1728/// };
1729enum ImageInfoFlags {
1730 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1731 eImageInfo_GarbageCollected = (1 << 1),
1732 eImageInfo_GCOnly = (1 << 2)
1733};
1734
1735void CGObjCMac::EmitImageInfo() {
1736 unsigned version = 0; // Version is unused?
1737 unsigned flags = 0;
1738
1739 // FIXME: Fix and continue?
1740 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1741 flags |= eImageInfo_GarbageCollected;
1742 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1743 flags |= eImageInfo_GCOnly;
1744
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001745 // Emitted as int[2];
1746 llvm::Constant *values[2] = {
1747 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1748 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1749 };
1750 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001751 llvm::GlobalVariable *GV =
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001752 new llvm::GlobalVariable(AT, true,
1753 llvm::GlobalValue::InternalLinkage,
1754 llvm::ConstantArray::get(AT, values, 2),
1755 "\01L_OBJC_IMAGE_INFO",
1756 &CGM.getModule());
1757
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001758 if (ObjCABI == 1) {
1759 GV->setSection("__OBJC, __image_info,regular");
1760 } else {
1761 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1762 }
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001763
1764 UsedGlobals.push_back(GV);
1765}
1766
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001767
1768// struct objc_module {
1769// unsigned long version;
1770// unsigned long size;
1771// const char *name;
1772// Symtab symtab;
1773// };
1774
1775// FIXME: Get from somewhere
1776static const int ModuleVersion = 7;
1777
1778void CGObjCMac::EmitModuleInfo() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001779 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1780
1781 std::vector<llvm::Constant*> Values(4);
1782 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1783 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00001784 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001785 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001786 Values[3] = EmitModuleSymbols();
1787
1788 llvm::GlobalVariable *GV =
1789 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1790 llvm::GlobalValue::InternalLinkage,
1791 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1792 Values),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001793 "\01L_OBJC_MODULES",
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001794 &CGM.getModule());
1795 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1796 UsedGlobals.push_back(GV);
1797}
1798
1799llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001800 unsigned NumClasses = DefinedClasses.size();
1801 unsigned NumCategories = DefinedCategories.size();
1802
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001803 // Return null if no symbols were defined.
1804 if (!NumClasses && !NumCategories)
1805 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1806
1807 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001808 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1809 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1810 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1811 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1812
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001813 // The runtime expects exactly the list of defined classes followed
1814 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001815 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001816 for (unsigned i=0; i<NumClasses; i++)
1817 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1818 ObjCTypes.Int8PtrTy);
1819 for (unsigned i=0; i<NumCategories; i++)
1820 Symbols[NumClasses + i] =
1821 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1822 ObjCTypes.Int8PtrTy);
1823
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001824 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001825 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001826 NumClasses + NumCategories),
1827 Symbols);
1828
1829 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1830
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001831 llvm::GlobalVariable *GV =
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001832 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001833 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001834 Init,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001835 "\01L_OBJC_SYMBOLS",
1836 &CGM.getModule());
1837 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1838 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001839 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
1840}
1841
1842llvm::Value *CGObjCMac::EmitClassRef(llvm::IRBuilder<> &Builder,
1843 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001844 LazySymbols.insert(ID->getIdentifier());
1845
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001846 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
1847
1848 if (!Entry) {
1849 llvm::Constant *Casted =
1850 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
1851 ObjCTypes.ClassPtrTy);
1852 Entry =
1853 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
1854 llvm::GlobalValue::InternalLinkage,
1855 Casted, "\01L_OBJC_CLASS_REFERENCES_",
1856 &CGM.getModule());
1857 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
1858 UsedGlobals.push_back(Entry);
1859 }
1860
1861 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001862}
1863
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001864llvm::Value *CGObjCMac::EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
1865 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
1866
1867 if (!Entry) {
1868 llvm::Constant *Casted =
1869 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
1870 ObjCTypes.SelectorPtrTy);
1871 Entry =
1872 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
1873 llvm::GlobalValue::InternalLinkage,
1874 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
1875 &CGM.getModule());
1876 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
1877 UsedGlobals.push_back(Entry);
1878 }
1879
1880 return Builder.CreateLoad(Entry, false, "tmp");
1881}
1882
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001883llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
1884 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001885
1886 if (!Entry) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001887 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001888 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001889 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001890 llvm::GlobalValue::InternalLinkage,
1891 C, "\01L_OBJC_CLASS_NAME_",
1892 &CGM.getModule());
1893 Entry->setSection("__TEXT,__cstring,cstring_literals");
1894 UsedGlobals.push_back(Entry);
1895 }
1896
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001897 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001898}
1899
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001900llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
1901 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
1902
1903 if (!Entry) {
1904 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
1905 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001906 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001907 llvm::GlobalValue::InternalLinkage,
1908 C, "\01L_OBJC_METH_VAR_NAME_",
1909 &CGM.getModule());
1910 Entry->setSection("__TEXT,__cstring,cstring_literals");
1911 UsedGlobals.push_back(Entry);
1912 }
1913
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001914 return getConstantGEP(Entry, 0, 0);
1915}
1916
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001917// FIXME: Merge into a single cstring creation function.
1918llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
1919 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
1920}
1921
1922// FIXME: Merge into a single cstring creation function.
1923llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
1924 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
1925}
1926
1927llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
1928 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001929
1930 if (!Entry) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001931 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001932 Entry =
1933 new llvm::GlobalVariable(C->getType(), false,
1934 llvm::GlobalValue::InternalLinkage,
1935 C, "\01L_OBJC_METH_VAR_TYPE_",
1936 &CGM.getModule());
1937 Entry->setSection("__TEXT,__cstring,cstring_literals");
1938 UsedGlobals.push_back(Entry);
1939 }
1940
1941 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001942}
1943
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001944// FIXME: Merge into a single cstring creation function.
Daniel Dunbar12996f52008-08-26 21:51:14 +00001945llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001946 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00001947 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
1948 TypeStr);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001949 return GetMethodVarType(TypeStr);
1950}
1951
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001952// FIXME: Merge into a single cstring creation function.
1953llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
1954 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
1955
1956 if (!Entry) {
1957 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
1958 Entry =
1959 new llvm::GlobalVariable(C->getType(), false,
1960 llvm::GlobalValue::InternalLinkage,
1961 C, "\01L_OBJC_PROP_NAME_ATTR_",
1962 &CGM.getModule());
1963 Entry->setSection("__TEXT,__cstring,cstring_literals");
1964 UsedGlobals.push_back(Entry);
1965 }
1966
1967 return getConstantGEP(Entry, 0, 0);
1968}
1969
1970// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001971// FIXME: This Decl should be more precise.
1972llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
1973 const Decl *Container) {
1974 std::string TypeStr;
1975 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001976 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
1977}
1978
Daniel Dunbarace33292008-08-16 03:19:19 +00001979void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
1980 std::string &NameOut) {
1981 // FIXME: Find the mangling GCC uses.
1982 std::stringstream s;
1983 s << (D->isInstance() ? "-" : "+");
1984 s << "[";
1985 s << D->getClassInterface()->getName();
1986 s << " ";
1987 s << D->getSelector().getName();
1988 s << "]";
1989 NameOut = s.str();
1990}
1991
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001992void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001993 EmitModuleInfo();
1994
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001995 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001996
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001997 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001998 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001999 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002000 }
2001
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002002 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002003 llvm::GlobalValue *GV =
2004 new llvm::GlobalVariable(AT, false,
2005 llvm::GlobalValue::AppendingLinkage,
2006 llvm::ConstantArray::get(AT, Used),
2007 "llvm.used",
2008 &CGM.getModule());
2009
2010 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002011
2012 // Add assembler directives to add lazy undefined symbol references
2013 // for classes which are referenced but not defined. This is
2014 // important for correct linker interaction.
2015
2016 // FIXME: Uh, this isn't particularly portable.
2017 std::stringstream s;
2018 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2019 e = LazySymbols.end(); i != e; ++i) {
2020 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2021 }
2022 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2023 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002024 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002025 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2026 }
2027 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002028}
2029
2030/* *** */
2031
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002032ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbardbdb9512008-08-23 18:37:06 +00002033 : CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002034{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002035 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2036 ASTContext &Ctx = CGM.getContext();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002037
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002038 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002039 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002040 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002041 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2042
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002043 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2044 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002045
2046 // FIXME: It would be nice to unify this with the opaque type, so
2047 // that the IR comes out a bit cleaner.
2048 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2049 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002050
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002051 MethodDescriptionTy =
2052 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002053 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002054 NULL);
2055 CGM.getModule().addTypeName("struct._objc_method_description",
2056 MethodDescriptionTy);
2057
2058 MethodDescriptionListTy =
2059 llvm::StructType::get(IntTy,
2060 llvm::ArrayType::get(MethodDescriptionTy, 0),
2061 NULL);
2062 CGM.getModule().addTypeName("struct._objc_method_description_list",
2063 MethodDescriptionListTy);
2064 MethodDescriptionListPtrTy =
2065 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2066
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002067 PropertyTy = llvm::StructType::get(Int8PtrTy,
2068 Int8PtrTy,
2069 NULL);
2070 CGM.getModule().addTypeName("struct._objc_property",
2071 PropertyTy);
2072
2073 PropertyListTy = llvm::StructType::get(IntTy,
2074 IntTy,
2075 llvm::ArrayType::get(PropertyTy, 0),
2076 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002077 CGM.getModule().addTypeName("struct._objc_property_list",
2078 PropertyListTy);
2079 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2080
2081 // Protocol description structures
2082
2083 ProtocolExtensionTy =
2084 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2085 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2086 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2087 PropertyListPtrTy,
2088 NULL);
2089 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2090 ProtocolExtensionTy);
2091 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2092
2093 // Handle recursive construction of Protocl and ProtocolList types
2094
2095 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2096 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2097
2098 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2099 LongTy,
2100 llvm::ArrayType::get(ProtocolTyHolder, 0),
2101 NULL);
2102 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2103
2104 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002105 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002106 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2107 MethodDescriptionListPtrTy,
2108 MethodDescriptionListPtrTy,
2109 NULL);
2110 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2111
2112 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2113 CGM.getModule().addTypeName("struct._objc_protocol_list",
2114 ProtocolListTy);
2115 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2116
2117 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2118 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2119 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002120
2121 // Class description structures
2122
2123 IvarTy = llvm::StructType::get(Int8PtrTy,
2124 Int8PtrTy,
2125 IntTy,
2126 NULL);
2127 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2128
2129 IvarListTy = llvm::OpaqueType::get();
2130 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2131 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2132
2133 MethodTy = llvm::StructType::get(SelectorPtrTy,
2134 Int8PtrTy,
2135 Int8PtrTy,
2136 NULL);
2137 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2138
2139 MethodListTy = llvm::OpaqueType::get();
2140 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2141 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2142
2143 CacheTy = llvm::OpaqueType::get();
2144 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2145 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2146
2147 ClassExtensionTy =
2148 llvm::StructType::get(IntTy,
2149 Int8PtrTy,
2150 PropertyListPtrTy,
2151 NULL);
2152 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2153 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2154
2155 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2156
2157 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2158 llvm::PointerType::getUnqual(ClassTyHolder),
2159 Int8PtrTy,
2160 LongTy,
2161 LongTy,
2162 LongTy,
2163 IvarListPtrTy,
2164 MethodListPtrTy,
2165 CachePtrTy,
2166 ProtocolListPtrTy,
2167 Int8PtrTy,
2168 ClassExtensionPtrTy,
2169 NULL);
2170 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2171
2172 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2173 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2174 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2175
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002176 CategoryTy = llvm::StructType::get(Int8PtrTy,
2177 Int8PtrTy,
2178 MethodListPtrTy,
2179 MethodListPtrTy,
2180 ProtocolListPtrTy,
2181 IntTy,
2182 PropertyListPtrTy,
2183 NULL);
2184 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2185
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002186 // I'm not sure I like this. The implicit coordination is a bit
2187 // gross. We should solve this in a reasonable fashion because this
2188 // is a pretty common task (match some runtime data structure with
2189 // an LLVM data structure).
2190
2191 // FIXME: This is leaked.
2192 // FIXME: Merge with rewriter code?
2193 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2194 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002195 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002196 FieldDecl *FieldDecls[2];
2197 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2198 Ctx.getObjCIdType());
2199 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2200 Ctx.getObjCClassType());
Ted Kremenek46a837c2008-09-05 17:16:31 +00002201 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002202
2203 SuperCTy = Ctx.getTagDeclType(RD);
2204 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2205
2206 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002207 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbar15245e52008-08-23 04:28:29 +00002208
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002209 // Global metadata structures
2210
2211 SymtabTy = llvm::StructType::get(LongTy,
2212 SelectorPtrTy,
2213 ShortTy,
2214 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002215 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002216 NULL);
2217 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2218 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2219
2220 ModuleTy =
2221 llvm::StructType::get(LongTy,
2222 LongTy,
2223 Int8PtrTy,
2224 SymtabPtrTy,
2225 NULL);
2226 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002227
Daniel Dunbarf7103722008-09-24 03:38:44 +00002228 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002229
2230 std::vector<const llvm::Type*> Params;
2231 Params.push_back(ObjectPtrTy);
2232 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002233 MessageSendFn =
2234 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2235 Params,
2236 true),
2237 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002238
2239 Params.clear();
2240 Params.push_back(Int8PtrTy);
2241 Params.push_back(ObjectPtrTy);
2242 Params.push_back(SelectorPtrTy);
2243 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002244 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2245 Params,
2246 true),
2247 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002248
2249 Params.clear();
2250 Params.push_back(ObjectPtrTy);
2251 Params.push_back(SelectorPtrTy);
2252 // FIXME: This should be long double on x86_64?
2253 MessageSendFpretFn =
2254 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2255 Params,
2256 true),
2257 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002258
2259 Params.clear();
2260 Params.push_back(SuperPtrTy);
2261 Params.push_back(SelectorPtrTy);
2262 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002263 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2264 Params,
2265 true),
2266 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002267
2268 Params.clear();
2269 Params.push_back(Int8PtrTy);
2270 Params.push_back(SuperPtrTy);
2271 Params.push_back(SelectorPtrTy);
2272 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002273 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2274 Params,
2275 true),
2276 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002277
2278 // There is no objc_msgSendSuper_fpret? How can that work?
2279 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00002280
Daniel Dunbarf7103722008-09-24 03:38:44 +00002281 // Property manipulation functions.
2282
2283 Params.clear();
2284 Params.push_back(ObjectPtrTy);
2285 Params.push_back(SelectorPtrTy);
2286 Params.push_back(LongTy);
2287 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2288 GetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002289 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2290 Params,
2291 false),
2292 "objc_getProperty");
2293
Daniel Dunbarf7103722008-09-24 03:38:44 +00002294 Params.clear();
2295 Params.push_back(ObjectPtrTy);
2296 Params.push_back(SelectorPtrTy);
2297 Params.push_back(LongTy);
Daniel Dunbarf7f6c7b2008-09-24 06:32:09 +00002298 Params.push_back(ObjectPtrTy);
Daniel Dunbarf7103722008-09-24 03:38:44 +00002299 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2300 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2301 SetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002302 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2303 Params,
2304 false),
2305 "objc_setProperty");
Daniel Dunbarf7103722008-09-24 03:38:44 +00002306
Anders Carlsson58d16242008-08-31 04:05:03 +00002307 // Enumeration mutation.
Daniel Dunbarf7103722008-09-24 03:38:44 +00002308
Anders Carlsson58d16242008-08-31 04:05:03 +00002309 Params.clear();
2310 Params.push_back(ObjectPtrTy);
2311 EnumerationMutationFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002312 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2313 Params,
2314 false),
2315 "objc_enumerationMutation");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002316
2317 // FIXME: This is the size of the setjmp buffer and should be
2318 // target specific. 18 is what's used on 32-bit X86.
2319 uint64_t SetJmpBufferSize = 18;
2320
2321 // Exceptions
2322 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00002323 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002324
2325 ExceptionDataTy =
2326 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2327 SetJmpBufferSize),
2328 StackPtrTy, NULL);
2329 CGM.getModule().addTypeName("struct._objc_exception_data",
2330 ExceptionDataTy);
2331
2332 Params.clear();
2333 Params.push_back(ObjectPtrTy);
2334 ExceptionThrowFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002335 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2336 Params,
2337 false),
2338 "objc_exception_throw");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002339
2340 Params.clear();
2341 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2342 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002343 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2344 Params,
2345 false),
2346 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002347 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002348 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2349 Params,
2350 false),
2351 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002352 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002353 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2354 Params,
2355 false),
2356 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002357
2358 Params.clear();
2359 Params.push_back(ClassPtrTy);
2360 Params.push_back(ObjectPtrTy);
2361 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002362 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2363 Params,
2364 false),
2365 "objc_exception_match");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002366
2367 Params.clear();
2368 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2369 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002370 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2371 Params,
2372 false),
2373 "_setjmp");
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002374}
2375
2376ObjCTypesHelper::~ObjCTypesHelper() {
2377}
2378
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002379/* *** */
2380
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002381CodeGen::CGObjCRuntime *
2382CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002383 return new CGObjCMac(CGM);
2384}