blob: a8f6bbab9b4f25bf31ea7ac9fd09d90064fce08b [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 Dunbar35b777f2008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.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;
Chris Lattnerdd978702008-11-15 21:26:17 +0000158
159 /// SyncEnterFn - LLVM object_sync_enter function.
160 llvm::Function *SyncEnterFn;
161
162 /// SyncExitFn - LLVM object_sync_exit function.
163 llvm::Function *SyncExitFn;
164
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000165public:
166 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
167 ~ObjCTypesHelper();
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000168
169
170 llvm::Function *getSendFn(bool IsSuper) {
171 return IsSuper ? MessageSendSuperFn : MessageSendFn;
172 }
173
174 llvm::Function *getSendStretFn(bool IsSuper) {
175 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
176 }
177
178 llvm::Function *getSendFpretFn(bool IsSuper) {
179 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
180 }
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000181};
182
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000183class CGObjCMac : public CodeGen::CGObjCRuntime {
184private:
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000185 CodeGen::CodeGenModule &CGM;
186 ObjCTypesHelper ObjCTypes;
187 /// ObjCABI - FIXME: Not sure yet.
188 unsigned ObjCABI;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000189
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000190 /// LazySymbols - Symbols to generate a lazy reference for. See
191 /// DefinedSymbols and FinishModule().
192 std::set<IdentifierInfo*> LazySymbols;
193
194 /// DefinedSymbols - External symbols which are defined by this
195 /// module. The symbols in this list and LazySymbols are used to add
196 /// special linker symbols which ensure that Objective-C modules are
197 /// linked properly.
198 std::set<IdentifierInfo*> DefinedSymbols;
199
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000200 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000201 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000202
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000203 /// MethodVarNames - uniqued method variable names.
204 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
205
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000206 /// MethodVarTypes - uniqued method type signatures. We have to use
207 /// a StringMap here because have no other unique reference.
208 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
209
Daniel Dunbar12996f52008-08-26 21:51:14 +0000210 /// MethodDefinitions - map of methods which have been defined in
211 /// this translation unit.
212 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
213
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000214 /// PropertyNames - uniqued method variable names.
215 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
216
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000217 /// ClassReferences - uniqued class references.
218 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
219
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000220 /// SelectorReferences - uniqued selector references.
221 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
222
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000223 /// Protocols - Protocols for which an objc_protocol structure has
224 /// been emitted. Forward declarations are handled by creating an
225 /// empty structure whose initializer is filled in when/if defined.
226 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
227
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000228 /// DefinedProtocols - Protocols which have actually been
229 /// defined. We should not need this, see FIXME in GenerateProtocol.
230 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
231
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000232 /// DefinedClasses - List of defined classes.
233 std::vector<llvm::GlobalValue*> DefinedClasses;
234
235 /// DefinedCategories - List of defined categories.
236 std::vector<llvm::GlobalValue*> DefinedCategories;
237
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000238 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000239 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000240 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000241
242 /// EmitImageInfo - Emit the image info marker used to encode some module
243 /// level information.
244 void EmitImageInfo();
245
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000246 /// EmitModuleInfo - Another marker encoding module level
247 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000248 void EmitModuleInfo();
249
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000250 /// EmitModuleSymols - Emit module symbols, the list of defined
251 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000252 llvm::Constant *EmitModuleSymbols();
253
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000254 /// FinishModule - Write out global data structures at the end of
255 /// processing a translation unit.
256 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000257
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000258 /// EmitClassExtension - Generate the class extension structure used
259 /// to store the weak ivar layout and properties. The return value
260 /// has type ClassExtensionPtrTy.
261 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
262
263 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
264 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000265 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000266 const ObjCInterfaceDecl *ID);
267
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000268 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000269 QualType ResultType,
270 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000271 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000272 QualType Arg0Ty,
273 bool IsSuper,
274 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000275
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000276 /// EmitIvarList - Emit the ivar list for the given
277 /// implementation. If ForClass is true the list of class ivars
278 /// (i.e. metaclass ivars) is emitted, otherwise the list of
279 /// interface ivars will be emitted. The return value has type
280 /// IvarListPtrTy.
281 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
282 bool ForClass,
283 const llvm::Type *InterfaceTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000284
285 /// EmitMetaClass - Emit a forward reference to the class structure
286 /// for the metaclass of the given interface. The return value has
287 /// type ClassPtrTy.
288 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
289
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000290 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000291 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000292 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
293 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000294 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000295 const ConstantVector &Methods);
296
297 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
298
299 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000300
301 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000302 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000303 llvm::Constant *EmitMethodList(const std::string &Name,
304 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000305 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000306
307 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000308 /// method declarations.
309 /// - TypeName: The name for the type containing the methods.
310 /// - IsProtocol: True iff these methods are for a protocol.
311 /// - ClassMethds: True iff these are class methods.
312 /// - Required: When true, only "required" methods are
313 /// listed. Similarly, when false only "optional" methods are
314 /// listed. For classes this should always be true.
315 /// - begin, end: The method list to output.
316 ///
317 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000318 llvm::Constant *EmitMethodDescList(const std::string &Name,
319 const char *Section,
320 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000321
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000322 /// EmitPropertyList - Emit the given property list. The return
323 /// value has type PropertyListPtrTy.
324 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000325 const Decl *Container,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000326 ObjCPropertyDecl * const *begin,
327 ObjCPropertyDecl * const *end);
328
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000329 /// GetOrEmitProtocol - Get the protocol object for the given
330 /// declaration, emitting it if necessary. The return value has type
331 /// ProtocolPtrTy.
332 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
333
334 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
335 /// object for the given declaration, emitting it if needed. These
336 /// forward references will be filled in with empty bodies if no
337 /// definition is seen. The return value has type ProtocolPtrTy.
338 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
339
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000340 /// EmitProtocolExtension - Generate the protocol extension
341 /// structure used to store optional instance and class methods, and
342 /// protocol properties. The return value has type
343 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000344 llvm::Constant *
345 EmitProtocolExtension(const ObjCProtocolDecl *PD,
346 const ConstantVector &OptInstanceMethods,
347 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000348
349 /// EmitProtocolList - Generate the list of referenced
350 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000351 llvm::Constant *EmitProtocolList(const std::string &Name,
352 ObjCProtocolDecl::protocol_iterator begin,
353 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000354
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000355 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
356 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000357 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000358
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000359 /// GetProtocolRef - Return a reference to the internal protocol
360 /// description, creating an empty one if it has not been
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000361 /// defined. The return value has type ProtocolPtrTy.
362 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000363
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000364 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000365 /// name. The return value has type char *.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000366 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000367
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000368 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000369 /// selector's name. The return value has type char *.
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000370 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000371 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000372 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000373
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000374 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000375 /// selector's name. The return value has type char *.
376
377 // FIXME: This is a horrible name.
Daniel Dunbar12996f52008-08-26 21:51:14 +0000378 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000379 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000380
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000381 /// GetPropertyName - Return a unique constant for the given
382 /// name. The return value has type char *.
383 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
384
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000385 // FIXME: This can be dropped once string functions are unified.
386 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
387 const Decl *Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000388
Daniel Dunbarace33292008-08-16 03:19:19 +0000389 /// GetNameForMethod - Return a name for the given method.
390 /// \param[out] NameOut - The return value.
391 void GetNameForMethod(const ObjCMethodDecl *OMD,
392 std::string &NameOut);
393
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000394public:
395 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000396 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000397
Daniel Dunbara04840b2008-08-23 03:46:30 +0000398 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000399 QualType ResultType,
400 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000401 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000402 bool IsClassMessage,
403 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000404
Daniel Dunbara04840b2008-08-23 03:46:30 +0000405 virtual CodeGen::RValue
406 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000407 QualType ResultType,
408 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000409 const ObjCInterfaceDecl *Class,
410 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000411 bool IsClassMessage,
412 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000413
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000414 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000415 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000416
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000417 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000418
Daniel Dunbarac93e472008-08-15 22:20:32 +0000419 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000420
Daniel Dunbarac93e472008-08-15 22:20:32 +0000421 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000422
Daniel Dunbarac93e472008-08-15 22:20:32 +0000423 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000424
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000425 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000426 const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000427
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000428 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000429
430 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbarf7103722008-09-24 03:38:44 +0000431 virtual llvm::Function *GetPropertyGetFunction();
432 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson58d16242008-08-31 04:05:03 +0000433 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000434
435 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
436 const ObjCAtTryStmt &S);
437 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
438 const ObjCAtThrowStmt &S);
Chris Lattnerdd978702008-11-15 21:26:17 +0000439 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
440 const ObjCAtSynchronizedStmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000441
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000442};
443} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000444
445/* *** Helper Functions *** */
446
447/// getConstantGEP() - Help routine to construct simple GEPs.
448static llvm::Constant *getConstantGEP(llvm::Constant *C,
449 unsigned idx0,
450 unsigned idx1) {
451 llvm::Value *Idxs[] = {
452 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
453 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
454 };
455 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
456}
457
458/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000459
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000460CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
461 : CGM(cgm),
462 ObjCTypes(cgm),
463 ObjCABI(1)
464{
465 // FIXME: How does this get set in GCC? And what does it even mean?
466 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
467 ObjCABI = 2;
468
469 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000470}
471
Daniel Dunbar434627a2008-08-16 00:25:02 +0000472/// GetClass - Return a reference to the class for the given interface
473/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000474llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000475 const ObjCInterfaceDecl *ID) {
476 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000477}
478
479/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000480llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000481 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000482}
483
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000484/// Generate a constant CFString object.
485/*
486 struct __builtin_CFString {
487 const int *isa; // point to __CFConstantStringClassReference
488 int flags;
489 const char *str;
490 long length;
491 };
492*/
493
494llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000495 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000496}
497
498/// Generates a message send where the super is the receiver. This is
499/// a message send to self with special delivery semantics indicating
500/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000501CodeGen::RValue
502CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000503 QualType ResultType,
504 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000505 const ObjCInterfaceDecl *Class,
506 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000507 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000508 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000509 // Create and init a super structure; this is a (receiver, class)
510 // pair we will pass to objc_msgSendSuper.
511 llvm::Value *ObjCSuper =
512 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
513 llvm::Value *ReceiverAsObject =
514 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
515 CGF.Builder.CreateStore(ReceiverAsObject,
516 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000517
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000518 // If this is a class message the metaclass is passed as the target.
519 llvm::Value *Target;
520 if (IsClassMessage) {
521 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
522 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
523 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
524 Target = Super;
525 } else {
526 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
527 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000528 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
529 // and ObjCTypes types.
530 const llvm::Type *ClassTy =
531 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000532 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000533 CGF.Builder.CreateStore(Target,
534 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
535
Daniel Dunbardd851282008-08-30 05:35:15 +0000536 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000537 ObjCSuper, ObjCTypes.SuperPtrCTy,
538 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000539}
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000540
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000541/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000542CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000543 QualType ResultType,
544 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000545 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000546 bool IsClassMessage,
547 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000548 llvm::Value *Arg0 =
549 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +0000550 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000551 Arg0, CGF.getContext().getObjCIdType(),
552 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000553}
554
555CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000556 QualType ResultType,
557 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000558 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000559 QualType Arg0Ty,
560 bool IsSuper,
561 const CallArgList &CallArgs) {
562 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000563 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
564 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
565 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000566 CGF.getContext().getObjCSelType()));
567 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +0000568
Daniel Dunbara9976a22008-09-10 07:00:50 +0000569 const llvm::FunctionType *FTy =
570 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
571 false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000572
573 llvm::Constant *Fn;
574 if (CGM.ReturnTypeUsesSret(ResultType)) {
575 Fn = ObjCTypes.getSendStretFn(IsSuper);
576 } else if (ResultType->isFloatingType()) {
577 // FIXME: Sadly, this is wrong. This actually depends on the
578 // architecture. This happens to be right for x86-32 though.
579 Fn = ObjCTypes.getSendFpretFn(IsSuper);
580 } else {
581 Fn = ObjCTypes.getSendFn(IsSuper);
582 }
Daniel Dunbara9976a22008-09-10 07:00:50 +0000583 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +0000584 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000585}
586
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000587llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000588 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +0000589 // FIXME: I don't understand why gcc generates this, or where it is
590 // resolved. Investigate. Its also wasteful to look this up over and
591 // over.
592 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
593
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000594 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
595 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000596}
597
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000598void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
599 // FIXME: We shouldn't need this, the protocol decl should contain
600 // enough information to tell us whether this was a declaration or a
601 // definition.
602 DefinedProtocols.insert(PD->getIdentifier());
603
604 // If we have generated a forward reference to this protocol, emit
605 // it now. Otherwise do nothing, the protocol objects are lazily
606 // emitted.
607 if (Protocols.count(PD->getIdentifier()))
608 GetOrEmitProtocol(PD);
609}
610
611llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
612 if (DefinedProtocols.count(PD->getIdentifier()))
613 return GetOrEmitProtocol(PD);
614 return GetOrEmitProtocolRef(PD);
615}
616
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000617/*
618 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
619 struct _objc_protocol {
620 struct _objc_protocol_extension *isa;
621 char *protocol_name;
622 struct _objc_protocol_list *protocol_list;
623 struct _objc__method_prototype_list *instance_methods;
624 struct _objc__method_prototype_list *class_methods
625 };
626
627 See EmitProtocolExtension().
628*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000629llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
630 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
631
632 // Early exit if a defining object has already been generated.
633 if (Entry && Entry->hasInitializer())
634 return Entry;
635
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000636 // FIXME: I don't understand why gcc generates this, or where it is
637 // resolved. Investigate. Its also wasteful to look this up over and
638 // over.
639 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
640
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000641 const char *ProtocolName = PD->getIdentifierName();
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000642
643 // Construct method lists.
644 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
645 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
646 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
647 e = PD->instmeth_end(); i != e; ++i) {
648 ObjCMethodDecl *MD = *i;
649 llvm::Constant *C = GetMethodDescriptionConstant(MD);
650 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
651 OptInstanceMethods.push_back(C);
652 } else {
653 InstanceMethods.push_back(C);
654 }
655 }
656
657 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
658 e = PD->classmeth_end(); i != e; ++i) {
659 ObjCMethodDecl *MD = *i;
660 llvm::Constant *C = GetMethodDescriptionConstant(MD);
661 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
662 OptClassMethods.push_back(C);
663 } else {
664 ClassMethods.push_back(C);
665 }
666 }
667
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000668 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000669 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000670 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000671 Values[2] =
672 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
673 PD->protocol_begin(),
674 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000675 Values[3] =
676 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
677 + PD->getName(),
678 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
679 InstanceMethods);
680 Values[4] =
681 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
682 + PD->getName(),
683 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
684 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000685 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
686 Values);
687
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000688 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000689 // Already created, fix the linkage and update the initializer.
690 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000691 Entry->setInitializer(Init);
692 } else {
693 Entry =
694 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
695 llvm::GlobalValue::InternalLinkage,
696 Init,
697 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
698 &CGM.getModule());
699 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
700 UsedGlobals.push_back(Entry);
701 // FIXME: Is this necessary? Why only for protocol?
702 Entry->setAlignment(4);
703 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000704
705 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000706}
707
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000708llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000709 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
710
711 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000712 // We use the initializer as a marker of whether this is a forward
713 // reference or not. At module finalization we add the empty
714 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000715 Entry =
716 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000717 llvm::GlobalValue::ExternalLinkage,
718 0,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000719 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
720 &CGM.getModule());
721 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
722 UsedGlobals.push_back(Entry);
723 // FIXME: Is this necessary? Why only for protocol?
724 Entry->setAlignment(4);
725 }
726
727 return Entry;
728}
729
730/*
731 struct _objc_protocol_extension {
732 uint32_t size;
733 struct objc_method_description_list *optional_instance_methods;
734 struct objc_method_description_list *optional_class_methods;
735 struct objc_property_list *instance_properties;
736 };
737*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000738llvm::Constant *
739CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
740 const ConstantVector &OptInstanceMethods,
741 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000742 uint64_t Size =
743 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
744 std::vector<llvm::Constant*> Values(4);
745 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000746 Values[1] =
747 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
748 + PD->getName(),
749 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
750 OptInstanceMethods);
751 Values[2] =
752 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
753 + PD->getName(),
754 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
755 OptClassMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000756 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
757 PD->getName(),
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000758 0,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000759 PD->classprop_begin(),
760 PD->classprop_end());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000761
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000762 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000763 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
764 Values[3]->isNullValue())
765 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
766
767 llvm::Constant *Init =
768 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
769 llvm::GlobalVariable *GV =
770 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
771 llvm::GlobalValue::InternalLinkage,
772 Init,
773 (std::string("\01L_OBJC_PROTOCOLEXT_") +
774 PD->getName()),
775 &CGM.getModule());
776 // No special section, but goes in llvm.used
777 UsedGlobals.push_back(GV);
778
779 return GV;
780}
781
782/*
783 struct objc_protocol_list {
784 struct objc_protocol_list *next;
785 long count;
786 Protocol *list[];
787 };
788*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000789llvm::Constant *
790CGObjCMac::EmitProtocolList(const std::string &Name,
791 ObjCProtocolDecl::protocol_iterator begin,
792 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000793 std::vector<llvm::Constant*> ProtocolRefs;
794
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000795 for (; begin != end; ++begin)
796 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000797
798 // Just return null for empty protocol lists
799 if (ProtocolRefs.empty())
800 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
801
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000802 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000803 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
804
805 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000806 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000807 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
808 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
809 Values[2] =
810 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
811 ProtocolRefs.size()),
812 ProtocolRefs);
813
814 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
815 llvm::GlobalVariable *GV =
816 new llvm::GlobalVariable(Init->getType(), false,
817 llvm::GlobalValue::InternalLinkage,
818 Init,
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000819 Name,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000820 &CGM.getModule());
821 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
822 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
823}
824
825/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000826 struct _objc_property {
827 const char * const name;
828 const char * const attributes;
829 };
830
831 struct _objc_property_list {
832 uint32_t entsize; // sizeof (struct _objc_property)
833 uint32_t prop_count;
834 struct _objc_property[prop_count];
835 };
836*/
837llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000838 const Decl *Container,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000839 ObjCPropertyDecl * const *begin,
840 ObjCPropertyDecl * const *end) {
841 std::vector<llvm::Constant*> Properties, Prop(2);
842 for (; begin != end; ++begin) {
843 const ObjCPropertyDecl *PD = *begin;
844 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000845 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000846 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
847 Prop));
848 }
849
850 // Return null for empty list.
851 if (Properties.empty())
852 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
853
854 unsigned PropertySize =
855 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
856 std::vector<llvm::Constant*> Values(3);
857 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
858 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
859 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
860 Properties.size());
861 Values[2] = llvm::ConstantArray::get(AT, Properties);
862 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
863
864 llvm::GlobalVariable *GV =
865 new llvm::GlobalVariable(Init->getType(), false,
866 llvm::GlobalValue::InternalLinkage,
867 Init,
868 Name,
869 &CGM.getModule());
870 // No special section on property lists?
871 UsedGlobals.push_back(GV);
872 return llvm::ConstantExpr::getBitCast(GV,
873 ObjCTypes.PropertyListPtrTy);
874
875}
876
877/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000878 struct objc_method_description_list {
879 int count;
880 struct objc_method_description list[];
881 };
882*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000883llvm::Constant *
884CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
885 std::vector<llvm::Constant*> Desc(2);
886 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
887 ObjCTypes.SelectorPtrTy);
888 Desc[1] = GetMethodVarType(MD);
889 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
890 Desc);
891}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000892
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000893llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
894 const char *Section,
895 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000896 // Return null for empty list.
897 if (Methods.empty())
898 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
899
900 std::vector<llvm::Constant*> Values(2);
901 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
902 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
903 Methods.size());
904 Values[1] = llvm::ConstantArray::get(AT, Methods);
905 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
906
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000907 llvm::GlobalVariable *GV =
908 new llvm::GlobalVariable(Init->getType(), false,
909 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000910 Init, Name, &CGM.getModule());
911 GV->setSection(Section);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000912 UsedGlobals.push_back(GV);
913 return llvm::ConstantExpr::getBitCast(GV,
914 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000915}
916
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000917/*
918 struct _objc_category {
919 char *category_name;
920 char *class_name;
921 struct _objc_method_list *instance_methods;
922 struct _objc_method_list *class_methods;
923 struct _objc_protocol_list *protocols;
924 uint32_t size; // <rdar://4585769>
925 struct _objc_property_list *instance_properties;
926 };
927 */
Daniel Dunbarac93e472008-08-15 22:20:32 +0000928void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000929 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
930
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000931 // FIXME: This is poor design, the OCD should have a pointer to the
932 // category decl. Additionally, note that Category can be null for
933 // the @implementation w/o an @interface case. Sema should just
934 // create one for us as it does for @implementation so everyone else
935 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000936 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000937 const ObjCCategoryDecl *Category =
938 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000939 std::string ExtName(std::string(Interface->getName()) +
940 "_" +
941 OCD->getName());
942
Daniel Dunbar12996f52008-08-26 21:51:14 +0000943 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
944 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
945 e = OCD->instmeth_end(); i != e; ++i) {
946 // Instance methods should always be defined.
947 InstanceMethods.push_back(GetMethodConstant(*i));
948 }
949 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
950 e = OCD->classmeth_end(); i != e; ++i) {
951 // Class methods should always be defined.
952 ClassMethods.push_back(GetMethodConstant(*i));
953 }
954
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000955 std::vector<llvm::Constant*> Values(7);
956 Values[0] = GetClassName(OCD->getIdentifier());
957 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000958 Values[2] =
959 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
960 ExtName,
961 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000962 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000963 Values[3] =
964 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
965 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000966 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000967 if (Category) {
968 Values[4] =
969 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
970 Category->protocol_begin(),
971 Category->protocol_end());
972 } else {
973 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
974 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000975 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000976
977 // If there is no category @interface then there can be no properties.
978 if (Category) {
979 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000980 OCD,
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000981 Category->classprop_begin(),
982 Category->classprop_end());
983 } else {
984 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
985 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000986
987 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
988 Values);
989
990 llvm::GlobalVariable *GV =
991 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
992 llvm::GlobalValue::InternalLinkage,
993 Init,
994 std::string("\01L_OBJC_CATEGORY_")+ExtName,
995 &CGM.getModule());
996 GV->setSection("__OBJC,__category,regular,no_dead_strip");
997 UsedGlobals.push_back(GV);
998 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000999}
1000
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001001// FIXME: Get from somewhere?
1002enum ClassFlags {
1003 eClassFlags_Factory = 0x00001,
1004 eClassFlags_Meta = 0x00002,
1005 // <rdr://5142207>
1006 eClassFlags_HasCXXStructors = 0x02000,
1007 eClassFlags_Hidden = 0x20000,
1008 eClassFlags_ABI2_Hidden = 0x00010,
1009 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1010};
1011
1012// <rdr://5142207&4705298&4843145>
1013static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1014 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1015 // FIXME: Support -fvisibility
1016 switch (attr->getVisibility()) {
1017 default:
1018 assert(0 && "Unknown visibility");
1019 return false;
1020 case VisibilityAttr::DefaultVisibility:
1021 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1022 return false;
1023 case VisibilityAttr::HiddenVisibility:
1024 return true;
1025 }
1026 } else {
1027 return false; // FIXME: Support -fvisibility
1028 }
1029}
1030
1031/*
1032 struct _objc_class {
1033 Class isa;
1034 Class super_class;
1035 const char *name;
1036 long version;
1037 long info;
1038 long instance_size;
1039 struct _objc_ivar_list *ivars;
1040 struct _objc_method_list *methods;
1041 struct _objc_cache *cache;
1042 struct _objc_protocol_list *protocols;
1043 // Objective-C 1.0 extensions (<rdr://4585769>)
1044 const char *ivar_layout;
1045 struct _objc_class_ext *ext;
1046 };
1047
1048 See EmitClassExtension();
1049 */
1050void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001051 DefinedSymbols.insert(ID->getIdentifier());
1052
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001053 const char *ClassName = ID->getIdentifierName();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001054 // FIXME: Gross
1055 ObjCInterfaceDecl *Interface =
1056 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001057 llvm::Constant *Protocols =
1058 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1059 Interface->protocol_begin(),
1060 Interface->protocol_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001061 const llvm::Type *InterfaceTy =
1062 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1063 unsigned Flags = eClassFlags_Factory;
1064 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1065
1066 // FIXME: Set CXX-structors flag.
1067 if (IsClassHidden(ID->getClassInterface()))
1068 Flags |= eClassFlags_Hidden;
1069
Daniel Dunbar12996f52008-08-26 21:51:14 +00001070 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1071 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1072 e = ID->instmeth_end(); i != e; ++i) {
1073 // Instance methods should always be defined.
1074 InstanceMethods.push_back(GetMethodConstant(*i));
1075 }
1076 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1077 e = ID->classmeth_end(); i != e; ++i) {
1078 // Class methods should always be defined.
1079 ClassMethods.push_back(GetMethodConstant(*i));
1080 }
1081
1082 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1083 e = ID->propimpl_end(); i != e; ++i) {
1084 ObjCPropertyImplDecl *PID = *i;
1085
1086 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1087 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1088
1089 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1090 if (llvm::Constant *C = GetMethodConstant(MD))
1091 InstanceMethods.push_back(C);
1092 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1093 if (llvm::Constant *C = GetMethodConstant(MD))
1094 InstanceMethods.push_back(C);
1095 }
1096 }
1097
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001098 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001099 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001100 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001101 // Record a reference to the super class.
1102 LazySymbols.insert(Super->getIdentifier());
1103
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001104 Values[ 1] =
1105 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1106 ObjCTypes.ClassPtrTy);
1107 } else {
1108 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1109 }
1110 Values[ 2] = GetClassName(ID->getIdentifier());
1111 // Version is always 0.
1112 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1113 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1114 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1115 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001116 Values[ 7] =
1117 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1118 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001119 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001120 // cache is always NULL.
1121 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1122 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001123 // FIXME: Set ivar_layout
1124 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001125 Values[11] = EmitClassExtension(ID);
1126 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1127 Values);
1128
1129 llvm::GlobalVariable *GV =
1130 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1131 llvm::GlobalValue::InternalLinkage,
1132 Init,
1133 std::string("\01L_OBJC_CLASS_")+ClassName,
1134 &CGM.getModule());
1135 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1136 UsedGlobals.push_back(GV);
1137 // FIXME: Why?
1138 GV->setAlignment(32);
1139 DefinedClasses.push_back(GV);
1140}
1141
1142llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1143 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001144 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001145 const ConstantVector &Methods) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001146 const char *ClassName = ID->getIdentifierName();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001147 unsigned Flags = eClassFlags_Meta;
1148 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1149
1150 if (IsClassHidden(ID->getClassInterface()))
1151 Flags |= eClassFlags_Hidden;
1152
1153 std::vector<llvm::Constant*> Values(12);
1154 // The isa for the metaclass is the root of the hierarchy.
1155 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1156 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1157 Root = Super;
1158 Values[ 0] =
1159 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1160 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001161 // The super class for the metaclass is emitted as the name of the
1162 // super class. The runtime fixes this up to point to the
1163 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001164 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1165 Values[ 1] =
1166 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1167 ObjCTypes.ClassPtrTy);
1168 } else {
1169 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1170 }
1171 Values[ 2] = GetClassName(ID->getIdentifier());
1172 // Version is always 0.
1173 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1174 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1175 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1176 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001177 Values[ 7] =
1178 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1179 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001180 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001181 // cache is always NULL.
1182 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1183 Values[ 9] = Protocols;
1184 // ivar_layout for metaclass is always NULL.
1185 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1186 // The class extension is always unused for metaclasses.
1187 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1188 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1189 Values);
1190
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001191 std::string Name("\01L_OBJC_METACLASS_");
1192 Name += ClassName;
1193
1194 // Check for a forward reference.
1195 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1196 if (GV) {
1197 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1198 "Forward metaclass reference has incorrect type.");
1199 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1200 GV->setInitializer(Init);
1201 } else {
1202 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1203 llvm::GlobalValue::InternalLinkage,
1204 Init, Name,
1205 &CGM.getModule());
1206 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001207 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1208 UsedGlobals.push_back(GV);
1209 // FIXME: Why?
1210 GV->setAlignment(32);
1211
1212 return GV;
1213}
1214
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001215llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1216 std::string Name("\01L_OBJC_METACLASS_");
1217 Name += ID->getName();
1218
1219 // FIXME: Should we look these up somewhere other than the
1220 // module. Its a bit silly since we only generate these while
1221 // processing an implementation, so exactly one pointer would work
1222 // if know when we entered/exitted an implementation block.
1223
1224 // Check for an existing forward reference.
1225 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1226 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1227 "Forward metaclass reference has incorrect type.");
1228 return GV;
1229 } else {
1230 // Generate as an external reference to keep a consistent
1231 // module. This will be patched up when we emit the metaclass.
1232 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1233 llvm::GlobalValue::ExternalLinkage,
1234 0,
1235 Name,
1236 &CGM.getModule());
1237 }
1238}
1239
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001240/*
1241 struct objc_class_ext {
1242 uint32_t size;
1243 const char *weak_ivar_layout;
1244 struct _objc_property_list *properties;
1245 };
1246*/
1247llvm::Constant *
1248CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1249 uint64_t Size =
1250 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1251
1252 std::vector<llvm::Constant*> Values(3);
1253 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001254 // FIXME: Output weak_ivar_layout string.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001255 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001256 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1257 ID->getName(),
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001258 ID,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001259 ID->getClassInterface()->classprop_begin(),
1260 ID->getClassInterface()->classprop_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001261
1262 // Return null if no extension bits are used.
1263 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1264 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1265
1266 llvm::Constant *Init =
1267 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1268 llvm::GlobalVariable *GV =
1269 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1270 llvm::GlobalValue::InternalLinkage,
1271 Init,
1272 (std::string("\01L_OBJC_CLASSEXT_") +
1273 ID->getName()),
1274 &CGM.getModule());
1275 // No special section, but goes in llvm.used
1276 UsedGlobals.push_back(GV);
1277
1278 return GV;
1279}
1280
1281/*
1282 struct objc_ivar {
1283 char *ivar_name;
1284 char *ivar_type;
1285 int ivar_offset;
1286 };
1287
1288 struct objc_ivar_list {
1289 int ivar_count;
1290 struct objc_ivar list[count];
1291 };
1292 */
1293llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1294 bool ForClass,
1295 const llvm::Type *InterfaceTy) {
1296 std::vector<llvm::Constant*> Ivars, Ivar(3);
1297
1298 // When emitting the root class GCC emits ivar entries for the
1299 // actual class structure. It is not clear if we need to follow this
1300 // behavior; for now lets try and get away with not doing it. If so,
1301 // the cleanest solution would be to make up an ObjCInterfaceDecl
1302 // for the class.
1303 if (ForClass)
1304 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1305
1306 const llvm::StructLayout *Layout =
1307 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1308 for (ObjCInterfaceDecl::ivar_iterator
1309 i = ID->getClassInterface()->ivar_begin(),
1310 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1311 ObjCIvarDecl *V = *i;
1312 unsigned Offset =
1313 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1314 std::string TypeStr;
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001315 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001316 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001317 Ivar[1] = GetMethodVarType(TypeStr);
1318 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001319 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001320 }
1321
1322 // Return null for empty list.
1323 if (Ivars.empty())
1324 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1325
1326 std::vector<llvm::Constant*> Values(2);
1327 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1328 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1329 Ivars.size());
1330 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1331 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1332
1333 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1334 "\01L_OBJC_INSTANCE_VARIABLES_");
1335 llvm::GlobalVariable *GV =
1336 new llvm::GlobalVariable(Init->getType(), false,
1337 llvm::GlobalValue::InternalLinkage,
1338 Init,
1339 std::string(Prefix) + ID->getName(),
1340 &CGM.getModule());
1341 if (ForClass) {
1342 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1343 // FIXME: Why is this only here?
1344 GV->setAlignment(32);
1345 } else {
1346 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1347 }
1348 UsedGlobals.push_back(GV);
1349 return llvm::ConstantExpr::getBitCast(GV,
1350 ObjCTypes.IvarListPtrTy);
1351}
1352
1353/*
1354 struct objc_method {
1355 SEL method_name;
1356 char *method_types;
1357 void *method;
1358 };
1359
1360 struct objc_method_list {
1361 struct objc_method_list *obsolete;
1362 int count;
1363 struct objc_method methods_list[count];
1364 };
1365*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001366
1367/// GetMethodConstant - Return a struct objc_method constant for the
1368/// given method if it has been defined. The result is null if the
1369/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001370llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001371 // FIXME: Use DenseMap::lookup
1372 llvm::Function *Fn = MethodDefinitions[MD];
1373 if (!Fn)
1374 return 0;
1375
1376 std::vector<llvm::Constant*> Method(3);
1377 Method[0] =
1378 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1379 ObjCTypes.SelectorPtrTy);
1380 Method[1] = GetMethodVarType(MD);
1381 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1382 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1383}
1384
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001385llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1386 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001387 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001388 // Return null for empty list.
1389 if (Methods.empty())
1390 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1391
1392 std::vector<llvm::Constant*> Values(3);
1393 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1394 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1395 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1396 Methods.size());
1397 Values[2] = llvm::ConstantArray::get(AT, Methods);
1398 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1399
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001400 llvm::GlobalVariable *GV =
1401 new llvm::GlobalVariable(Init->getType(), false,
1402 llvm::GlobalValue::InternalLinkage,
1403 Init,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001404 Name,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001405 &CGM.getModule());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001406 GV->setSection(Section);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001407 UsedGlobals.push_back(GV);
1408 return llvm::ConstantExpr::getBitCast(GV,
1409 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001410}
1411
1412llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001413 std::string Name;
1414 GetNameForMethod(OMD, Name);
1415
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001416 const llvm::FunctionType *MethodTy =
1417 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarace33292008-08-16 03:19:19 +00001418 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001419 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001420 llvm::GlobalValue::InternalLinkage,
1421 Name,
1422 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001423 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001424
Daniel Dunbarace33292008-08-16 03:19:19 +00001425 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001426}
1427
1428llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001429 // Abuse this interface function as a place to finalize.
1430 FinishModule();
1431
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001432 return NULL;
1433}
1434
Daniel Dunbarf7103722008-09-24 03:38:44 +00001435llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1436 return ObjCTypes.GetPropertyFn;
1437}
1438
1439llvm::Function *CGObjCMac::GetPropertySetFunction() {
1440 return ObjCTypes.SetPropertyFn;
1441}
1442
Anders Carlsson58d16242008-08-31 04:05:03 +00001443llvm::Function *CGObjCMac::EnumerationMutationFunction()
1444{
1445 return ObjCTypes.EnumerationMutationFn;
1446}
1447
Daniel Dunbar83544842008-09-28 01:03:14 +00001448/*
1449
1450Objective-C setjmp-longjmp (sjlj) Exception Handling
1451--
1452
1453The basic framework for a @try-catch-finally is as follows:
1454{
1455 objc_exception_data d;
1456 id _rethrow = null;
1457
1458 objc_exception_try_enter(&d);
1459 if (!setjmp(d.jmp_buf)) {
1460 ... try body ...
1461 } else {
1462 // exception path
1463 id _caught = objc_exception_extract(&d);
1464
1465 // enter new try scope for handlers
1466 if (!setjmp(d.jmp_buf)) {
1467 ... match exception and execute catch blocks ...
1468
1469 // fell off end, rethrow.
1470 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001471 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001472 } else {
1473 // exception in catch block
1474 _rethrow = objc_exception_extract(&d);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001475 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001476 }
1477 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001478 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001479
1480finally:
1481 // match either the initial try_enter or the catch try_enter,
1482 // depending on the path followed.
1483 objc_exception_try_exit(&d);
1484finally_no_exit:
1485 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001486 ... dispatch to finally destination ...
1487
1488finally_rethrow:
1489 objc_exception_throw(_rethrow);
1490
1491finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00001492}
1493
1494This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001495uses _rethrow to determine if objc_exception_try_exit should be called
1496and if the object should be rethrown. This breaks in the face of
1497throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00001498
1499We specialize this framework for a few particular circumstances:
1500
1501 - If there are no catch blocks, then we avoid emitting the second
1502 exception handling context.
1503
1504 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1505 e)) we avoid emitting the code to rethrow an uncaught exception.
1506
1507 - FIXME: If there is no @finally block we can do a few more
1508 simplifications.
1509
1510Rethrows and Jumps-Through-Finally
1511--
1512
1513Support for implicit rethrows and jumping through the finally block is
1514handled by storing the current exception-handling context in
1515ObjCEHStack.
1516
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001517In order to implement proper @finally semantics, we support one basic
1518mechanism for jumping through the finally block to an arbitrary
1519destination. Constructs which generate exits from a @try or @catch
1520block use this mechanism to implement the proper semantics by chaining
1521jumps, as necessary.
1522
1523This mechanism works like the one used for indirect goto: we
1524arbitrarily assign an ID to each destination and store the ID for the
1525destination in a variable prior to entering the finally block. At the
1526end of the finally block we simply create a switch to the proper
1527destination.
1528
Daniel Dunbar83544842008-09-28 01:03:14 +00001529*/
1530
Anders Carlssonb01a2112008-09-09 10:04:29 +00001531void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001532 const ObjCAtTryStmt &S) {
1533 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00001534 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1535 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1536 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1537 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001538 llvm::Value *DestCode =
1539 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1540
1541 // Generate jump code. Done here so we can directly add things to
1542 // the switch instruction.
Daniel Dunbar72f96552008-11-11 02:29:29 +00001543 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001544 llvm::SwitchInst *FinallySwitch =
1545 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1546 FinallyEnd, 10, FinallyJump);
1547
1548 // Push an EH context entry, used for handling rethrows and jumps
1549 // through finally.
1550 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1551 FinallySwitch, DestCode);
1552 CGF.ObjCEHStack.push_back(&EHEntry);
1553
1554 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00001555 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1556 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001557 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1558 "_rethrow");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001559
1560 // Enter a new try block and call setjmp.
1561 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1562 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1563 "jmpbufarray");
1564 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1565 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1566 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001567
Daniel Dunbar72f96552008-11-11 02:29:29 +00001568 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1569 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001570 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001571 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001572
1573 // Emit the @try block.
1574 CGF.EmitBlock(TryBlock);
1575 CGF.EmitStmt(S.getTryBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001576 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001577
1578 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001579 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001580
1581 // Retrieve the exception object. We may emit multiple blocks but
1582 // nothing can cross this so the value is already in SSA form.
1583 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1584 ExceptionData,
1585 "caught");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001586 EHEntry.Exception = Caught;
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001587 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1588 // Enter a new exception try block (in case a @catch block throws
1589 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00001590 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001591
Anders Carlssonfca6c292008-09-09 17:59:25 +00001592 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1593 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001594 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001595
Daniel Dunbar72f96552008-11-11 02:29:29 +00001596 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1597 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001598 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001599
1600 CGF.EmitBlock(CatchBlock);
1601
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001602 // Handle catch list. As a special case we check if everything is
1603 // matched and avoid generating code for falling off the end if
1604 // so.
1605 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001606 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00001607 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001608
Anders Carlsson75d86732008-09-11 09:15:33 +00001609 const DeclStmt *CatchParam =
1610 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001611 const VarDecl *VD = 0;
1612 const PointerType *PT = 0;
1613
Anders Carlssonfca6c292008-09-09 17:59:25 +00001614 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001615 if (!CatchParam) {
1616 AllMatched = true;
1617 } else {
Ted Kremenekf41e9f72008-10-06 20:58:56 +00001618 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001619 PT = VD->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001620
Daniel Dunbard04c9352008-09-27 22:21:14 +00001621 // catch(id e) always matches.
1622 // FIXME: For the time being we also match id<X>; this should
1623 // be rejected by Sema instead.
1624 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1625 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001626 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001627 }
1628
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001629 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00001630 if (CatchParam) {
1631 CGF.EmitStmt(CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001632 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001633 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001634 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00001635
Anders Carlsson75d86732008-09-11 09:15:33 +00001636 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001637 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001638 break;
1639 }
1640
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001641 assert(PT && "Unexpected non-pointer type in @catch");
1642 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00001643 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001644 assert(ObjCType && "Catch parameter must have Objective-C type!");
1645
1646 // Check if the @catch block matches the exception object.
1647 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1648
Anders Carlssonfca6c292008-09-09 17:59:25 +00001649 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1650 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001651
Daniel Dunbar72f96552008-11-11 02:29:29 +00001652 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001653
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001654 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001655 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001656
1657 // Emit the @catch block.
1658 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar83544842008-09-28 01:03:14 +00001659 CGF.EmitStmt(CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001660 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00001661
1662 llvm::Value *Tmp =
1663 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1664 "tmp");
1665 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001666
1667 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001668 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001669
1670 CGF.EmitBlock(NextCatchBlock);
1671 }
1672
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001673 if (!AllMatched) {
1674 // None of the handlers caught the exception, so store it to be
1675 // rethrown at the end of the @finally block.
1676 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001677 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001678 }
1679
1680 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001681 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001682 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1683 ExceptionData),
1684 RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001685 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001686 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00001687 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001688 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001689 }
1690
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001691 // Pop the exception-handling stack entry. It is important to do
1692 // this now, because the code in the @finally block is not in this
1693 // context.
1694 CGF.ObjCEHStack.pop_back();
1695
Anders Carlssonfca6c292008-09-09 17:59:25 +00001696 // Emit the @finally block.
1697 CGF.EmitBlock(FinallyBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001698 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001699
1700 CGF.EmitBlock(FinallyNoExit);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001701 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1702 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1703
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001704 CGF.EmitBlock(FinallyJump);
1705
1706 CGF.EmitBlock(FinallyRethrow);
1707 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1708 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001709 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001710
1711 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001712}
1713
1714void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001715 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00001716 llvm::Value *ExceptionAsObject;
1717
1718 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1719 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1720 ExceptionAsObject =
1721 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1722 } else {
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001723 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00001724 "Unexpected rethrow outside @catch block.");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001725 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson05d7be72008-09-09 16:16:55 +00001726 }
1727
1728 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001729 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001730
1731 // Clear the insertion point to indicate we are in unreachable code.
1732 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001733}
1734
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001735void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1736 llvm::BasicBlock *Dst,
1737 bool ExecuteTryExit) {
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001738 if (!HaveInsertPoint())
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001739 return;
1740
1741 // Find the destination code for this block. We always use 0 for the
1742 // fallthrough block (default destination).
1743 llvm::SwitchInst *SI = E->FinallySwitch;
1744 llvm::ConstantInt *ID;
1745 if (Dst == SI->getDefaultDest()) {
1746 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1747 } else {
1748 ID = SI->findCaseDest(Dst);
1749 if (!ID) {
1750 // No code found, get a new unique one by just using the number
1751 // of switch successors.
1752 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1753 SI->addCase(ID, Dst);
1754 }
1755 }
1756
1757 // Set the destination code and branch.
1758 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001759 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001760}
1761
Chris Lattnerdd978702008-11-15 21:26:17 +00001762/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1763/// Effectively generating code for:
1764/// objc_sync_enter(expr);
1765/// @try stmt @finally { objc_sync_exit(expr); }
1766void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1767 const ObjCAtSynchronizedStmt &S) {
1768 // Create various blocks we refer to for handling @finally.
1769 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1770 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1771 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1772 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1773 llvm::Value *DestCode =
1774 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1775
1776 // Generate jump code. Done here so we can directly add things to
1777 // the switch instruction.
1778 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1779 llvm::SwitchInst *FinallySwitch =
1780 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1781 FinallyEnd, 10, FinallyJump);
1782
1783 // Push an EH context entry, used for handling rethrows and jumps
1784 // through finally.
1785 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1786 FinallySwitch, DestCode);
1787 CGF.ObjCEHStack.push_back(&EHEntry);
1788
1789 // Allocate memory for the exception data and rethrow pointer.
1790 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1791 "exceptiondata.ptr");
1792 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1793 "_rethrow");
1794 // Call objc_sync_enter(sync.expr)
1795 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1796 CGF.EmitScalarExpr(S.getSynchExpr()));
1797
1798 // Enter a new try block and call setjmp.
1799 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1800 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1801 "jmpbufarray");
1802 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1803 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1804 JmpBufPtr, "result");
1805
1806 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1807 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1808 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1809 TryHandler, TryBlock);
1810
1811 // Emit the @try block.
1812 CGF.EmitBlock(TryBlock);
1813 CGF.EmitStmt(S.getSynchBody());
1814 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1815
1816 // Emit the "exception in @try" block.
1817 CGF.EmitBlock(TryHandler);
1818
1819 // Retrieve the exception object. We may emit multiple blocks but
1820 // nothing can cross this so the value is already in SSA form.
1821 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1822 ExceptionData,
1823 "caught");
1824 EHEntry.Exception = Caught;
1825 CGF.Builder.CreateStore(Caught, RethrowPtr);
1826 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1827
1828 // Pop the exception-handling stack entry. It is important to do
1829 // this now, because the code in the @finally block is not in this
1830 // context.
1831 CGF.ObjCEHStack.pop_back();
1832
1833 // Emit the @finally block.
1834 CGF.EmitBlock(FinallyBlock);
1835 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1836
1837 CGF.EmitBlock(FinallyNoExit);
1838 // objc_sync_exit(expr); As finally's sole statement.
1839 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1840 CGF.EmitScalarExpr(S.getSynchExpr()));
1841
1842 CGF.EmitBlock(FinallyJump);
1843
1844 CGF.EmitBlock(FinallyRethrow);
1845 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1846 CGF.Builder.CreateLoad(RethrowPtr));
1847 CGF.Builder.CreateUnreachable();
1848
1849 CGF.EmitBlock(FinallyEnd);
1850}
1851
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001852/* *** Private Interface *** */
1853
1854/// EmitImageInfo - Emit the image info marker used to encode some module
1855/// level information.
1856///
1857/// See: <rdr://4810609&4810587&4810587>
1858/// struct IMAGE_INFO {
1859/// unsigned version;
1860/// unsigned flags;
1861/// };
1862enum ImageInfoFlags {
1863 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1864 eImageInfo_GarbageCollected = (1 << 1),
1865 eImageInfo_GCOnly = (1 << 2)
1866};
1867
1868void CGObjCMac::EmitImageInfo() {
1869 unsigned version = 0; // Version is unused?
1870 unsigned flags = 0;
1871
1872 // FIXME: Fix and continue?
1873 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1874 flags |= eImageInfo_GarbageCollected;
1875 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1876 flags |= eImageInfo_GCOnly;
1877
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001878 // Emitted as int[2];
1879 llvm::Constant *values[2] = {
1880 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1881 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1882 };
1883 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001884 llvm::GlobalVariable *GV =
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001885 new llvm::GlobalVariable(AT, true,
1886 llvm::GlobalValue::InternalLinkage,
1887 llvm::ConstantArray::get(AT, values, 2),
1888 "\01L_OBJC_IMAGE_INFO",
1889 &CGM.getModule());
1890
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001891 if (ObjCABI == 1) {
1892 GV->setSection("__OBJC, __image_info,regular");
1893 } else {
1894 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1895 }
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001896
1897 UsedGlobals.push_back(GV);
1898}
1899
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001900
1901// struct objc_module {
1902// unsigned long version;
1903// unsigned long size;
1904// const char *name;
1905// Symtab symtab;
1906// };
1907
1908// FIXME: Get from somewhere
1909static const int ModuleVersion = 7;
1910
1911void CGObjCMac::EmitModuleInfo() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001912 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1913
1914 std::vector<llvm::Constant*> Values(4);
1915 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1916 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00001917 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001918 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001919 Values[3] = EmitModuleSymbols();
1920
1921 llvm::GlobalVariable *GV =
1922 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1923 llvm::GlobalValue::InternalLinkage,
1924 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1925 Values),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001926 "\01L_OBJC_MODULES",
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001927 &CGM.getModule());
1928 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1929 UsedGlobals.push_back(GV);
1930}
1931
1932llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001933 unsigned NumClasses = DefinedClasses.size();
1934 unsigned NumCategories = DefinedCategories.size();
1935
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001936 // Return null if no symbols were defined.
1937 if (!NumClasses && !NumCategories)
1938 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1939
1940 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001941 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1942 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1943 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1944 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1945
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001946 // The runtime expects exactly the list of defined classes followed
1947 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001948 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001949 for (unsigned i=0; i<NumClasses; i++)
1950 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1951 ObjCTypes.Int8PtrTy);
1952 for (unsigned i=0; i<NumCategories; i++)
1953 Symbols[NumClasses + i] =
1954 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1955 ObjCTypes.Int8PtrTy);
1956
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001957 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001958 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001959 NumClasses + NumCategories),
1960 Symbols);
1961
1962 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1963
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001964 llvm::GlobalVariable *GV =
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001965 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001966 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001967 Init,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001968 "\01L_OBJC_SYMBOLS",
1969 &CGM.getModule());
1970 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1971 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001972 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
1973}
1974
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001975llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001976 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001977 LazySymbols.insert(ID->getIdentifier());
1978
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001979 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
1980
1981 if (!Entry) {
1982 llvm::Constant *Casted =
1983 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
1984 ObjCTypes.ClassPtrTy);
1985 Entry =
1986 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
1987 llvm::GlobalValue::InternalLinkage,
1988 Casted, "\01L_OBJC_CLASS_REFERENCES_",
1989 &CGM.getModule());
1990 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
1991 UsedGlobals.push_back(Entry);
1992 }
1993
1994 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001995}
1996
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001997llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001998 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
1999
2000 if (!Entry) {
2001 llvm::Constant *Casted =
2002 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2003 ObjCTypes.SelectorPtrTy);
2004 Entry =
2005 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2006 llvm::GlobalValue::InternalLinkage,
2007 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2008 &CGM.getModule());
2009 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2010 UsedGlobals.push_back(Entry);
2011 }
2012
2013 return Builder.CreateLoad(Entry, false, "tmp");
2014}
2015
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002016llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2017 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002018
2019 if (!Entry) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002020 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002021 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002022 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002023 llvm::GlobalValue::InternalLinkage,
2024 C, "\01L_OBJC_CLASS_NAME_",
2025 &CGM.getModule());
2026 Entry->setSection("__TEXT,__cstring,cstring_literals");
2027 UsedGlobals.push_back(Entry);
2028 }
2029
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002030 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002031}
2032
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002033llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2034 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2035
2036 if (!Entry) {
2037 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2038 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002039 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002040 llvm::GlobalValue::InternalLinkage,
2041 C, "\01L_OBJC_METH_VAR_NAME_",
2042 &CGM.getModule());
2043 Entry->setSection("__TEXT,__cstring,cstring_literals");
2044 UsedGlobals.push_back(Entry);
2045 }
2046
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002047 return getConstantGEP(Entry, 0, 0);
2048}
2049
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002050// FIXME: Merge into a single cstring creation function.
2051llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2052 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2053}
2054
2055// FIXME: Merge into a single cstring creation function.
2056llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2057 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2058}
2059
2060llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2061 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002062
2063 if (!Entry) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002064 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002065 Entry =
2066 new llvm::GlobalVariable(C->getType(), false,
2067 llvm::GlobalValue::InternalLinkage,
2068 C, "\01L_OBJC_METH_VAR_TYPE_",
2069 &CGM.getModule());
2070 Entry->setSection("__TEXT,__cstring,cstring_literals");
2071 UsedGlobals.push_back(Entry);
2072 }
2073
2074 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002075}
2076
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002077// FIXME: Merge into a single cstring creation function.
Daniel Dunbar12996f52008-08-26 21:51:14 +00002078llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002079 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00002080 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2081 TypeStr);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002082 return GetMethodVarType(TypeStr);
2083}
2084
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002085// FIXME: Merge into a single cstring creation function.
2086llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2087 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2088
2089 if (!Entry) {
2090 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2091 Entry =
2092 new llvm::GlobalVariable(C->getType(), false,
2093 llvm::GlobalValue::InternalLinkage,
2094 C, "\01L_OBJC_PROP_NAME_ATTR_",
2095 &CGM.getModule());
2096 Entry->setSection("__TEXT,__cstring,cstring_literals");
2097 UsedGlobals.push_back(Entry);
2098 }
2099
2100 return getConstantGEP(Entry, 0, 0);
2101}
2102
2103// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002104// FIXME: This Decl should be more precise.
2105llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2106 const Decl *Container) {
2107 std::string TypeStr;
2108 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002109 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2110}
2111
Daniel Dunbarace33292008-08-16 03:19:19 +00002112void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2113 std::string &NameOut) {
2114 // FIXME: Find the mangling GCC uses.
2115 std::stringstream s;
2116 s << (D->isInstance() ? "-" : "+");
2117 s << "[";
2118 s << D->getClassInterface()->getName();
2119 s << " ";
2120 s << D->getSelector().getName();
2121 s << "]";
2122 NameOut = s.str();
2123}
2124
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002125void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002126 EmitModuleInfo();
2127
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002128 // Emit the dummy bodies for any protocols which were referenced but
2129 // never defined.
2130 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2131 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2132 if (i->second->hasInitializer())
2133 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002134
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002135 std::vector<llvm::Constant*> Values(5);
2136 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2137 Values[1] = GetClassName(i->first);
2138 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2139 Values[3] = Values[4] =
2140 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2141 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2142 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2143 Values));
2144 }
2145
2146 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002147 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002148 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002149 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002150 }
2151
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002152 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002153 llvm::GlobalValue *GV =
2154 new llvm::GlobalVariable(AT, false,
2155 llvm::GlobalValue::AppendingLinkage,
2156 llvm::ConstantArray::get(AT, Used),
2157 "llvm.used",
2158 &CGM.getModule());
2159
2160 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002161
2162 // Add assembler directives to add lazy undefined symbol references
2163 // for classes which are referenced but not defined. This is
2164 // important for correct linker interaction.
2165
2166 // FIXME: Uh, this isn't particularly portable.
2167 std::stringstream s;
2168 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2169 e = LazySymbols.end(); i != e; ++i) {
2170 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2171 }
2172 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2173 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002174 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002175 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2176 }
2177 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002178}
2179
2180/* *** */
2181
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002182ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbardbdb9512008-08-23 18:37:06 +00002183 : CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002184{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002185 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2186 ASTContext &Ctx = CGM.getContext();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002187
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002188 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002189 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002190 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002191 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2192
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002193 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2194 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002195
2196 // FIXME: It would be nice to unify this with the opaque type, so
2197 // that the IR comes out a bit cleaner.
2198 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2199 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002200
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002201 MethodDescriptionTy =
2202 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002203 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002204 NULL);
2205 CGM.getModule().addTypeName("struct._objc_method_description",
2206 MethodDescriptionTy);
2207
2208 MethodDescriptionListTy =
2209 llvm::StructType::get(IntTy,
2210 llvm::ArrayType::get(MethodDescriptionTy, 0),
2211 NULL);
2212 CGM.getModule().addTypeName("struct._objc_method_description_list",
2213 MethodDescriptionListTy);
2214 MethodDescriptionListPtrTy =
2215 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2216
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002217 PropertyTy = llvm::StructType::get(Int8PtrTy,
2218 Int8PtrTy,
2219 NULL);
2220 CGM.getModule().addTypeName("struct._objc_property",
2221 PropertyTy);
2222
2223 PropertyListTy = llvm::StructType::get(IntTy,
2224 IntTy,
2225 llvm::ArrayType::get(PropertyTy, 0),
2226 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002227 CGM.getModule().addTypeName("struct._objc_property_list",
2228 PropertyListTy);
2229 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2230
2231 // Protocol description structures
2232
2233 ProtocolExtensionTy =
2234 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2235 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2236 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2237 PropertyListPtrTy,
2238 NULL);
2239 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2240 ProtocolExtensionTy);
2241 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2242
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002243 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002244
2245 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2246 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2247
2248 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2249 LongTy,
2250 llvm::ArrayType::get(ProtocolTyHolder, 0),
2251 NULL);
2252 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2253
2254 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002255 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002256 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2257 MethodDescriptionListPtrTy,
2258 MethodDescriptionListPtrTy,
2259 NULL);
2260 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2261
2262 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2263 CGM.getModule().addTypeName("struct._objc_protocol_list",
2264 ProtocolListTy);
2265 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2266
2267 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2268 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2269 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002270
2271 // Class description structures
2272
2273 IvarTy = llvm::StructType::get(Int8PtrTy,
2274 Int8PtrTy,
2275 IntTy,
2276 NULL);
2277 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2278
2279 IvarListTy = llvm::OpaqueType::get();
2280 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2281 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2282
2283 MethodTy = llvm::StructType::get(SelectorPtrTy,
2284 Int8PtrTy,
2285 Int8PtrTy,
2286 NULL);
2287 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2288
2289 MethodListTy = llvm::OpaqueType::get();
2290 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2291 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2292
2293 CacheTy = llvm::OpaqueType::get();
2294 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2295 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2296
2297 ClassExtensionTy =
2298 llvm::StructType::get(IntTy,
2299 Int8PtrTy,
2300 PropertyListPtrTy,
2301 NULL);
2302 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2303 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2304
2305 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2306
2307 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2308 llvm::PointerType::getUnqual(ClassTyHolder),
2309 Int8PtrTy,
2310 LongTy,
2311 LongTy,
2312 LongTy,
2313 IvarListPtrTy,
2314 MethodListPtrTy,
2315 CachePtrTy,
2316 ProtocolListPtrTy,
2317 Int8PtrTy,
2318 ClassExtensionPtrTy,
2319 NULL);
2320 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2321
2322 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2323 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2324 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2325
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002326 CategoryTy = llvm::StructType::get(Int8PtrTy,
2327 Int8PtrTy,
2328 MethodListPtrTy,
2329 MethodListPtrTy,
2330 ProtocolListPtrTy,
2331 IntTy,
2332 PropertyListPtrTy,
2333 NULL);
2334 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2335
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002336 // I'm not sure I like this. The implicit coordination is a bit
2337 // gross. We should solve this in a reasonable fashion because this
2338 // is a pretty common task (match some runtime data structure with
2339 // an LLVM data structure).
2340
2341 // FIXME: This is leaked.
2342 // FIXME: Merge with rewriter code?
2343 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2344 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002345 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002346 FieldDecl *FieldDecls[2];
2347 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2348 Ctx.getObjCIdType());
2349 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2350 Ctx.getObjCClassType());
Ted Kremenek46a837c2008-09-05 17:16:31 +00002351 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002352
2353 SuperCTy = Ctx.getTagDeclType(RD);
2354 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2355
2356 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002357 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbar15245e52008-08-23 04:28:29 +00002358
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002359 // Global metadata structures
2360
2361 SymtabTy = llvm::StructType::get(LongTy,
2362 SelectorPtrTy,
2363 ShortTy,
2364 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002365 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002366 NULL);
2367 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2368 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2369
2370 ModuleTy =
2371 llvm::StructType::get(LongTy,
2372 LongTy,
2373 Int8PtrTy,
2374 SymtabPtrTy,
2375 NULL);
2376 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002377
Daniel Dunbarf7103722008-09-24 03:38:44 +00002378 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002379
2380 std::vector<const llvm::Type*> Params;
2381 Params.push_back(ObjectPtrTy);
2382 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002383 MessageSendFn =
2384 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2385 Params,
2386 true),
2387 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002388
2389 Params.clear();
2390 Params.push_back(Int8PtrTy);
2391 Params.push_back(ObjectPtrTy);
2392 Params.push_back(SelectorPtrTy);
2393 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002394 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2395 Params,
2396 true),
2397 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002398
2399 Params.clear();
2400 Params.push_back(ObjectPtrTy);
2401 Params.push_back(SelectorPtrTy);
2402 // FIXME: This should be long double on x86_64?
2403 MessageSendFpretFn =
2404 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2405 Params,
2406 true),
2407 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002408
2409 Params.clear();
2410 Params.push_back(SuperPtrTy);
2411 Params.push_back(SelectorPtrTy);
2412 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002413 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2414 Params,
2415 true),
2416 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002417
2418 Params.clear();
2419 Params.push_back(Int8PtrTy);
2420 Params.push_back(SuperPtrTy);
2421 Params.push_back(SelectorPtrTy);
2422 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002423 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2424 Params,
2425 true),
2426 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002427
2428 // There is no objc_msgSendSuper_fpret? How can that work?
2429 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00002430
Daniel Dunbarf7103722008-09-24 03:38:44 +00002431 // Property manipulation functions.
2432
2433 Params.clear();
2434 Params.push_back(ObjectPtrTy);
2435 Params.push_back(SelectorPtrTy);
2436 Params.push_back(LongTy);
2437 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2438 GetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002439 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2440 Params,
2441 false),
2442 "objc_getProperty");
2443
Daniel Dunbarf7103722008-09-24 03:38:44 +00002444 Params.clear();
2445 Params.push_back(ObjectPtrTy);
2446 Params.push_back(SelectorPtrTy);
2447 Params.push_back(LongTy);
Daniel Dunbarf7f6c7b2008-09-24 06:32:09 +00002448 Params.push_back(ObjectPtrTy);
Daniel Dunbarf7103722008-09-24 03:38:44 +00002449 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2450 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2451 SetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002452 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2453 Params,
2454 false),
2455 "objc_setProperty");
Daniel Dunbarf7103722008-09-24 03:38:44 +00002456
Anders Carlsson58d16242008-08-31 04:05:03 +00002457 // Enumeration mutation.
Daniel Dunbarf7103722008-09-24 03:38:44 +00002458
Anders Carlsson58d16242008-08-31 04:05:03 +00002459 Params.clear();
2460 Params.push_back(ObjectPtrTy);
2461 EnumerationMutationFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002462 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2463 Params,
2464 false),
2465 "objc_enumerationMutation");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002466
2467 // FIXME: This is the size of the setjmp buffer and should be
2468 // target specific. 18 is what's used on 32-bit X86.
2469 uint64_t SetJmpBufferSize = 18;
2470
2471 // Exceptions
2472 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00002473 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002474
2475 ExceptionDataTy =
2476 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2477 SetJmpBufferSize),
2478 StackPtrTy, NULL);
2479 CGM.getModule().addTypeName("struct._objc_exception_data",
2480 ExceptionDataTy);
2481
2482 Params.clear();
2483 Params.push_back(ObjectPtrTy);
2484 ExceptionThrowFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002485 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2486 Params,
2487 false),
2488 "objc_exception_throw");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002489
2490 Params.clear();
2491 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2492 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002493 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2494 Params,
2495 false),
2496 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002497 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002498 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2499 Params,
2500 false),
2501 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002502 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002503 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2504 Params,
2505 false),
2506 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002507
2508 Params.clear();
2509 Params.push_back(ClassPtrTy);
2510 Params.push_back(ObjectPtrTy);
2511 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002512 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2513 Params,
2514 false),
2515 "objc_exception_match");
Chris Lattnerdd978702008-11-15 21:26:17 +00002516
2517 // synchronized APIs
2518 // void objc_sync_enter (id)
2519 Params.clear();
2520 Params.push_back(ObjectPtrTy);
2521 SyncEnterFn =
2522 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2523 Params,
2524 false),
2525 "objc_sync_enter");
2526 // void objc_sync_exit (id)
2527 SyncExitFn =
2528 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2529 Params,
2530 false),
2531 "objc_sync_exit");
2532
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002533
2534 Params.clear();
2535 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2536 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002537 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2538 Params,
2539 false),
2540 "_setjmp");
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002541}
2542
2543ObjCTypesHelper::~ObjCTypesHelper() {
2544}
2545
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002546/* *** */
2547
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002548CodeGen::CGObjCRuntime *
2549CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002550 return new CGObjCMac(CGM);
2551}