blob: 682515180dd91dce639d465f2110e7203789b0db [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000024#include "llvm/Support/IRBuilder.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
Daniel Dunbarbbce49b2008-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 Dunbar5669e572008-10-17 03:24:53 +000044 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46 *MessageSendSuperFpretFn;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000047
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000048public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000049 const llvm::Type *ShortTy, *IntTy, *LongTy;
50 const llvm::Type *Int8PtrTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000051
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000052 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53 const llvm::Type *ObjectPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000054 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000055 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000056 /// ProtocolPtrTy - LLVM type for external protocol handles
57 /// (typeof(Protocol))
58 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000059
Daniel Dunbar19cd87e2008-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 Dunbare8b470d2008-08-23 04:28:29 +000065 /// SuperTy - LLVM type for struct objc_super.
66 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000067 /// SuperPtrTy - LLVM type for struct objc_super *.
68 const llvm::Type *SuperPtrTy;
Daniel Dunbare8b470d2008-08-23 04:28:29 +000069
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000070 /// SymtabTy - LLVM type for struct objc_symtab.
71 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000072 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
73 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000074 /// ModuleTy - LLVM type for struct objc_module.
75 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000076
Daniel Dunbar6efc0c52008-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 Dunbarc8ef5512008-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 Dunbar6efc0c52008-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 Dunbar86e253a2008-08-22 20:34:54 +0000108 /// CategoryTy - LLVM type for struct objc_category.
109 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000134
Daniel Dunbar49f66022008-09-24 03:38:44 +0000135 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000136 llvm::Function *EnumerationMutationFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000137
138 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
139 const llvm::Type *ExceptionDataTy;
140
141 /// ExceptionThrowFn - LLVM objc_exception_throw function.
142 llvm::Function *ExceptionThrowFn;
143
144 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
145 llvm::Function *ExceptionTryEnterFn;
146
147 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
148 llvm::Function *ExceptionTryExitFn;
149
150 /// ExceptionExtractFn - LLVM objc_exception_extract function.
151 llvm::Function *ExceptionExtractFn;
152
153 /// ExceptionMatchFn - LLVM objc_exception_match function.
154 llvm::Function *ExceptionMatchFn;
155
156 /// SetJmpFn - LLVM _setjmp function.
157 llvm::Function *SetJmpFn;
158
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000159public:
160 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
161 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000162
163
164 llvm::Function *getSendFn(bool IsSuper) {
165 return IsSuper ? MessageSendSuperFn : MessageSendFn;
166 }
167
168 llvm::Function *getSendStretFn(bool IsSuper) {
169 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
170 }
171
172 llvm::Function *getSendFpretFn(bool IsSuper) {
173 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
174 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000175};
176
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000177class CGObjCMac : public CodeGen::CGObjCRuntime {
178private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000179 CodeGen::CodeGenModule &CGM;
180 ObjCTypesHelper ObjCTypes;
181 /// ObjCABI - FIXME: Not sure yet.
182 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000183
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000184 /// LazySymbols - Symbols to generate a lazy reference for. See
185 /// DefinedSymbols and FinishModule().
186 std::set<IdentifierInfo*> LazySymbols;
187
188 /// DefinedSymbols - External symbols which are defined by this
189 /// module. The symbols in this list and LazySymbols are used to add
190 /// special linker symbols which ensure that Objective-C modules are
191 /// linked properly.
192 std::set<IdentifierInfo*> DefinedSymbols;
193
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000194 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000195 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000196
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000197 /// MethodVarNames - uniqued method variable names.
198 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
199
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000200 /// MethodVarTypes - uniqued method type signatures. We have to use
201 /// a StringMap here because have no other unique reference.
202 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
203
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000204 /// MethodDefinitions - map of methods which have been defined in
205 /// this translation unit.
206 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
207
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000208 /// PropertyNames - uniqued method variable names.
209 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
210
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000211 /// ClassReferences - uniqued class references.
212 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
213
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000214 /// SelectorReferences - uniqued selector references.
215 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
216
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000217 /// Protocols - Protocols for which an objc_protocol structure has
218 /// been emitted. Forward declarations are handled by creating an
219 /// empty structure whose initializer is filled in when/if defined.
220 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
221
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000222 /// DefinedClasses - List of defined classes.
223 std::vector<llvm::GlobalValue*> DefinedClasses;
224
225 /// DefinedCategories - List of defined categories.
226 std::vector<llvm::GlobalValue*> DefinedCategories;
227
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000228 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000229 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000230 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000231
232 /// EmitImageInfo - Emit the image info marker used to encode some module
233 /// level information.
234 void EmitImageInfo();
235
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000236 /// EmitModuleInfo - Another marker encoding module level
237 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000238 void EmitModuleInfo();
239
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000240 /// EmitModuleSymols - Emit module symbols, the list of defined
241 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000242 llvm::Constant *EmitModuleSymbols();
243
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000244 /// FinishModule - Write out global data structures at the end of
245 /// processing a translation unit.
246 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000247
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000248 /// EmitClassExtension - Generate the class extension structure used
249 /// to store the weak ivar layout and properties. The return value
250 /// has type ClassExtensionPtrTy.
251 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
252
253 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
254 /// for the given class.
255 llvm::Value *EmitClassRef(llvm::IRBuilder<> &Builder,
256 const ObjCInterfaceDecl *ID);
257
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000258 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000259 QualType ResultType,
260 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000261 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000262 QualType Arg0Ty,
263 bool IsSuper,
264 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000265
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000266 /// EmitIvarList - Emit the ivar list for the given
267 /// implementation. If ForClass is true the list of class ivars
268 /// (i.e. metaclass ivars) is emitted, otherwise the list of
269 /// interface ivars will be emitted. The return value has type
270 /// IvarListPtrTy.
271 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
272 bool ForClass,
273 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000274
275 /// EmitMetaClass - Emit a forward reference to the class structure
276 /// for the metaclass of the given interface. The return value has
277 /// type ClassPtrTy.
278 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
279
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000280 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000281 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000282 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
283 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000284 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000285 const ConstantVector &Methods);
286
287 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
288
289 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000290
291 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000292 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000293 llvm::Constant *EmitMethodList(const std::string &Name,
294 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000295 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000296
297 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000298 /// method declarations.
299 /// - TypeName: The name for the type containing the methods.
300 /// - IsProtocol: True iff these methods are for a protocol.
301 /// - ClassMethds: True iff these are class methods.
302 /// - Required: When true, only "required" methods are
303 /// listed. Similarly, when false only "optional" methods are
304 /// listed. For classes this should always be true.
305 /// - begin, end: The method list to output.
306 ///
307 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000308 llvm::Constant *EmitMethodDescList(const std::string &Name,
309 const char *Section,
310 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000311
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000312 /// EmitPropertyList - Emit the given property list. The return
313 /// value has type PropertyListPtrTy.
314 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000315 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000316 ObjCPropertyDecl * const *begin,
317 ObjCPropertyDecl * const *end);
318
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000319 /// EmitProtocolExtension - Generate the protocol extension
320 /// structure used to store optional instance and class methods, and
321 /// protocol properties. The return value has type
322 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000323 llvm::Constant *
324 EmitProtocolExtension(const ObjCProtocolDecl *PD,
325 const ConstantVector &OptInstanceMethods,
326 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000327
328 /// EmitProtocolList - Generate the list of referenced
329 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000330 llvm::Constant *EmitProtocolList(const std::string &Name,
331 ObjCProtocolDecl::protocol_iterator begin,
332 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000333
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000334 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
335 /// for the given selector.
336 llvm::Value *EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel);
337
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000338 /// GetProtocolRef - Return a reference to the internal protocol
339 /// description, creating an empty one if it has not been
340 /// defined. The return value has type pointer-to ProtocolTy.
341 llvm::GlobalVariable *GetProtocolRef(const ObjCProtocolDecl *PD);
342
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000343 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000344 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000345 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000346
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000347 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000348 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000349 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000350 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000351 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000352
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000353 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000354 /// selector's name. The return value has type char *.
355
356 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000357 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000358 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000359
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000360 /// GetPropertyName - Return a unique constant for the given
361 /// name. The return value has type char *.
362 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
363
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000364 // FIXME: This can be dropped once string functions are unified.
365 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
366 const Decl *Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000367
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000368 /// GetNameForMethod - Return a name for the given method.
369 /// \param[out] NameOut - The return value.
370 void GetNameForMethod(const ObjCMethodDecl *OMD,
371 std::string &NameOut);
372
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000373public:
374 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000375 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000376
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000377 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000378 QualType ResultType,
379 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000380 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000381 bool IsClassMessage,
382 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000383
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000384 virtual CodeGen::RValue
385 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000386 QualType ResultType,
387 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000388 const ObjCInterfaceDecl *Class,
389 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000390 bool IsClassMessage,
391 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000392
393 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000394 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000395
396 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
397
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000398 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000399
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000400 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000401
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000402 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000403
404 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000405 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000406
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000407 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000408
409 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000410 virtual llvm::Function *GetPropertyGetFunction();
411 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000412 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000413
414 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
415 const ObjCAtTryStmt &S);
416 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
417 const ObjCAtThrowStmt &S);
418
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000419};
420} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000421
422/* *** Helper Functions *** */
423
424/// getConstantGEP() - Help routine to construct simple GEPs.
425static llvm::Constant *getConstantGEP(llvm::Constant *C,
426 unsigned idx0,
427 unsigned idx1) {
428 llvm::Value *Idxs[] = {
429 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
430 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
431 };
432 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
433}
434
435/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000436
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000437CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
438 : CGM(cgm),
439 ObjCTypes(cgm),
440 ObjCABI(1)
441{
442 // FIXME: How does this get set in GCC? And what does it even mean?
443 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
444 ObjCABI = 2;
445
446 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000447}
448
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000449/// GetClass - Return a reference to the class for the given interface
450/// decl.
451llvm::Value *CGObjCMac::GetClass(llvm::IRBuilder<> &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000452 const ObjCInterfaceDecl *ID) {
453 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000454}
455
456/// GetSelector - Return the pointer to the unique'd string for this selector.
457llvm::Value *CGObjCMac::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000458 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000459}
460
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000461/// Generate a constant CFString object.
462/*
463 struct __builtin_CFString {
464 const int *isa; // point to __CFConstantStringClassReference
465 int flags;
466 const char *str;
467 long length;
468 };
469*/
470
471llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000472 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000473}
474
475/// Generates a message send where the super is the receiver. This is
476/// a message send to self with special delivery semantics indicating
477/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000478CodeGen::RValue
479CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000480 QualType ResultType,
481 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000482 const ObjCInterfaceDecl *Class,
483 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000484 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000485 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000486 // Create and init a super structure; this is a (receiver, class)
487 // pair we will pass to objc_msgSendSuper.
488 llvm::Value *ObjCSuper =
489 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
490 llvm::Value *ReceiverAsObject =
491 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
492 CGF.Builder.CreateStore(ReceiverAsObject,
493 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000494
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000495 // If this is a class message the metaclass is passed as the target.
496 llvm::Value *Target;
497 if (IsClassMessage) {
498 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
499 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
500 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
501 Target = Super;
502 } else {
503 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
504 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000505 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
506 // and ObjCTypes types.
507 const llvm::Type *ClassTy =
508 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
509 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000510 CGF.Builder.CreateStore(Target,
511 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
512
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000513 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000514 ObjCSuper, ObjCTypes.SuperPtrCTy,
515 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000516}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000517
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000518/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000519CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000520 QualType ResultType,
521 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000522 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000523 bool IsClassMessage,
524 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000525 llvm::Value *Arg0 =
526 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000527 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000528 Arg0, CGF.getContext().getObjCIdType(),
529 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000530}
531
532CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000533 QualType ResultType,
534 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000535 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000536 QualType Arg0Ty,
537 bool IsSuper,
538 const CallArgList &CallArgs) {
539 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000540 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
541 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
542 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000543 CGF.getContext().getObjCSelType()));
544 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000545
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000546 const llvm::FunctionType *FTy =
547 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
548 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000549
550 llvm::Constant *Fn;
551 if (CGM.ReturnTypeUsesSret(ResultType)) {
552 Fn = ObjCTypes.getSendStretFn(IsSuper);
553 } else if (ResultType->isFloatingType()) {
554 // FIXME: Sadly, this is wrong. This actually depends on the
555 // architecture. This happens to be right for x86-32 though.
556 Fn = ObjCTypes.getSendFpretFn(IsSuper);
557 } else {
558 Fn = ObjCTypes.getSendFn(IsSuper);
559 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000560 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000561 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000562}
563
564llvm::Value *CGObjCMac::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000565 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000566 // FIXME: I don't understand why gcc generates this, or where it is
567 // resolved. Investigate. Its also wasteful to look this up over and
568 // over.
569 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
570
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000571 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
572 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000573}
574
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000575/*
576 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
577 struct _objc_protocol {
578 struct _objc_protocol_extension *isa;
579 char *protocol_name;
580 struct _objc_protocol_list *protocol_list;
581 struct _objc__method_prototype_list *instance_methods;
582 struct _objc__method_prototype_list *class_methods
583 };
584
585 See EmitProtocolExtension().
586*/
587void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000588 // FIXME: I don't understand why gcc generates this, or where it is
589 // resolved. Investigate. Its also wasteful to look this up over and
590 // over.
591 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
592
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000593 const char *ProtocolName = PD->getName();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000594
595 // Construct method lists.
596 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
597 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
598 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
599 e = PD->instmeth_end(); i != e; ++i) {
600 ObjCMethodDecl *MD = *i;
601 llvm::Constant *C = GetMethodDescriptionConstant(MD);
602 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
603 OptInstanceMethods.push_back(C);
604 } else {
605 InstanceMethods.push_back(C);
606 }
607 }
608
609 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
610 e = PD->classmeth_end(); i != e; ++i) {
611 ObjCMethodDecl *MD = *i;
612 llvm::Constant *C = GetMethodDescriptionConstant(MD);
613 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
614 OptClassMethods.push_back(C);
615 } else {
616 ClassMethods.push_back(C);
617 }
618 }
619
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000620 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000621 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000622 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000623 Values[2] =
624 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
625 PD->protocol_begin(),
626 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000627 Values[3] =
628 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
629 + PD->getName(),
630 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
631 InstanceMethods);
632 Values[4] =
633 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
634 + PD->getName(),
635 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
636 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000637 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
638 Values);
639
640 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
641 if (Entry) {
642 // Already created, just update the initializer
643 Entry->setInitializer(Init);
644 } else {
645 Entry =
646 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
647 llvm::GlobalValue::InternalLinkage,
648 Init,
649 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
650 &CGM.getModule());
651 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
652 UsedGlobals.push_back(Entry);
653 // FIXME: Is this necessary? Why only for protocol?
654 Entry->setAlignment(4);
655 }
656}
657
658llvm::GlobalVariable *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
659 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
660
661 if (!Entry) {
662 std::vector<llvm::Constant*> Values(5);
663 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
664 Values[1] = GetClassName(PD->getIdentifier());
665 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
666 Values[3] = Values[4] =
667 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
668 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
669 Values);
670
671 Entry =
672 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
673 llvm::GlobalValue::InternalLinkage,
674 Init,
675 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
676 &CGM.getModule());
677 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
678 UsedGlobals.push_back(Entry);
679 // FIXME: Is this necessary? Why only for protocol?
680 Entry->setAlignment(4);
681 }
682
683 return Entry;
684}
685
686/*
687 struct _objc_protocol_extension {
688 uint32_t size;
689 struct objc_method_description_list *optional_instance_methods;
690 struct objc_method_description_list *optional_class_methods;
691 struct objc_property_list *instance_properties;
692 };
693*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000694llvm::Constant *
695CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
696 const ConstantVector &OptInstanceMethods,
697 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000698 uint64_t Size =
699 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
700 std::vector<llvm::Constant*> Values(4);
701 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000702 Values[1] =
703 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
704 + PD->getName(),
705 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
706 OptInstanceMethods);
707 Values[2] =
708 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
709 + PD->getName(),
710 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
711 OptClassMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000712 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
713 PD->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000714 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000715 PD->classprop_begin(),
716 PD->classprop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000717
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000718 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000719 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
720 Values[3]->isNullValue())
721 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
722
723 llvm::Constant *Init =
724 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
725 llvm::GlobalVariable *GV =
726 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
727 llvm::GlobalValue::InternalLinkage,
728 Init,
729 (std::string("\01L_OBJC_PROTOCOLEXT_") +
730 PD->getName()),
731 &CGM.getModule());
732 // No special section, but goes in llvm.used
733 UsedGlobals.push_back(GV);
734
735 return GV;
736}
737
738/*
739 struct objc_protocol_list {
740 struct objc_protocol_list *next;
741 long count;
742 Protocol *list[];
743 };
744*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000745llvm::Constant *
746CGObjCMac::EmitProtocolList(const std::string &Name,
747 ObjCProtocolDecl::protocol_iterator begin,
748 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000749 std::vector<llvm::Constant*> ProtocolRefs;
750
Daniel Dunbardbc933702008-08-21 21:57:41 +0000751 for (; begin != end; ++begin)
752 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000753
754 // Just return null for empty protocol lists
755 if (ProtocolRefs.empty())
756 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
757
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000758 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000759 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
760
761 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000762 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000763 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
764 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
765 Values[2] =
766 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
767 ProtocolRefs.size()),
768 ProtocolRefs);
769
770 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
771 llvm::GlobalVariable *GV =
772 new llvm::GlobalVariable(Init->getType(), false,
773 llvm::GlobalValue::InternalLinkage,
774 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000775 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000776 &CGM.getModule());
777 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
778 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
779}
780
781/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000782 struct _objc_property {
783 const char * const name;
784 const char * const attributes;
785 };
786
787 struct _objc_property_list {
788 uint32_t entsize; // sizeof (struct _objc_property)
789 uint32_t prop_count;
790 struct _objc_property[prop_count];
791 };
792*/
793llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000794 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000795 ObjCPropertyDecl * const *begin,
796 ObjCPropertyDecl * const *end) {
797 std::vector<llvm::Constant*> Properties, Prop(2);
798 for (; begin != end; ++begin) {
799 const ObjCPropertyDecl *PD = *begin;
800 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000801 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000802 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
803 Prop));
804 }
805
806 // Return null for empty list.
807 if (Properties.empty())
808 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
809
810 unsigned PropertySize =
811 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
812 std::vector<llvm::Constant*> Values(3);
813 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
814 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
815 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
816 Properties.size());
817 Values[2] = llvm::ConstantArray::get(AT, Properties);
818 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
819
820 llvm::GlobalVariable *GV =
821 new llvm::GlobalVariable(Init->getType(), false,
822 llvm::GlobalValue::InternalLinkage,
823 Init,
824 Name,
825 &CGM.getModule());
826 // No special section on property lists?
827 UsedGlobals.push_back(GV);
828 return llvm::ConstantExpr::getBitCast(GV,
829 ObjCTypes.PropertyListPtrTy);
830
831}
832
833/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000834 struct objc_method_description_list {
835 int count;
836 struct objc_method_description list[];
837 };
838*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000839llvm::Constant *
840CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
841 std::vector<llvm::Constant*> Desc(2);
842 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
843 ObjCTypes.SelectorPtrTy);
844 Desc[1] = GetMethodVarType(MD);
845 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
846 Desc);
847}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000848
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000849llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
850 const char *Section,
851 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000852 // Return null for empty list.
853 if (Methods.empty())
854 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
855
856 std::vector<llvm::Constant*> Values(2);
857 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
858 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
859 Methods.size());
860 Values[1] = llvm::ConstantArray::get(AT, Methods);
861 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
862
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000863 llvm::GlobalVariable *GV =
864 new llvm::GlobalVariable(Init->getType(), false,
865 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000866 Init, Name, &CGM.getModule());
867 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000868 UsedGlobals.push_back(GV);
869 return llvm::ConstantExpr::getBitCast(GV,
870 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000871}
872
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000873/*
874 struct _objc_category {
875 char *category_name;
876 char *class_name;
877 struct _objc_method_list *instance_methods;
878 struct _objc_method_list *class_methods;
879 struct _objc_protocol_list *protocols;
880 uint32_t size; // <rdar://4585769>
881 struct _objc_property_list *instance_properties;
882 };
883 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000884void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000885 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
886
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000887 // FIXME: This is poor design, the OCD should have a pointer to the
888 // category decl. Additionally, note that Category can be null for
889 // the @implementation w/o an @interface case. Sema should just
890 // create one for us as it does for @implementation so everyone else
891 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000892 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000893 const ObjCCategoryDecl *Category =
894 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000895 std::string ExtName(std::string(Interface->getName()) +
896 "_" +
897 OCD->getName());
898
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000899 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
900 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
901 e = OCD->instmeth_end(); i != e; ++i) {
902 // Instance methods should always be defined.
903 InstanceMethods.push_back(GetMethodConstant(*i));
904 }
905 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
906 e = OCD->classmeth_end(); i != e; ++i) {
907 // Class methods should always be defined.
908 ClassMethods.push_back(GetMethodConstant(*i));
909 }
910
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000911 std::vector<llvm::Constant*> Values(7);
912 Values[0] = GetClassName(OCD->getIdentifier());
913 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000914 Values[2] =
915 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
916 ExtName,
917 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000918 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000919 Values[3] =
920 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
921 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000922 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000923 if (Category) {
924 Values[4] =
925 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
926 Category->protocol_begin(),
927 Category->protocol_end());
928 } else {
929 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
930 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000931 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000932
933 // If there is no category @interface then there can be no properties.
934 if (Category) {
935 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000936 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000937 Category->classprop_begin(),
938 Category->classprop_end());
939 } else {
940 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
941 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000942
943 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
944 Values);
945
946 llvm::GlobalVariable *GV =
947 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
948 llvm::GlobalValue::InternalLinkage,
949 Init,
950 std::string("\01L_OBJC_CATEGORY_")+ExtName,
951 &CGM.getModule());
952 GV->setSection("__OBJC,__category,regular,no_dead_strip");
953 UsedGlobals.push_back(GV);
954 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000955}
956
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000957// FIXME: Get from somewhere?
958enum ClassFlags {
959 eClassFlags_Factory = 0x00001,
960 eClassFlags_Meta = 0x00002,
961 // <rdr://5142207>
962 eClassFlags_HasCXXStructors = 0x02000,
963 eClassFlags_Hidden = 0x20000,
964 eClassFlags_ABI2_Hidden = 0x00010,
965 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
966};
967
968// <rdr://5142207&4705298&4843145>
969static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
970 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
971 // FIXME: Support -fvisibility
972 switch (attr->getVisibility()) {
973 default:
974 assert(0 && "Unknown visibility");
975 return false;
976 case VisibilityAttr::DefaultVisibility:
977 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
978 return false;
979 case VisibilityAttr::HiddenVisibility:
980 return true;
981 }
982 } else {
983 return false; // FIXME: Support -fvisibility
984 }
985}
986
987/*
988 struct _objc_class {
989 Class isa;
990 Class super_class;
991 const char *name;
992 long version;
993 long info;
994 long instance_size;
995 struct _objc_ivar_list *ivars;
996 struct _objc_method_list *methods;
997 struct _objc_cache *cache;
998 struct _objc_protocol_list *protocols;
999 // Objective-C 1.0 extensions (<rdr://4585769>)
1000 const char *ivar_layout;
1001 struct _objc_class_ext *ext;
1002 };
1003
1004 See EmitClassExtension();
1005 */
1006void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001007 DefinedSymbols.insert(ID->getIdentifier());
1008
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001009 const char *ClassName = ID->getName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001010 // FIXME: Gross
1011 ObjCInterfaceDecl *Interface =
1012 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001013 llvm::Constant *Protocols =
1014 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1015 Interface->protocol_begin(),
1016 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001017 const llvm::Type *InterfaceTy =
1018 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1019 unsigned Flags = eClassFlags_Factory;
1020 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1021
1022 // FIXME: Set CXX-structors flag.
1023 if (IsClassHidden(ID->getClassInterface()))
1024 Flags |= eClassFlags_Hidden;
1025
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001026 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1027 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1028 e = ID->instmeth_end(); i != e; ++i) {
1029 // Instance methods should always be defined.
1030 InstanceMethods.push_back(GetMethodConstant(*i));
1031 }
1032 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1033 e = ID->classmeth_end(); i != e; ++i) {
1034 // Class methods should always be defined.
1035 ClassMethods.push_back(GetMethodConstant(*i));
1036 }
1037
1038 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1039 e = ID->propimpl_end(); i != e; ++i) {
1040 ObjCPropertyImplDecl *PID = *i;
1041
1042 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1043 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1044
1045 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1046 if (llvm::Constant *C = GetMethodConstant(MD))
1047 InstanceMethods.push_back(C);
1048 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1049 if (llvm::Constant *C = GetMethodConstant(MD))
1050 InstanceMethods.push_back(C);
1051 }
1052 }
1053
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001054 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001055 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001056 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001057 // Record a reference to the super class.
1058 LazySymbols.insert(Super->getIdentifier());
1059
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001060 Values[ 1] =
1061 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1062 ObjCTypes.ClassPtrTy);
1063 } else {
1064 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1065 }
1066 Values[ 2] = GetClassName(ID->getIdentifier());
1067 // Version is always 0.
1068 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1069 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1070 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1071 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001072 Values[ 7] =
1073 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1074 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001075 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001076 // cache is always NULL.
1077 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1078 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001079 // FIXME: Set ivar_layout
1080 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001081 Values[11] = EmitClassExtension(ID);
1082 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1083 Values);
1084
1085 llvm::GlobalVariable *GV =
1086 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1087 llvm::GlobalValue::InternalLinkage,
1088 Init,
1089 std::string("\01L_OBJC_CLASS_")+ClassName,
1090 &CGM.getModule());
1091 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1092 UsedGlobals.push_back(GV);
1093 // FIXME: Why?
1094 GV->setAlignment(32);
1095 DefinedClasses.push_back(GV);
1096}
1097
1098llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1099 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001100 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001101 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001102 const char *ClassName = ID->getName();
1103 unsigned Flags = eClassFlags_Meta;
1104 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1105
1106 if (IsClassHidden(ID->getClassInterface()))
1107 Flags |= eClassFlags_Hidden;
1108
1109 std::vector<llvm::Constant*> Values(12);
1110 // The isa for the metaclass is the root of the hierarchy.
1111 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1112 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1113 Root = Super;
1114 Values[ 0] =
1115 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1116 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001117 // The super class for the metaclass is emitted as the name of the
1118 // super class. The runtime fixes this up to point to the
1119 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001120 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1121 Values[ 1] =
1122 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1123 ObjCTypes.ClassPtrTy);
1124 } else {
1125 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1126 }
1127 Values[ 2] = GetClassName(ID->getIdentifier());
1128 // Version is always 0.
1129 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1130 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1131 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1132 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001133 Values[ 7] =
1134 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1135 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001136 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001137 // cache is always NULL.
1138 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1139 Values[ 9] = Protocols;
1140 // ivar_layout for metaclass is always NULL.
1141 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1142 // The class extension is always unused for metaclasses.
1143 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1144 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1145 Values);
1146
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001147 std::string Name("\01L_OBJC_METACLASS_");
1148 Name += ClassName;
1149
1150 // Check for a forward reference.
1151 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1152 if (GV) {
1153 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1154 "Forward metaclass reference has incorrect type.");
1155 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1156 GV->setInitializer(Init);
1157 } else {
1158 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1159 llvm::GlobalValue::InternalLinkage,
1160 Init, Name,
1161 &CGM.getModule());
1162 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001163 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1164 UsedGlobals.push_back(GV);
1165 // FIXME: Why?
1166 GV->setAlignment(32);
1167
1168 return GV;
1169}
1170
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001171llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1172 std::string Name("\01L_OBJC_METACLASS_");
1173 Name += ID->getName();
1174
1175 // FIXME: Should we look these up somewhere other than the
1176 // module. Its a bit silly since we only generate these while
1177 // processing an implementation, so exactly one pointer would work
1178 // if know when we entered/exitted an implementation block.
1179
1180 // Check for an existing forward reference.
1181 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1182 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1183 "Forward metaclass reference has incorrect type.");
1184 return GV;
1185 } else {
1186 // Generate as an external reference to keep a consistent
1187 // module. This will be patched up when we emit the metaclass.
1188 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1189 llvm::GlobalValue::ExternalLinkage,
1190 0,
1191 Name,
1192 &CGM.getModule());
1193 }
1194}
1195
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001196/*
1197 struct objc_class_ext {
1198 uint32_t size;
1199 const char *weak_ivar_layout;
1200 struct _objc_property_list *properties;
1201 };
1202*/
1203llvm::Constant *
1204CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1205 uint64_t Size =
1206 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1207
1208 std::vector<llvm::Constant*> Values(3);
1209 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001210 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001211 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001212 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1213 ID->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001214 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001215 ID->getClassInterface()->classprop_begin(),
1216 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001217
1218 // Return null if no extension bits are used.
1219 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1220 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1221
1222 llvm::Constant *Init =
1223 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1224 llvm::GlobalVariable *GV =
1225 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1226 llvm::GlobalValue::InternalLinkage,
1227 Init,
1228 (std::string("\01L_OBJC_CLASSEXT_") +
1229 ID->getName()),
1230 &CGM.getModule());
1231 // No special section, but goes in llvm.used
1232 UsedGlobals.push_back(GV);
1233
1234 return GV;
1235}
1236
1237/*
1238 struct objc_ivar {
1239 char *ivar_name;
1240 char *ivar_type;
1241 int ivar_offset;
1242 };
1243
1244 struct objc_ivar_list {
1245 int ivar_count;
1246 struct objc_ivar list[count];
1247 };
1248 */
1249llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1250 bool ForClass,
1251 const llvm::Type *InterfaceTy) {
1252 std::vector<llvm::Constant*> Ivars, Ivar(3);
1253
1254 // When emitting the root class GCC emits ivar entries for the
1255 // actual class structure. It is not clear if we need to follow this
1256 // behavior; for now lets try and get away with not doing it. If so,
1257 // the cleanest solution would be to make up an ObjCInterfaceDecl
1258 // for the class.
1259 if (ForClass)
1260 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1261
1262 const llvm::StructLayout *Layout =
1263 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1264 for (ObjCInterfaceDecl::ivar_iterator
1265 i = ID->getClassInterface()->ivar_begin(),
1266 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1267 ObjCIvarDecl *V = *i;
1268 unsigned Offset =
1269 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1270 std::string TypeStr;
1271 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1272 Ivar[0] = GetMethodVarName(V->getIdentifier());
1273 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr,
1274 EncodingRecordTypes);
1275 Ivar[1] = GetMethodVarType(TypeStr);
1276 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
1277 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy,
1278 Ivar));
1279 }
1280
1281 // Return null for empty list.
1282 if (Ivars.empty())
1283 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1284
1285 std::vector<llvm::Constant*> Values(2);
1286 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1287 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1288 Ivars.size());
1289 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1290 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1291
1292 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1293 "\01L_OBJC_INSTANCE_VARIABLES_");
1294 llvm::GlobalVariable *GV =
1295 new llvm::GlobalVariable(Init->getType(), false,
1296 llvm::GlobalValue::InternalLinkage,
1297 Init,
1298 std::string(Prefix) + ID->getName(),
1299 &CGM.getModule());
1300 if (ForClass) {
1301 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1302 // FIXME: Why is this only here?
1303 GV->setAlignment(32);
1304 } else {
1305 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1306 }
1307 UsedGlobals.push_back(GV);
1308 return llvm::ConstantExpr::getBitCast(GV,
1309 ObjCTypes.IvarListPtrTy);
1310}
1311
1312/*
1313 struct objc_method {
1314 SEL method_name;
1315 char *method_types;
1316 void *method;
1317 };
1318
1319 struct objc_method_list {
1320 struct objc_method_list *obsolete;
1321 int count;
1322 struct objc_method methods_list[count];
1323 };
1324*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001325
1326/// GetMethodConstant - Return a struct objc_method constant for the
1327/// given method if it has been defined. The result is null if the
1328/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001329llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001330 // FIXME: Use DenseMap::lookup
1331 llvm::Function *Fn = MethodDefinitions[MD];
1332 if (!Fn)
1333 return 0;
1334
1335 std::vector<llvm::Constant*> Method(3);
1336 Method[0] =
1337 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1338 ObjCTypes.SelectorPtrTy);
1339 Method[1] = GetMethodVarType(MD);
1340 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1341 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1342}
1343
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001344llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1345 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001346 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001347 // Return null for empty list.
1348 if (Methods.empty())
1349 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1350
1351 std::vector<llvm::Constant*> Values(3);
1352 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1353 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1354 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1355 Methods.size());
1356 Values[2] = llvm::ConstantArray::get(AT, Methods);
1357 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1358
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001359 llvm::GlobalVariable *GV =
1360 new llvm::GlobalVariable(Init->getType(), false,
1361 llvm::GlobalValue::InternalLinkage,
1362 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001363 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001364 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001365 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001366 UsedGlobals.push_back(GV);
1367 return llvm::ConstantExpr::getBitCast(GV,
1368 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001369}
1370
1371llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001372 std::string Name;
1373 GetNameForMethod(OMD, Name);
1374
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001375 const llvm::FunctionType *MethodTy =
1376 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001377 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001378 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001379 llvm::GlobalValue::InternalLinkage,
1380 Name,
1381 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001382 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001383
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001384 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001385}
1386
1387llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001388 // Abuse this interface function as a place to finalize.
1389 FinishModule();
1390
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001391 return NULL;
1392}
1393
Daniel Dunbar49f66022008-09-24 03:38:44 +00001394llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1395 return ObjCTypes.GetPropertyFn;
1396}
1397
1398llvm::Function *CGObjCMac::GetPropertySetFunction() {
1399 return ObjCTypes.SetPropertyFn;
1400}
1401
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001402llvm::Function *CGObjCMac::EnumerationMutationFunction()
1403{
1404 return ObjCTypes.EnumerationMutationFn;
1405}
1406
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001407/*
1408
1409Objective-C setjmp-longjmp (sjlj) Exception Handling
1410--
1411
1412The basic framework for a @try-catch-finally is as follows:
1413{
1414 objc_exception_data d;
1415 id _rethrow = null;
1416
1417 objc_exception_try_enter(&d);
1418 if (!setjmp(d.jmp_buf)) {
1419 ... try body ...
1420 } else {
1421 // exception path
1422 id _caught = objc_exception_extract(&d);
1423
1424 // enter new try scope for handlers
1425 if (!setjmp(d.jmp_buf)) {
1426 ... match exception and execute catch blocks ...
1427
1428 // fell off end, rethrow.
1429 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001430 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001431 } else {
1432 // exception in catch block
1433 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001434 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001435 }
1436 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001437 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001438
1439finally:
1440 // match either the initial try_enter or the catch try_enter,
1441 // depending on the path followed.
1442 objc_exception_try_exit(&d);
1443finally_no_exit:
1444 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001445 ... dispatch to finally destination ...
1446
1447finally_rethrow:
1448 objc_exception_throw(_rethrow);
1449
1450finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001451}
1452
1453This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001454uses _rethrow to determine if objc_exception_try_exit should be called
1455and if the object should be rethrown. This breaks in the face of
1456throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001457
1458We specialize this framework for a few particular circumstances:
1459
1460 - If there are no catch blocks, then we avoid emitting the second
1461 exception handling context.
1462
1463 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1464 e)) we avoid emitting the code to rethrow an uncaught exception.
1465
1466 - FIXME: If there is no @finally block we can do a few more
1467 simplifications.
1468
1469Rethrows and Jumps-Through-Finally
1470--
1471
1472Support for implicit rethrows and jumping through the finally block is
1473handled by storing the current exception-handling context in
1474ObjCEHStack.
1475
Daniel Dunbar898d5082008-09-30 01:06:03 +00001476In order to implement proper @finally semantics, we support one basic
1477mechanism for jumping through the finally block to an arbitrary
1478destination. Constructs which generate exits from a @try or @catch
1479block use this mechanism to implement the proper semantics by chaining
1480jumps, as necessary.
1481
1482This mechanism works like the one used for indirect goto: we
1483arbitrarily assign an ID to each destination and store the ID for the
1484destination in a variable prior to entering the finally block. At the
1485end of the finally block we simply create a switch to the proper
1486destination.
1487
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001488*/
1489
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001490void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001491 const ObjCAtTryStmt &S) {
1492 // Create various blocks we refer to for handling @finally.
1493 llvm::BasicBlock *FinallyBlock = llvm::BasicBlock::Create("finally");
1494 llvm::BasicBlock *FinallyNoExit = llvm::BasicBlock::Create("finally.noexit");
1495 llvm::BasicBlock *FinallyRethrow = llvm::BasicBlock::Create("finally.throw");
1496 llvm::BasicBlock *FinallyEnd = llvm::BasicBlock::Create("finally.end");
1497 llvm::Value *DestCode =
1498 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1499
1500 // Generate jump code. Done here so we can directly add things to
1501 // the switch instruction.
1502 llvm::BasicBlock *FinallyJump = llvm::BasicBlock::Create("finally.jump");
1503 llvm::SwitchInst *FinallySwitch =
1504 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1505 FinallyEnd, 10, FinallyJump);
1506
1507 // Push an EH context entry, used for handling rethrows and jumps
1508 // through finally.
1509 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1510 FinallySwitch, DestCode);
1511 CGF.ObjCEHStack.push_back(&EHEntry);
1512
1513 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001514 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1515 "exceptiondata.ptr");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001516 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, "_rethrow");
Anders Carlsson80f25672008-09-09 17:59:25 +00001517
1518 // Enter a new try block and call setjmp.
1519 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1520 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1521 "jmpbufarray");
1522 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1523 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1524 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001525
Anders Carlsson80f25672008-09-09 17:59:25 +00001526 llvm::BasicBlock *TryBlock = llvm::BasicBlock::Create("try");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001527 llvm::BasicBlock *TryHandler = llvm::BasicBlock::Create("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001528 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001529 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001530
1531 // Emit the @try block.
1532 CGF.EmitBlock(TryBlock);
1533 CGF.EmitStmt(S.getTryBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001534 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001535
1536 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001537 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001538
1539 // Retrieve the exception object. We may emit multiple blocks but
1540 // nothing can cross this so the value is already in SSA form.
1541 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1542 ExceptionData,
1543 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001544 EHEntry.Exception = Caught;
Daniel Dunbar55e40722008-09-27 07:03:52 +00001545 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1546 // Enter a new exception try block (in case a @catch block throws
1547 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001548 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001549
Anders Carlsson80f25672008-09-09 17:59:25 +00001550 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1551 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001552 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001553
1554 llvm::BasicBlock *CatchBlock = llvm::BasicBlock::Create("catch");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001555 llvm::BasicBlock *CatchHandler = llvm::BasicBlock::Create("catch.handler");
1556 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001557
1558 CGF.EmitBlock(CatchBlock);
1559
Daniel Dunbar55e40722008-09-27 07:03:52 +00001560 // Handle catch list. As a special case we check if everything is
1561 // matched and avoid generating code for falling off the end if
1562 // so.
1563 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001564 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001565 llvm::BasicBlock *NextCatchBlock = llvm::BasicBlock::Create("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001566
Anders Carlssondde0a942008-09-11 09:15:33 +00001567 const DeclStmt *CatchParam =
1568 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001569 const VarDecl *VD = 0;
1570 const PointerType *PT = 0;
1571
Anders Carlsson80f25672008-09-09 17:59:25 +00001572 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001573 if (!CatchParam) {
1574 AllMatched = true;
1575 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001576 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001577 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001578
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001579 // catch(id e) always matches.
1580 // FIXME: For the time being we also match id<X>; this should
1581 // be rejected by Sema instead.
1582 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1583 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001584 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001585 }
1586
Daniel Dunbar55e40722008-09-27 07:03:52 +00001587 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001588 if (CatchParam) {
1589 CGF.EmitStmt(CatchParam);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001590 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001591 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001592
Anders Carlssondde0a942008-09-11 09:15:33 +00001593 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001594 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001595 break;
1596 }
1597
Daniel Dunbar129271a2008-09-27 07:36:24 +00001598 assert(PT && "Unexpected non-pointer type in @catch");
1599 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001600 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001601 assert(ObjCType && "Catch parameter must have Objective-C type!");
1602
1603 // Check if the @catch block matches the exception object.
1604 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1605
Anders Carlsson80f25672008-09-09 17:59:25 +00001606 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1607 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001608
1609 llvm::BasicBlock *MatchedBlock = llvm::BasicBlock::Create("matched");
1610
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001611 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001612 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001613
1614 // Emit the @catch block.
1615 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001616 CGF.EmitStmt(CatchParam);
1617
1618 llvm::Value *Tmp =
1619 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1620 "tmp");
1621 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001622
1623 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001624 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001625
1626 CGF.EmitBlock(NextCatchBlock);
1627 }
1628
Daniel Dunbar55e40722008-09-27 07:03:52 +00001629 if (!AllMatched) {
1630 // None of the handlers caught the exception, so store it to be
1631 // rethrown at the end of the @finally block.
1632 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001633 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001634 }
1635
1636 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001637 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001638 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1639 ExceptionData),
1640 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001641 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001642 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001643 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001644 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001645 }
1646
Daniel Dunbar898d5082008-09-30 01:06:03 +00001647 // Pop the exception-handling stack entry. It is important to do
1648 // this now, because the code in the @finally block is not in this
1649 // context.
1650 CGF.ObjCEHStack.pop_back();
1651
Anders Carlsson80f25672008-09-09 17:59:25 +00001652 // Emit the @finally block.
1653 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001654 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001655
1656 CGF.EmitBlock(FinallyNoExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00001657 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1658 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1659
Daniel Dunbar898d5082008-09-30 01:06:03 +00001660 CGF.EmitBlock(FinallyJump);
1661
1662 CGF.EmitBlock(FinallyRethrow);
1663 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1664 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001665 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001666
1667 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001668}
1669
1670void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001671 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001672 llvm::Value *ExceptionAsObject;
1673
1674 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1675 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1676 ExceptionAsObject =
1677 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1678 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001679 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001680 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001681 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001682 }
1683
1684 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001685 CGF.Builder.CreateUnreachable();
1686 CGF.EmitBlock(llvm::BasicBlock::Create("bb"));
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001687}
1688
Daniel Dunbar898d5082008-09-30 01:06:03 +00001689void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1690 llvm::BasicBlock *Dst,
1691 bool ExecuteTryExit) {
1692 llvm::BasicBlock *Src = Builder.GetInsertBlock();
1693
1694 if (isDummyBlock(Src))
1695 return;
1696
1697 // Find the destination code for this block. We always use 0 for the
1698 // fallthrough block (default destination).
1699 llvm::SwitchInst *SI = E->FinallySwitch;
1700 llvm::ConstantInt *ID;
1701 if (Dst == SI->getDefaultDest()) {
1702 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1703 } else {
1704 ID = SI->findCaseDest(Dst);
1705 if (!ID) {
1706 // No code found, get a new unique one by just using the number
1707 // of switch successors.
1708 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1709 SI->addCase(ID, Dst);
1710 }
1711 }
1712
1713 // Set the destination code and branch.
1714 Builder.CreateStore(ID, E->DestCode);
1715 Builder.CreateBr(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
1716}
1717
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001718/* *** Private Interface *** */
1719
1720/// EmitImageInfo - Emit the image info marker used to encode some module
1721/// level information.
1722///
1723/// See: <rdr://4810609&4810587&4810587>
1724/// struct IMAGE_INFO {
1725/// unsigned version;
1726/// unsigned flags;
1727/// };
1728enum ImageInfoFlags {
1729 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1730 eImageInfo_GarbageCollected = (1 << 1),
1731 eImageInfo_GCOnly = (1 << 2)
1732};
1733
1734void CGObjCMac::EmitImageInfo() {
1735 unsigned version = 0; // Version is unused?
1736 unsigned flags = 0;
1737
1738 // FIXME: Fix and continue?
1739 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1740 flags |= eImageInfo_GarbageCollected;
1741 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1742 flags |= eImageInfo_GCOnly;
1743
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001744 // Emitted as int[2];
1745 llvm::Constant *values[2] = {
1746 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1747 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1748 };
1749 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001750 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001751 new llvm::GlobalVariable(AT, true,
1752 llvm::GlobalValue::InternalLinkage,
1753 llvm::ConstantArray::get(AT, values, 2),
1754 "\01L_OBJC_IMAGE_INFO",
1755 &CGM.getModule());
1756
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001757 if (ObjCABI == 1) {
1758 GV->setSection("__OBJC, __image_info,regular");
1759 } else {
1760 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1761 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001762
1763 UsedGlobals.push_back(GV);
1764}
1765
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001766
1767// struct objc_module {
1768// unsigned long version;
1769// unsigned long size;
1770// const char *name;
1771// Symtab symtab;
1772// };
1773
1774// FIXME: Get from somewhere
1775static const int ModuleVersion = 7;
1776
1777void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001778 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1779
1780 std::vector<llvm::Constant*> Values(4);
1781 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1782 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001783 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001784 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001785 Values[3] = EmitModuleSymbols();
1786
1787 llvm::GlobalVariable *GV =
1788 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1789 llvm::GlobalValue::InternalLinkage,
1790 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1791 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001792 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001793 &CGM.getModule());
1794 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1795 UsedGlobals.push_back(GV);
1796}
1797
1798llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001799 unsigned NumClasses = DefinedClasses.size();
1800 unsigned NumCategories = DefinedCategories.size();
1801
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001802 // Return null if no symbols were defined.
1803 if (!NumClasses && !NumCategories)
1804 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1805
1806 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001807 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1808 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1809 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1810 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1811
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001812 // The runtime expects exactly the list of defined classes followed
1813 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001814 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001815 for (unsigned i=0; i<NumClasses; i++)
1816 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1817 ObjCTypes.Int8PtrTy);
1818 for (unsigned i=0; i<NumCategories; i++)
1819 Symbols[NumClasses + i] =
1820 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1821 ObjCTypes.Int8PtrTy);
1822
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001823 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001824 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001825 NumClasses + NumCategories),
1826 Symbols);
1827
1828 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1829
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001830 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001831 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001832 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001833 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001834 "\01L_OBJC_SYMBOLS",
1835 &CGM.getModule());
1836 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1837 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001838 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
1839}
1840
1841llvm::Value *CGObjCMac::EmitClassRef(llvm::IRBuilder<> &Builder,
1842 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001843 LazySymbols.insert(ID->getIdentifier());
1844
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001845 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
1846
1847 if (!Entry) {
1848 llvm::Constant *Casted =
1849 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
1850 ObjCTypes.ClassPtrTy);
1851 Entry =
1852 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
1853 llvm::GlobalValue::InternalLinkage,
1854 Casted, "\01L_OBJC_CLASS_REFERENCES_",
1855 &CGM.getModule());
1856 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
1857 UsedGlobals.push_back(Entry);
1858 }
1859
1860 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001861}
1862
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001863llvm::Value *CGObjCMac::EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
1864 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
1865
1866 if (!Entry) {
1867 llvm::Constant *Casted =
1868 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
1869 ObjCTypes.SelectorPtrTy);
1870 Entry =
1871 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
1872 llvm::GlobalValue::InternalLinkage,
1873 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
1874 &CGM.getModule());
1875 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
1876 UsedGlobals.push_back(Entry);
1877 }
1878
1879 return Builder.CreateLoad(Entry, false, "tmp");
1880}
1881
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001882llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
1883 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001884
1885 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001886 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001887 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001888 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001889 llvm::GlobalValue::InternalLinkage,
1890 C, "\01L_OBJC_CLASS_NAME_",
1891 &CGM.getModule());
1892 Entry->setSection("__TEXT,__cstring,cstring_literals");
1893 UsedGlobals.push_back(Entry);
1894 }
1895
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001896 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001897}
1898
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001899llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
1900 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
1901
1902 if (!Entry) {
1903 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
1904 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001905 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001906 llvm::GlobalValue::InternalLinkage,
1907 C, "\01L_OBJC_METH_VAR_NAME_",
1908 &CGM.getModule());
1909 Entry->setSection("__TEXT,__cstring,cstring_literals");
1910 UsedGlobals.push_back(Entry);
1911 }
1912
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001913 return getConstantGEP(Entry, 0, 0);
1914}
1915
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001916// FIXME: Merge into a single cstring creation function.
1917llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
1918 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
1919}
1920
1921// FIXME: Merge into a single cstring creation function.
1922llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
1923 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
1924}
1925
1926llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
1927 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001928
1929 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001930 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001931 Entry =
1932 new llvm::GlobalVariable(C->getType(), false,
1933 llvm::GlobalValue::InternalLinkage,
1934 C, "\01L_OBJC_METH_VAR_TYPE_",
1935 &CGM.getModule());
1936 Entry->setSection("__TEXT,__cstring,cstring_literals");
1937 UsedGlobals.push_back(Entry);
1938 }
1939
1940 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001941}
1942
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001943// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001944llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001945 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001946 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
1947 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001948 return GetMethodVarType(TypeStr);
1949}
1950
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001951// FIXME: Merge into a single cstring creation function.
1952llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
1953 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
1954
1955 if (!Entry) {
1956 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
1957 Entry =
1958 new llvm::GlobalVariable(C->getType(), false,
1959 llvm::GlobalValue::InternalLinkage,
1960 C, "\01L_OBJC_PROP_NAME_ATTR_",
1961 &CGM.getModule());
1962 Entry->setSection("__TEXT,__cstring,cstring_literals");
1963 UsedGlobals.push_back(Entry);
1964 }
1965
1966 return getConstantGEP(Entry, 0, 0);
1967}
1968
1969// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001970// FIXME: This Decl should be more precise.
1971llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
1972 const Decl *Container) {
1973 std::string TypeStr;
1974 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001975 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
1976}
1977
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001978void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
1979 std::string &NameOut) {
1980 // FIXME: Find the mangling GCC uses.
1981 std::stringstream s;
1982 s << (D->isInstance() ? "-" : "+");
1983 s << "[";
1984 s << D->getClassInterface()->getName();
1985 s << " ";
1986 s << D->getSelector().getName();
1987 s << "]";
1988 NameOut = s.str();
1989}
1990
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001991void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001992 EmitModuleInfo();
1993
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001994 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001995
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001996 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001997 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001998 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001999 }
2000
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002001 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002002 llvm::GlobalValue *GV =
2003 new llvm::GlobalVariable(AT, false,
2004 llvm::GlobalValue::AppendingLinkage,
2005 llvm::ConstantArray::get(AT, Used),
2006 "llvm.used",
2007 &CGM.getModule());
2008
2009 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002010
2011 // Add assembler directives to add lazy undefined symbol references
2012 // for classes which are referenced but not defined. This is
2013 // important for correct linker interaction.
2014
2015 // FIXME: Uh, this isn't particularly portable.
2016 std::stringstream s;
2017 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2018 e = LazySymbols.end(); i != e; ++i) {
2019 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2020 }
2021 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2022 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002023 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002024 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2025 }
2026 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002027}
2028
2029/* *** */
2030
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002031ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002032 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002033{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002034 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2035 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002036
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002037 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002038 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002039 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002040 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2041
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002042 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2043 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002044
2045 // FIXME: It would be nice to unify this with the opaque type, so
2046 // that the IR comes out a bit cleaner.
2047 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2048 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002049
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002050 MethodDescriptionTy =
2051 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002052 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002053 NULL);
2054 CGM.getModule().addTypeName("struct._objc_method_description",
2055 MethodDescriptionTy);
2056
2057 MethodDescriptionListTy =
2058 llvm::StructType::get(IntTy,
2059 llvm::ArrayType::get(MethodDescriptionTy, 0),
2060 NULL);
2061 CGM.getModule().addTypeName("struct._objc_method_description_list",
2062 MethodDescriptionListTy);
2063 MethodDescriptionListPtrTy =
2064 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2065
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002066 PropertyTy = llvm::StructType::get(Int8PtrTy,
2067 Int8PtrTy,
2068 NULL);
2069 CGM.getModule().addTypeName("struct._objc_property",
2070 PropertyTy);
2071
2072 PropertyListTy = llvm::StructType::get(IntTy,
2073 IntTy,
2074 llvm::ArrayType::get(PropertyTy, 0),
2075 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002076 CGM.getModule().addTypeName("struct._objc_property_list",
2077 PropertyListTy);
2078 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2079
2080 // Protocol description structures
2081
2082 ProtocolExtensionTy =
2083 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2084 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2085 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2086 PropertyListPtrTy,
2087 NULL);
2088 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2089 ProtocolExtensionTy);
2090 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2091
2092 // Handle recursive construction of Protocl and ProtocolList types
2093
2094 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2095 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2096
2097 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2098 LongTy,
2099 llvm::ArrayType::get(ProtocolTyHolder, 0),
2100 NULL);
2101 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2102
2103 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002104 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002105 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2106 MethodDescriptionListPtrTy,
2107 MethodDescriptionListPtrTy,
2108 NULL);
2109 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2110
2111 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2112 CGM.getModule().addTypeName("struct._objc_protocol_list",
2113 ProtocolListTy);
2114 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2115
2116 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2117 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2118 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002119
2120 // Class description structures
2121
2122 IvarTy = llvm::StructType::get(Int8PtrTy,
2123 Int8PtrTy,
2124 IntTy,
2125 NULL);
2126 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2127
2128 IvarListTy = llvm::OpaqueType::get();
2129 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2130 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2131
2132 MethodTy = llvm::StructType::get(SelectorPtrTy,
2133 Int8PtrTy,
2134 Int8PtrTy,
2135 NULL);
2136 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2137
2138 MethodListTy = llvm::OpaqueType::get();
2139 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2140 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2141
2142 CacheTy = llvm::OpaqueType::get();
2143 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2144 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2145
2146 ClassExtensionTy =
2147 llvm::StructType::get(IntTy,
2148 Int8PtrTy,
2149 PropertyListPtrTy,
2150 NULL);
2151 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2152 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2153
2154 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2155
2156 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2157 llvm::PointerType::getUnqual(ClassTyHolder),
2158 Int8PtrTy,
2159 LongTy,
2160 LongTy,
2161 LongTy,
2162 IvarListPtrTy,
2163 MethodListPtrTy,
2164 CachePtrTy,
2165 ProtocolListPtrTy,
2166 Int8PtrTy,
2167 ClassExtensionPtrTy,
2168 NULL);
2169 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2170
2171 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2172 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2173 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2174
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002175 CategoryTy = llvm::StructType::get(Int8PtrTy,
2176 Int8PtrTy,
2177 MethodListPtrTy,
2178 MethodListPtrTy,
2179 ProtocolListPtrTy,
2180 IntTy,
2181 PropertyListPtrTy,
2182 NULL);
2183 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2184
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002185 // I'm not sure I like this. The implicit coordination is a bit
2186 // gross. We should solve this in a reasonable fashion because this
2187 // is a pretty common task (match some runtime data structure with
2188 // an LLVM data structure).
2189
2190 // FIXME: This is leaked.
2191 // FIXME: Merge with rewriter code?
2192 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2193 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002194 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002195 FieldDecl *FieldDecls[2];
2196 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2197 Ctx.getObjCIdType());
2198 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2199 Ctx.getObjCClassType());
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002200 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002201
2202 SuperCTy = Ctx.getTagDeclType(RD);
2203 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2204
2205 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002206 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002207
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002208 // Global metadata structures
2209
2210 SymtabTy = llvm::StructType::get(LongTy,
2211 SelectorPtrTy,
2212 ShortTy,
2213 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002214 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002215 NULL);
2216 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2217 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2218
2219 ModuleTy =
2220 llvm::StructType::get(LongTy,
2221 LongTy,
2222 Int8PtrTy,
2223 SymtabPtrTy,
2224 NULL);
2225 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002226
Daniel Dunbar49f66022008-09-24 03:38:44 +00002227 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002228
2229 std::vector<const llvm::Type*> Params;
2230 Params.push_back(ObjectPtrTy);
2231 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002232 MessageSendFn =
2233 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2234 Params,
2235 true),
2236 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002237
2238 Params.clear();
2239 Params.push_back(Int8PtrTy);
2240 Params.push_back(ObjectPtrTy);
2241 Params.push_back(SelectorPtrTy);
2242 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002243 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2244 Params,
2245 true),
2246 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002247
2248 Params.clear();
2249 Params.push_back(ObjectPtrTy);
2250 Params.push_back(SelectorPtrTy);
2251 // FIXME: This should be long double on x86_64?
2252 MessageSendFpretFn =
2253 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2254 Params,
2255 true),
2256 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002257
2258 Params.clear();
2259 Params.push_back(SuperPtrTy);
2260 Params.push_back(SelectorPtrTy);
2261 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002262 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2263 Params,
2264 true),
2265 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002266
2267 Params.clear();
2268 Params.push_back(Int8PtrTy);
2269 Params.push_back(SuperPtrTy);
2270 Params.push_back(SelectorPtrTy);
2271 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002272 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2273 Params,
2274 true),
2275 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002276
2277 // There is no objc_msgSendSuper_fpret? How can that work?
2278 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002279
Daniel Dunbar49f66022008-09-24 03:38:44 +00002280 // Property manipulation functions.
2281
2282 Params.clear();
2283 Params.push_back(ObjectPtrTy);
2284 Params.push_back(SelectorPtrTy);
2285 Params.push_back(LongTy);
2286 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2287 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002288 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2289 Params,
2290 false),
2291 "objc_getProperty");
2292
Daniel Dunbar49f66022008-09-24 03:38:44 +00002293 Params.clear();
2294 Params.push_back(ObjectPtrTy);
2295 Params.push_back(SelectorPtrTy);
2296 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002297 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002298 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2299 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2300 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002301 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2302 Params,
2303 false),
2304 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002305
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002306 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002307
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002308 Params.clear();
2309 Params.push_back(ObjectPtrTy);
2310 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002311 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2312 Params,
2313 false),
2314 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002315
2316 // FIXME: This is the size of the setjmp buffer and should be
2317 // target specific. 18 is what's used on 32-bit X86.
2318 uint64_t SetJmpBufferSize = 18;
2319
2320 // Exceptions
2321 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002322 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002323
2324 ExceptionDataTy =
2325 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2326 SetJmpBufferSize),
2327 StackPtrTy, NULL);
2328 CGM.getModule().addTypeName("struct._objc_exception_data",
2329 ExceptionDataTy);
2330
2331 Params.clear();
2332 Params.push_back(ObjectPtrTy);
2333 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002334 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2335 Params,
2336 false),
2337 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002338
2339 Params.clear();
2340 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2341 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002342 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2343 Params,
2344 false),
2345 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002346 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002347 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2348 Params,
2349 false),
2350 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002351 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002352 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2353 Params,
2354 false),
2355 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002356
2357 Params.clear();
2358 Params.push_back(ClassPtrTy);
2359 Params.push_back(ObjectPtrTy);
2360 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002361 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2362 Params,
2363 false),
2364 "objc_exception_match");
Anders Carlsson124526b2008-09-09 10:10:21 +00002365
2366 Params.clear();
2367 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2368 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002369 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2370 Params,
2371 false),
2372 "_setjmp");
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002373}
2374
2375ObjCTypesHelper::~ObjCTypesHelper() {
2376}
2377
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002378/* *** */
2379
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002380CodeGen::CGObjCRuntime *
2381CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002382 return new CGObjCMac(CGM);
2383}