blob: 03f7b78ec8e0f45d0b95ddcb11694764028e7cd9 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
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;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000054
55 /// PtrObjectPtrTy - LLVM type for id *
56 const llvm::Type *PtrObjectPtrTy;
57
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000058 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000059 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000060 /// ProtocolPtrTy - LLVM type for external protocol handles
61 /// (typeof(Protocol))
62 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000063
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000064 // SuperCTy - clang type for struct objc_super.
65 QualType SuperCTy;
66 // SuperPtrCTy - clang type for struct objc_super *.
67 QualType SuperPtrCTy;
68
Daniel Dunbare8b470d2008-08-23 04:28:29 +000069 /// SuperTy - LLVM type for struct objc_super.
70 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000071 /// SuperPtrTy - LLVM type for struct objc_super *.
72 const llvm::Type *SuperPtrTy;
Daniel Dunbare8b470d2008-08-23 04:28:29 +000073
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000074 /// SymtabTy - LLVM type for struct objc_symtab.
75 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000076 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000078 /// ModuleTy - LLVM type for struct objc_module.
79 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000080
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000081 /// ProtocolTy - LLVM type for struct objc_protocol.
82 const llvm::StructType *ProtocolTy;
83 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
84 const llvm::Type *ProtocolPtrTy;
85 /// ProtocolExtensionTy - LLVM type for struct
86 /// objc_protocol_extension.
87 const llvm::StructType *ProtocolExtensionTy;
88 /// ProtocolExtensionTy - LLVM type for struct
89 /// objc_protocol_extension *.
90 const llvm::Type *ProtocolExtensionPtrTy;
91 /// MethodDescriptionTy - LLVM type for struct
92 /// objc_method_description.
93 const llvm::StructType *MethodDescriptionTy;
94 /// MethodDescriptionListTy - LLVM type for struct
95 /// objc_method_description_list.
96 const llvm::StructType *MethodDescriptionListTy;
97 /// MethodDescriptionListPtrTy - LLVM type for struct
98 /// objc_method_description_list *.
99 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000100 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
101 /// in GCC parlance).
102 const llvm::StructType *PropertyTy;
103 /// PropertyListTy - LLVM type for struct objc_property_list
104 /// (_prop_list_t in GCC parlance).
105 const llvm::StructType *PropertyListTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000106 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
107 const llvm::Type *PropertyListPtrTy;
108 /// ProtocolListTy - LLVM type for struct objc_property_list.
109 const llvm::Type *ProtocolListTy;
110 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
111 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000112 /// CategoryTy - LLVM type for struct objc_category.
113 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000114 /// ClassTy - LLVM type for struct objc_class.
115 const llvm::StructType *ClassTy;
116 /// ClassPtrTy - LLVM type for struct objc_class *.
117 const llvm::Type *ClassPtrTy;
118 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
119 const llvm::StructType *ClassExtensionTy;
120 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
121 const llvm::Type *ClassExtensionPtrTy;
122 /// CacheTy - LLVM type for struct objc_cache.
123 const llvm::Type *CacheTy;
124 /// CachePtrTy - LLVM type for struct objc_cache *.
125 const llvm::Type *CachePtrTy;
126 // IvarTy - LLVM type for struct objc_ivar.
127 const llvm::StructType *IvarTy;
128 /// IvarListTy - LLVM type for struct objc_ivar_list.
129 const llvm::Type *IvarListTy;
130 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
131 const llvm::Type *IvarListPtrTy;
132 // MethodTy - LLVM type for struct objc_method.
133 const llvm::StructType *MethodTy;
134 /// MethodListTy - LLVM type for struct objc_method_list.
135 const llvm::Type *MethodListTy;
136 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
137 const llvm::Type *MethodListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000138
Daniel Dunbar49f66022008-09-24 03:38:44 +0000139 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000140 llvm::Function *EnumerationMutationFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000141
142 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
143 const llvm::Type *ExceptionDataTy;
144
145 /// ExceptionThrowFn - LLVM objc_exception_throw function.
146 llvm::Function *ExceptionThrowFn;
147
148 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
149 llvm::Function *ExceptionTryEnterFn;
150
151 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
152 llvm::Function *ExceptionTryExitFn;
153
154 /// ExceptionExtractFn - LLVM objc_exception_extract function.
155 llvm::Function *ExceptionExtractFn;
156
157 /// ExceptionMatchFn - LLVM objc_exception_match function.
158 llvm::Function *ExceptionMatchFn;
159
160 /// SetJmpFn - LLVM _setjmp function.
161 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000162
163 /// SyncEnterFn - LLVM object_sync_enter function.
164 llvm::Function *SyncEnterFn;
165
166 /// SyncExitFn - LLVM object_sync_exit function.
167 llvm::Function *SyncExitFn;
168
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000169 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
170 llvm::Function *GcReadWeakFn;
171
172 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
173 llvm::Function *GcAssignWeakFn;
174
175 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
176 llvm::Function *GcAssignGlobalFn;
177
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000178 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
179 llvm::Function *GcAssignIvarFn;
180
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000181 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
182 llvm::Function *GcAssignStrongCastFn;
183
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000184public:
185 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
186 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000187
188
189 llvm::Function *getSendFn(bool IsSuper) {
190 return IsSuper ? MessageSendSuperFn : MessageSendFn;
191 }
192
193 llvm::Function *getSendStretFn(bool IsSuper) {
194 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
195 }
196
197 llvm::Function *getSendFpretFn(bool IsSuper) {
198 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
199 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000200};
201
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000202class CGObjCMac : public CodeGen::CGObjCRuntime {
203private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204 CodeGen::CodeGenModule &CGM;
205 ObjCTypesHelper ObjCTypes;
206 /// ObjCABI - FIXME: Not sure yet.
207 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000208
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000209 /// LazySymbols - Symbols to generate a lazy reference for. See
210 /// DefinedSymbols and FinishModule().
211 std::set<IdentifierInfo*> LazySymbols;
212
213 /// DefinedSymbols - External symbols which are defined by this
214 /// module. The symbols in this list and LazySymbols are used to add
215 /// special linker symbols which ensure that Objective-C modules are
216 /// linked properly.
217 std::set<IdentifierInfo*> DefinedSymbols;
218
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000219 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000220 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000221
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000222 /// MethodVarNames - uniqued method variable names.
223 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
224
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000225 /// MethodVarTypes - uniqued method type signatures. We have to use
226 /// a StringMap here because have no other unique reference.
227 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
228
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000229 /// MethodDefinitions - map of methods which have been defined in
230 /// this translation unit.
231 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
232
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000233 /// PropertyNames - uniqued method variable names.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
235
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000236 /// ClassReferences - uniqued class references.
237 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
238
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000239 /// SelectorReferences - uniqued selector references.
240 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
241
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000242 /// Protocols - Protocols for which an objc_protocol structure has
243 /// been emitted. Forward declarations are handled by creating an
244 /// empty structure whose initializer is filled in when/if defined.
245 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
246
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000247 /// DefinedProtocols - Protocols which have actually been
248 /// defined. We should not need this, see FIXME in GenerateProtocol.
249 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
250
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000251 /// DefinedClasses - List of defined classes.
252 std::vector<llvm::GlobalValue*> DefinedClasses;
253
254 /// DefinedCategories - List of defined categories.
255 std::vector<llvm::GlobalValue*> DefinedCategories;
256
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000257 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000258 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000259 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000260
261 /// EmitImageInfo - Emit the image info marker used to encode some module
262 /// level information.
263 void EmitImageInfo();
264
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000265 /// EmitModuleInfo - Another marker encoding module level
266 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000267 void EmitModuleInfo();
268
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000269 /// EmitModuleSymols - Emit module symbols, the list of defined
270 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000271 llvm::Constant *EmitModuleSymbols();
272
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000273 /// FinishModule - Write out global data structures at the end of
274 /// processing a translation unit.
275 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000276
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000277 /// EmitClassExtension - Generate the class extension structure used
278 /// to store the weak ivar layout and properties. The return value
279 /// has type ClassExtensionPtrTy.
280 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
281
282 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
283 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000284 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000285 const ObjCInterfaceDecl *ID);
286
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000287 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000288 QualType ResultType,
289 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000290 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000291 QualType Arg0Ty,
292 bool IsSuper,
293 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000294
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000295 /// EmitIvarList - Emit the ivar list for the given
296 /// implementation. If ForClass is true the list of class ivars
297 /// (i.e. metaclass ivars) is emitted, otherwise the list of
298 /// interface ivars will be emitted. The return value has type
299 /// IvarListPtrTy.
300 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
301 bool ForClass,
302 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000303
304 /// EmitMetaClass - Emit a forward reference to the class structure
305 /// for the metaclass of the given interface. The return value has
306 /// type ClassPtrTy.
307 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
308
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000309 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000310 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000311 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
312 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000313 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000314 const ConstantVector &Methods);
315
316 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
317
318 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000319
320 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000321 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000322 llvm::Constant *EmitMethodList(const std::string &Name,
323 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000324 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000325
326 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000327 /// method declarations.
328 /// - TypeName: The name for the type containing the methods.
329 /// - IsProtocol: True iff these methods are for a protocol.
330 /// - ClassMethds: True iff these are class methods.
331 /// - Required: When true, only "required" methods are
332 /// listed. Similarly, when false only "optional" methods are
333 /// listed. For classes this should always be true.
334 /// - begin, end: The method list to output.
335 ///
336 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000337 llvm::Constant *EmitMethodDescList(const std::string &Name,
338 const char *Section,
339 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000340
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000341 /// EmitPropertyList - Emit the given property list. The return
342 /// value has type PropertyListPtrTy.
343 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000344 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000345 ObjCPropertyDecl * const *begin,
346 ObjCPropertyDecl * const *end);
347
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000348 /// GetOrEmitProtocol - Get the protocol object for the given
349 /// declaration, emitting it if necessary. The return value has type
350 /// ProtocolPtrTy.
351 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
352
353 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
354 /// object for the given declaration, emitting it if needed. These
355 /// forward references will be filled in with empty bodies if no
356 /// definition is seen. The return value has type ProtocolPtrTy.
357 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
358
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000359 /// EmitProtocolExtension - Generate the protocol extension
360 /// structure used to store optional instance and class methods, and
361 /// protocol properties. The return value has type
362 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000363 llvm::Constant *
364 EmitProtocolExtension(const ObjCProtocolDecl *PD,
365 const ConstantVector &OptInstanceMethods,
366 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367
368 /// EmitProtocolList - Generate the list of referenced
369 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000370 llvm::Constant *EmitProtocolList(const std::string &Name,
371 ObjCProtocolDecl::protocol_iterator begin,
372 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000373
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000374 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
375 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000376 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000377
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000378 /// GetProtocolRef - Return a reference to the internal protocol
379 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000380 /// defined. The return value has type ProtocolPtrTy.
381 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000383 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000384 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000385 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000386
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000387 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000388 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000389 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000390 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000392
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000393 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000394 /// selector's name. The return value has type char *.
395
396 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000397 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000399
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000400 /// GetPropertyName - Return a unique constant for the given
401 /// name. The return value has type char *.
402 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
403
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000404 // FIXME: This can be dropped once string functions are unified.
405 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
406 const Decl *Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000407
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 std::string &NameOut);
412
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000413public:
414 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000415 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000416
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000417 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000418 QualType ResultType,
419 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000420 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000421 bool IsClassMessage,
422 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000423
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000424 virtual CodeGen::RValue
425 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000426 QualType ResultType,
427 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000428 const ObjCInterfaceDecl *Class,
429 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000430 bool IsClassMessage,
431 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000432
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000434 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000435
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000436 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000437
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000438 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000439
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000440 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000441
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000442 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000443
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000444 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000445 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000446
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000447 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000448
449 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000450 virtual llvm::Function *GetPropertyGetFunction();
451 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000452 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000453
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000454 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
455 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000456 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
457 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000458 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000459 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000460 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
461 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000462 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
463 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000464 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
465 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000466 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
467 llvm::Value *src, llvm::Value *dest);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000468};
469} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000470
471/* *** Helper Functions *** */
472
473/// getConstantGEP() - Help routine to construct simple GEPs.
474static llvm::Constant *getConstantGEP(llvm::Constant *C,
475 unsigned idx0,
476 unsigned idx1) {
477 llvm::Value *Idxs[] = {
478 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
479 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
480 };
481 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
482}
483
484/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000485
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000486CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
487 : CGM(cgm),
488 ObjCTypes(cgm),
489 ObjCABI(1)
490{
491 // FIXME: How does this get set in GCC? And what does it even mean?
492 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
493 ObjCABI = 2;
494
495 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000496}
497
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000498/// GetClass - Return a reference to the class for the given interface
499/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000500llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000501 const ObjCInterfaceDecl *ID) {
502 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000503}
504
505/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000506llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000507 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000508}
509
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000510/// Generate a constant CFString object.
511/*
512 struct __builtin_CFString {
513 const int *isa; // point to __CFConstantStringClassReference
514 int flags;
515 const char *str;
516 long length;
517 };
518*/
519
520llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000521 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000522}
523
524/// Generates a message send where the super is the receiver. This is
525/// a message send to self with special delivery semantics indicating
526/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000527CodeGen::RValue
528CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000529 QualType ResultType,
530 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000531 const ObjCInterfaceDecl *Class,
532 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000533 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000534 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000535 // Create and init a super structure; this is a (receiver, class)
536 // pair we will pass to objc_msgSendSuper.
537 llvm::Value *ObjCSuper =
538 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
539 llvm::Value *ReceiverAsObject =
540 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
541 CGF.Builder.CreateStore(ReceiverAsObject,
542 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000543
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000544 // If this is a class message the metaclass is passed as the target.
545 llvm::Value *Target;
546 if (IsClassMessage) {
547 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
548 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
549 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
550 Target = Super;
551 } else {
552 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
553 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000554 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
555 // and ObjCTypes types.
556 const llvm::Type *ClassTy =
557 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000558 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000559 CGF.Builder.CreateStore(Target,
560 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
561
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000562 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000563 ObjCSuper, ObjCTypes.SuperPtrCTy,
564 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000565}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000566
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000567/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000568CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000569 QualType ResultType,
570 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000571 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000572 bool IsClassMessage,
573 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000574 llvm::Value *Arg0 =
575 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000576 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000577 Arg0, CGF.getContext().getObjCIdType(),
578 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000579}
580
581CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000582 QualType ResultType,
583 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000584 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000585 QualType Arg0Ty,
586 bool IsSuper,
587 const CallArgList &CallArgs) {
588 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000589 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
590 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
591 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000592 CGF.getContext().getObjCSelType()));
593 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000594
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000595 const llvm::FunctionType *FTy =
596 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
597 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000598
599 llvm::Constant *Fn;
600 if (CGM.ReturnTypeUsesSret(ResultType)) {
601 Fn = ObjCTypes.getSendStretFn(IsSuper);
602 } else if (ResultType->isFloatingType()) {
603 // FIXME: Sadly, this is wrong. This actually depends on the
604 // architecture. This happens to be right for x86-32 though.
605 Fn = ObjCTypes.getSendFpretFn(IsSuper);
606 } else {
607 Fn = ObjCTypes.getSendFn(IsSuper);
608 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000609 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000610 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000611}
612
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000613llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000614 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000615 // FIXME: I don't understand why gcc generates this, or where it is
616 // resolved. Investigate. Its also wasteful to look this up over and
617 // over.
618 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
619
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000620 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
621 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000622}
623
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000624void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
625 // FIXME: We shouldn't need this, the protocol decl should contain
626 // enough information to tell us whether this was a declaration or a
627 // definition.
628 DefinedProtocols.insert(PD->getIdentifier());
629
630 // If we have generated a forward reference to this protocol, emit
631 // it now. Otherwise do nothing, the protocol objects are lazily
632 // emitted.
633 if (Protocols.count(PD->getIdentifier()))
634 GetOrEmitProtocol(PD);
635}
636
637llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
638 if (DefinedProtocols.count(PD->getIdentifier()))
639 return GetOrEmitProtocol(PD);
640 return GetOrEmitProtocolRef(PD);
641}
642
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000643/*
644 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
645 struct _objc_protocol {
646 struct _objc_protocol_extension *isa;
647 char *protocol_name;
648 struct _objc_protocol_list *protocol_list;
649 struct _objc__method_prototype_list *instance_methods;
650 struct _objc__method_prototype_list *class_methods
651 };
652
653 See EmitProtocolExtension().
654*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000655llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
656 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
657
658 // Early exit if a defining object has already been generated.
659 if (Entry && Entry->hasInitializer())
660 return Entry;
661
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000662 // FIXME: I don't understand why gcc generates this, or where it is
663 // resolved. Investigate. Its also wasteful to look this up over and
664 // over.
665 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
666
Chris Lattner8ec03f52008-11-24 03:54:41 +0000667 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000668
669 // Construct method lists.
670 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
671 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
672 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
673 e = PD->instmeth_end(); i != e; ++i) {
674 ObjCMethodDecl *MD = *i;
675 llvm::Constant *C = GetMethodDescriptionConstant(MD);
676 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
677 OptInstanceMethods.push_back(C);
678 } else {
679 InstanceMethods.push_back(C);
680 }
681 }
682
683 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
684 e = PD->classmeth_end(); i != e; ++i) {
685 ObjCMethodDecl *MD = *i;
686 llvm::Constant *C = GetMethodDescriptionConstant(MD);
687 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
688 OptClassMethods.push_back(C);
689 } else {
690 ClassMethods.push_back(C);
691 }
692 }
693
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000694 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000695 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000696 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000697 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000698 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +0000699 PD->protocol_begin(),
700 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000701 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000702 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
703 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000704 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
705 InstanceMethods);
706 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000707 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
708 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000709 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
710 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000711 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
712 Values);
713
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000714 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000715 // Already created, fix the linkage and update the initializer.
716 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000717 Entry->setInitializer(Init);
718 } else {
719 Entry =
720 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
721 llvm::GlobalValue::InternalLinkage,
722 Init,
723 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
724 &CGM.getModule());
725 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
726 UsedGlobals.push_back(Entry);
727 // FIXME: Is this necessary? Why only for protocol?
728 Entry->setAlignment(4);
729 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000730
731 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000732}
733
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000734llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000735 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
736
737 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000738 // We use the initializer as a marker of whether this is a forward
739 // reference or not. At module finalization we add the empty
740 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000741 Entry =
742 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000743 llvm::GlobalValue::ExternalLinkage,
744 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000745 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000746 &CGM.getModule());
747 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
748 UsedGlobals.push_back(Entry);
749 // FIXME: Is this necessary? Why only for protocol?
750 Entry->setAlignment(4);
751 }
752
753 return Entry;
754}
755
756/*
757 struct _objc_protocol_extension {
758 uint32_t size;
759 struct objc_method_description_list *optional_instance_methods;
760 struct objc_method_description_list *optional_class_methods;
761 struct objc_property_list *instance_properties;
762 };
763*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000764llvm::Constant *
765CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
766 const ConstantVector &OptInstanceMethods,
767 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000768 uint64_t Size =
769 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
770 std::vector<llvm::Constant*> Values(4);
771 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000772 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000773 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
774 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000775 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
776 OptInstanceMethods);
777 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000778 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
779 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000780 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
781 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000782 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
783 PD->getNameAsString(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000784 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000785 PD->classprop_begin(),
786 PD->classprop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000787
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000788 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000789 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
790 Values[3]->isNullValue())
791 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
792
793 llvm::Constant *Init =
794 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
795 llvm::GlobalVariable *GV =
796 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
797 llvm::GlobalValue::InternalLinkage,
798 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000799 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000800 &CGM.getModule());
801 // No special section, but goes in llvm.used
802 UsedGlobals.push_back(GV);
803
804 return GV;
805}
806
807/*
808 struct objc_protocol_list {
809 struct objc_protocol_list *next;
810 long count;
811 Protocol *list[];
812 };
813*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000814llvm::Constant *
815CGObjCMac::EmitProtocolList(const std::string &Name,
816 ObjCProtocolDecl::protocol_iterator begin,
817 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000818 std::vector<llvm::Constant*> ProtocolRefs;
819
Daniel Dunbardbc933702008-08-21 21:57:41 +0000820 for (; begin != end; ++begin)
821 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000822
823 // Just return null for empty protocol lists
824 if (ProtocolRefs.empty())
825 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
826
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000827 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000828 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
829
830 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000831 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000832 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
833 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
834 Values[2] =
835 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
836 ProtocolRefs.size()),
837 ProtocolRefs);
838
839 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
840 llvm::GlobalVariable *GV =
841 new llvm::GlobalVariable(Init->getType(), false,
842 llvm::GlobalValue::InternalLinkage,
843 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000844 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000845 &CGM.getModule());
846 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
847 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
848}
849
850/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000851 struct _objc_property {
852 const char * const name;
853 const char * const attributes;
854 };
855
856 struct _objc_property_list {
857 uint32_t entsize; // sizeof (struct _objc_property)
858 uint32_t prop_count;
859 struct _objc_property[prop_count];
860 };
861*/
862llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000863 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000864 ObjCPropertyDecl * const *begin,
865 ObjCPropertyDecl * const *end) {
866 std::vector<llvm::Constant*> Properties, Prop(2);
867 for (; begin != end; ++begin) {
868 const ObjCPropertyDecl *PD = *begin;
869 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000870 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000871 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
872 Prop));
873 }
874
875 // Return null for empty list.
876 if (Properties.empty())
877 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
878
879 unsigned PropertySize =
880 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
881 std::vector<llvm::Constant*> Values(3);
882 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
883 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
884 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
885 Properties.size());
886 Values[2] = llvm::ConstantArray::get(AT, Properties);
887 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
888
889 llvm::GlobalVariable *GV =
890 new llvm::GlobalVariable(Init->getType(), false,
891 llvm::GlobalValue::InternalLinkage,
892 Init,
893 Name,
894 &CGM.getModule());
895 // No special section on property lists?
896 UsedGlobals.push_back(GV);
897 return llvm::ConstantExpr::getBitCast(GV,
898 ObjCTypes.PropertyListPtrTy);
899
900}
901
902/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000903 struct objc_method_description_list {
904 int count;
905 struct objc_method_description list[];
906 };
907*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000908llvm::Constant *
909CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
910 std::vector<llvm::Constant*> Desc(2);
911 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
912 ObjCTypes.SelectorPtrTy);
913 Desc[1] = GetMethodVarType(MD);
914 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
915 Desc);
916}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000917
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000918llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
919 const char *Section,
920 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000921 // Return null for empty list.
922 if (Methods.empty())
923 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
924
925 std::vector<llvm::Constant*> Values(2);
926 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
927 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
928 Methods.size());
929 Values[1] = llvm::ConstantArray::get(AT, Methods);
930 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
931
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000932 llvm::GlobalVariable *GV =
933 new llvm::GlobalVariable(Init->getType(), false,
934 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000935 Init, Name, &CGM.getModule());
936 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000937 UsedGlobals.push_back(GV);
938 return llvm::ConstantExpr::getBitCast(GV,
939 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000940}
941
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000942/*
943 struct _objc_category {
944 char *category_name;
945 char *class_name;
946 struct _objc_method_list *instance_methods;
947 struct _objc_method_list *class_methods;
948 struct _objc_protocol_list *protocols;
949 uint32_t size; // <rdar://4585769>
950 struct _objc_property_list *instance_properties;
951 };
952 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000953void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000954 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
955
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000956 // FIXME: This is poor design, the OCD should have a pointer to the
957 // category decl. Additionally, note that Category can be null for
958 // the @implementation w/o an @interface case. Sema should just
959 // create one for us as it does for @implementation so everyone else
960 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000961 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000962 const ObjCCategoryDecl *Category =
963 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000964 std::string ExtName(Interface->getNameAsString() + "_" +
965 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000966
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000967 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
968 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
969 e = OCD->instmeth_end(); i != e; ++i) {
970 // Instance methods should always be defined.
971 InstanceMethods.push_back(GetMethodConstant(*i));
972 }
973 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
974 e = OCD->classmeth_end(); i != e; ++i) {
975 // Class methods should always be defined.
976 ClassMethods.push_back(GetMethodConstant(*i));
977 }
978
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000979 std::vector<llvm::Constant*> Values(7);
980 Values[0] = GetClassName(OCD->getIdentifier());
981 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000982 Values[2] =
983 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
984 ExtName,
985 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000986 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000987 Values[3] =
988 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
989 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000990 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000991 if (Category) {
992 Values[4] =
993 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
994 Category->protocol_begin(),
995 Category->protocol_end());
996 } else {
997 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
998 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000999 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001000
1001 // If there is no category @interface then there can be no properties.
1002 if (Category) {
1003 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001004 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001005 Category->classprop_begin(),
1006 Category->classprop_end());
1007 } else {
1008 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1009 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001010
1011 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1012 Values);
1013
1014 llvm::GlobalVariable *GV =
1015 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1016 llvm::GlobalValue::InternalLinkage,
1017 Init,
1018 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1019 &CGM.getModule());
1020 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1021 UsedGlobals.push_back(GV);
1022 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001023}
1024
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001025// FIXME: Get from somewhere?
1026enum ClassFlags {
1027 eClassFlags_Factory = 0x00001,
1028 eClassFlags_Meta = 0x00002,
1029 // <rdr://5142207>
1030 eClassFlags_HasCXXStructors = 0x02000,
1031 eClassFlags_Hidden = 0x20000,
1032 eClassFlags_ABI2_Hidden = 0x00010,
1033 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1034};
1035
1036// <rdr://5142207&4705298&4843145>
1037static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1038 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1039 // FIXME: Support -fvisibility
1040 switch (attr->getVisibility()) {
1041 default:
1042 assert(0 && "Unknown visibility");
1043 return false;
1044 case VisibilityAttr::DefaultVisibility:
1045 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1046 return false;
1047 case VisibilityAttr::HiddenVisibility:
1048 return true;
1049 }
1050 } else {
1051 return false; // FIXME: Support -fvisibility
1052 }
1053}
1054
1055/*
1056 struct _objc_class {
1057 Class isa;
1058 Class super_class;
1059 const char *name;
1060 long version;
1061 long info;
1062 long instance_size;
1063 struct _objc_ivar_list *ivars;
1064 struct _objc_method_list *methods;
1065 struct _objc_cache *cache;
1066 struct _objc_protocol_list *protocols;
1067 // Objective-C 1.0 extensions (<rdr://4585769>)
1068 const char *ivar_layout;
1069 struct _objc_class_ext *ext;
1070 };
1071
1072 See EmitClassExtension();
1073 */
1074void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001075 DefinedSymbols.insert(ID->getIdentifier());
1076
Chris Lattner8ec03f52008-11-24 03:54:41 +00001077 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001078 // FIXME: Gross
1079 ObjCInterfaceDecl *Interface =
1080 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001081 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001082 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001083 Interface->protocol_begin(),
1084 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001085 const llvm::Type *InterfaceTy =
1086 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1087 unsigned Flags = eClassFlags_Factory;
1088 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1089
1090 // FIXME: Set CXX-structors flag.
1091 if (IsClassHidden(ID->getClassInterface()))
1092 Flags |= eClassFlags_Hidden;
1093
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001094 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1095 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1096 e = ID->instmeth_end(); i != e; ++i) {
1097 // Instance methods should always be defined.
1098 InstanceMethods.push_back(GetMethodConstant(*i));
1099 }
1100 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1101 e = ID->classmeth_end(); i != e; ++i) {
1102 // Class methods should always be defined.
1103 ClassMethods.push_back(GetMethodConstant(*i));
1104 }
1105
1106 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1107 e = ID->propimpl_end(); i != e; ++i) {
1108 ObjCPropertyImplDecl *PID = *i;
1109
1110 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1111 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1112
1113 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1114 if (llvm::Constant *C = GetMethodConstant(MD))
1115 InstanceMethods.push_back(C);
1116 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1117 if (llvm::Constant *C = GetMethodConstant(MD))
1118 InstanceMethods.push_back(C);
1119 }
1120 }
1121
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001122 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001123 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001124 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001125 // Record a reference to the super class.
1126 LazySymbols.insert(Super->getIdentifier());
1127
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001128 Values[ 1] =
1129 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1130 ObjCTypes.ClassPtrTy);
1131 } else {
1132 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1133 }
1134 Values[ 2] = GetClassName(ID->getIdentifier());
1135 // Version is always 0.
1136 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1137 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1138 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1139 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001140 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001141 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001142 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001143 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001144 // cache is always NULL.
1145 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1146 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001147 // FIXME: Set ivar_layout
1148 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001149 Values[11] = EmitClassExtension(ID);
1150 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1151 Values);
1152
1153 llvm::GlobalVariable *GV =
1154 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1155 llvm::GlobalValue::InternalLinkage,
1156 Init,
1157 std::string("\01L_OBJC_CLASS_")+ClassName,
1158 &CGM.getModule());
1159 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1160 UsedGlobals.push_back(GV);
1161 // FIXME: Why?
1162 GV->setAlignment(32);
1163 DefinedClasses.push_back(GV);
1164}
1165
1166llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1167 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001168 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001169 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001170 unsigned Flags = eClassFlags_Meta;
1171 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1172
1173 if (IsClassHidden(ID->getClassInterface()))
1174 Flags |= eClassFlags_Hidden;
1175
1176 std::vector<llvm::Constant*> Values(12);
1177 // The isa for the metaclass is the root of the hierarchy.
1178 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1179 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1180 Root = Super;
1181 Values[ 0] =
1182 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1183 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001184 // The super class for the metaclass is emitted as the name of the
1185 // super class. The runtime fixes this up to point to the
1186 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001187 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1188 Values[ 1] =
1189 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1190 ObjCTypes.ClassPtrTy);
1191 } else {
1192 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1193 }
1194 Values[ 2] = GetClassName(ID->getIdentifier());
1195 // Version is always 0.
1196 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1197 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1198 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1199 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001200 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001201 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001202 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001203 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001204 // cache is always NULL.
1205 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1206 Values[ 9] = Protocols;
1207 // ivar_layout for metaclass is always NULL.
1208 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1209 // The class extension is always unused for metaclasses.
1210 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1211 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1212 Values);
1213
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001214 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001215 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001216
1217 // Check for a forward reference.
1218 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1219 if (GV) {
1220 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1221 "Forward metaclass reference has incorrect type.");
1222 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1223 GV->setInitializer(Init);
1224 } else {
1225 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1226 llvm::GlobalValue::InternalLinkage,
1227 Init, Name,
1228 &CGM.getModule());
1229 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001230 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1231 UsedGlobals.push_back(GV);
1232 // FIXME: Why?
1233 GV->setAlignment(32);
1234
1235 return GV;
1236}
1237
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001238llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001239 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001240
1241 // FIXME: Should we look these up somewhere other than the
1242 // module. Its a bit silly since we only generate these while
1243 // processing an implementation, so exactly one pointer would work
1244 // if know when we entered/exitted an implementation block.
1245
1246 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001247 // Previously, metaclass with internal linkage may have been defined.
1248 // pass 'true' as 2nd argument so it is returned.
1249 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001250 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1251 "Forward metaclass reference has incorrect type.");
1252 return GV;
1253 } else {
1254 // Generate as an external reference to keep a consistent
1255 // module. This will be patched up when we emit the metaclass.
1256 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1257 llvm::GlobalValue::ExternalLinkage,
1258 0,
1259 Name,
1260 &CGM.getModule());
1261 }
1262}
1263
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001264/*
1265 struct objc_class_ext {
1266 uint32_t size;
1267 const char *weak_ivar_layout;
1268 struct _objc_property_list *properties;
1269 };
1270*/
1271llvm::Constant *
1272CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1273 uint64_t Size =
1274 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1275
1276 std::vector<llvm::Constant*> Values(3);
1277 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001278 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001279 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001280 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001281 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001282 ID->getClassInterface()->classprop_begin(),
1283 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001284
1285 // Return null if no extension bits are used.
1286 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1287 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1288
1289 llvm::Constant *Init =
1290 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1291 llvm::GlobalVariable *GV =
1292 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1293 llvm::GlobalValue::InternalLinkage,
1294 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001295 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001296 &CGM.getModule());
1297 // No special section, but goes in llvm.used
1298 UsedGlobals.push_back(GV);
1299
1300 return GV;
1301}
1302
1303/*
1304 struct objc_ivar {
1305 char *ivar_name;
1306 char *ivar_type;
1307 int ivar_offset;
1308 };
1309
1310 struct objc_ivar_list {
1311 int ivar_count;
1312 struct objc_ivar list[count];
1313 };
1314 */
1315llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1316 bool ForClass,
1317 const llvm::Type *InterfaceTy) {
1318 std::vector<llvm::Constant*> Ivars, Ivar(3);
1319
1320 // When emitting the root class GCC emits ivar entries for the
1321 // actual class structure. It is not clear if we need to follow this
1322 // behavior; for now lets try and get away with not doing it. If so,
1323 // the cleanest solution would be to make up an ObjCInterfaceDecl
1324 // for the class.
1325 if (ForClass)
1326 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1327
1328 const llvm::StructLayout *Layout =
1329 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1330 for (ObjCInterfaceDecl::ivar_iterator
1331 i = ID->getClassInterface()->ivar_begin(),
1332 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +00001333 const ObjCIvarDecl *V = *i;
1334 ObjCInterfaceDecl *OID =
1335 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1336 FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), V);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001337 unsigned Offset =
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +00001338 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001339 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001340 Ivar[0] = GetMethodVarName(V->getIdentifier());
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00001341 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001342 Ivar[1] = GetMethodVarType(TypeStr);
1343 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001344 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001345 }
1346
1347 // Return null for empty list.
1348 if (Ivars.empty())
1349 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1350
1351 std::vector<llvm::Constant*> Values(2);
1352 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1353 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1354 Ivars.size());
1355 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1356 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1357
1358 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1359 "\01L_OBJC_INSTANCE_VARIABLES_");
1360 llvm::GlobalVariable *GV =
1361 new llvm::GlobalVariable(Init->getType(), false,
1362 llvm::GlobalValue::InternalLinkage,
1363 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001364 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001365 &CGM.getModule());
1366 if (ForClass) {
1367 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1368 // FIXME: Why is this only here?
1369 GV->setAlignment(32);
1370 } else {
1371 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1372 }
1373 UsedGlobals.push_back(GV);
1374 return llvm::ConstantExpr::getBitCast(GV,
1375 ObjCTypes.IvarListPtrTy);
1376}
1377
1378/*
1379 struct objc_method {
1380 SEL method_name;
1381 char *method_types;
1382 void *method;
1383 };
1384
1385 struct objc_method_list {
1386 struct objc_method_list *obsolete;
1387 int count;
1388 struct objc_method methods_list[count];
1389 };
1390*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001391
1392/// GetMethodConstant - Return a struct objc_method constant for the
1393/// given method if it has been defined. The result is null if the
1394/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001395llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001396 // FIXME: Use DenseMap::lookup
1397 llvm::Function *Fn = MethodDefinitions[MD];
1398 if (!Fn)
1399 return 0;
1400
1401 std::vector<llvm::Constant*> Method(3);
1402 Method[0] =
1403 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1404 ObjCTypes.SelectorPtrTy);
1405 Method[1] = GetMethodVarType(MD);
1406 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1407 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1408}
1409
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001410llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1411 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001412 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001413 // Return null for empty list.
1414 if (Methods.empty())
1415 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1416
1417 std::vector<llvm::Constant*> Values(3);
1418 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1419 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1420 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1421 Methods.size());
1422 Values[2] = llvm::ConstantArray::get(AT, Methods);
1423 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1424
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001425 llvm::GlobalVariable *GV =
1426 new llvm::GlobalVariable(Init->getType(), false,
1427 llvm::GlobalValue::InternalLinkage,
1428 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001429 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001430 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001431 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001432 UsedGlobals.push_back(GV);
1433 return llvm::ConstantExpr::getBitCast(GV,
1434 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001435}
1436
1437llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001438 std::string Name;
1439 GetNameForMethod(OMD, Name);
1440
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001441 const llvm::FunctionType *MethodTy =
1442 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001443 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001444 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001445 llvm::GlobalValue::InternalLinkage,
1446 Name,
1447 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001448 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001449
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001450 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001451}
1452
1453llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001454 // Abuse this interface function as a place to finalize.
1455 FinishModule();
1456
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001457 return NULL;
1458}
1459
Daniel Dunbar49f66022008-09-24 03:38:44 +00001460llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1461 return ObjCTypes.GetPropertyFn;
1462}
1463
1464llvm::Function *CGObjCMac::GetPropertySetFunction() {
1465 return ObjCTypes.SetPropertyFn;
1466}
1467
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001468llvm::Function *CGObjCMac::EnumerationMutationFunction()
1469{
1470 return ObjCTypes.EnumerationMutationFn;
1471}
1472
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001473/*
1474
1475Objective-C setjmp-longjmp (sjlj) Exception Handling
1476--
1477
1478The basic framework for a @try-catch-finally is as follows:
1479{
1480 objc_exception_data d;
1481 id _rethrow = null;
1482
1483 objc_exception_try_enter(&d);
1484 if (!setjmp(d.jmp_buf)) {
1485 ... try body ...
1486 } else {
1487 // exception path
1488 id _caught = objc_exception_extract(&d);
1489
1490 // enter new try scope for handlers
1491 if (!setjmp(d.jmp_buf)) {
1492 ... match exception and execute catch blocks ...
1493
1494 // fell off end, rethrow.
1495 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001496 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001497 } else {
1498 // exception in catch block
1499 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001500 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001501 }
1502 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001503 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001504
1505finally:
1506 // match either the initial try_enter or the catch try_enter,
1507 // depending on the path followed.
1508 objc_exception_try_exit(&d);
1509finally_no_exit:
1510 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001511 ... dispatch to finally destination ...
1512
1513finally_rethrow:
1514 objc_exception_throw(_rethrow);
1515
1516finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001517}
1518
1519This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001520uses _rethrow to determine if objc_exception_try_exit should be called
1521and if the object should be rethrown. This breaks in the face of
1522throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001523
1524We specialize this framework for a few particular circumstances:
1525
1526 - If there are no catch blocks, then we avoid emitting the second
1527 exception handling context.
1528
1529 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1530 e)) we avoid emitting the code to rethrow an uncaught exception.
1531
1532 - FIXME: If there is no @finally block we can do a few more
1533 simplifications.
1534
1535Rethrows and Jumps-Through-Finally
1536--
1537
1538Support for implicit rethrows and jumping through the finally block is
1539handled by storing the current exception-handling context in
1540ObjCEHStack.
1541
Daniel Dunbar898d5082008-09-30 01:06:03 +00001542In order to implement proper @finally semantics, we support one basic
1543mechanism for jumping through the finally block to an arbitrary
1544destination. Constructs which generate exits from a @try or @catch
1545block use this mechanism to implement the proper semantics by chaining
1546jumps, as necessary.
1547
1548This mechanism works like the one used for indirect goto: we
1549arbitrarily assign an ID to each destination and store the ID for the
1550destination in a variable prior to entering the finally block. At the
1551end of the finally block we simply create a switch to the proper
1552destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001553
1554Code gen for @synchronized(expr) stmt;
1555Effectively generating code for:
1556objc_sync_enter(expr);
1557@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001558*/
1559
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001560void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1561 const Stmt &S) {
1562 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001563 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001564 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1565 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1566 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1567 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001568 llvm::Value *DestCode =
1569 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1570
1571 // Generate jump code. Done here so we can directly add things to
1572 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001573 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001574 llvm::SwitchInst *FinallySwitch =
1575 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1576 FinallyEnd, 10, FinallyJump);
1577
1578 // Push an EH context entry, used for handling rethrows and jumps
1579 // through finally.
1580 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1581 FinallySwitch, DestCode);
1582 CGF.ObjCEHStack.push_back(&EHEntry);
1583
1584 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001585 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1586 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001587 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1588 "_rethrow");
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001589 if (!isTry) {
1590 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001591 llvm::Value *Arg = CGF.EmitScalarExpr(
1592 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1593 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1594 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001595 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001596
1597 // Enter a new try block and call setjmp.
1598 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1599 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1600 "jmpbufarray");
1601 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1602 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1603 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001604
Daniel Dunbar55e87422008-11-11 02:29:29 +00001605 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1606 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001607 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001608 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001609
1610 // Emit the @try block.
1611 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001612 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1613 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001614 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001615
1616 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001617 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001618
1619 // Retrieve the exception object. We may emit multiple blocks but
1620 // nothing can cross this so the value is already in SSA form.
1621 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1622 ExceptionData,
1623 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001624 EHEntry.Exception = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001625 if (!isTry)
1626 {
1627 CGF.Builder.CreateStore(Caught, RethrowPtr);
1628 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1629 }
1630 else if (const ObjCAtCatchStmt* CatchStmt =
1631 cast<ObjCAtTryStmt>(S).getCatchStmts())
1632 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001633 // Enter a new exception try block (in case a @catch block throws
1634 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001635 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001636
Anders Carlsson80f25672008-09-09 17:59:25 +00001637 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1638 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001639 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001640
Daniel Dunbar55e87422008-11-11 02:29:29 +00001641 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1642 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001643 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001644
1645 CGF.EmitBlock(CatchBlock);
1646
Daniel Dunbar55e40722008-09-27 07:03:52 +00001647 // Handle catch list. As a special case we check if everything is
1648 // matched and avoid generating code for falling off the end if
1649 // so.
1650 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001651 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001652 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001653
Anders Carlssondde0a942008-09-11 09:15:33 +00001654 const DeclStmt *CatchParam =
1655 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001656 const VarDecl *VD = 0;
1657 const PointerType *PT = 0;
1658
Anders Carlsson80f25672008-09-09 17:59:25 +00001659 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001660 if (!CatchParam) {
1661 AllMatched = true;
1662 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001663 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001664 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001665
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001666 // catch(id e) always matches.
1667 // FIXME: For the time being we also match id<X>; this should
1668 // be rejected by Sema instead.
1669 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1670 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001671 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001672 }
1673
Daniel Dunbar55e40722008-09-27 07:03:52 +00001674 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001675 if (CatchParam) {
1676 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001677 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001678 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001679 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001680
Anders Carlssondde0a942008-09-11 09:15:33 +00001681 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001682 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001683 break;
1684 }
1685
Daniel Dunbar129271a2008-09-27 07:36:24 +00001686 assert(PT && "Unexpected non-pointer type in @catch");
1687 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001688 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001689 assert(ObjCType && "Catch parameter must have Objective-C type!");
1690
1691 // Check if the @catch block matches the exception object.
1692 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1693
Anders Carlsson80f25672008-09-09 17:59:25 +00001694 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1695 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001696
Daniel Dunbar55e87422008-11-11 02:29:29 +00001697 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001698
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001699 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001700 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001701
1702 // Emit the @catch block.
1703 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001704 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001705 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001706
1707 llvm::Value *Tmp =
1708 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1709 "tmp");
1710 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001711
1712 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001713 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001714
1715 CGF.EmitBlock(NextCatchBlock);
1716 }
1717
Daniel Dunbar55e40722008-09-27 07:03:52 +00001718 if (!AllMatched) {
1719 // None of the handlers caught the exception, so store it to be
1720 // rethrown at the end of the @finally block.
1721 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001722 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001723 }
1724
1725 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001726 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001727 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1728 ExceptionData),
1729 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001730 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001731 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001732 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001733 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001734 }
1735
Daniel Dunbar898d5082008-09-30 01:06:03 +00001736 // Pop the exception-handling stack entry. It is important to do
1737 // this now, because the code in the @finally block is not in this
1738 // context.
1739 CGF.ObjCEHStack.pop_back();
1740
Anders Carlsson80f25672008-09-09 17:59:25 +00001741 // Emit the @finally block.
1742 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001743 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001744
1745 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001746 if (isTry) {
1747 if (const ObjCAtFinallyStmt* FinallyStmt =
1748 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1749 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1750 }
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001751 else {
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001752 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001753 // For @synchronized, call objc_sync_enter(sync.expr)
1754 llvm::Value *Arg = CGF.EmitScalarExpr(
1755 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1756 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1757 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1758 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001759
Daniel Dunbar898d5082008-09-30 01:06:03 +00001760 CGF.EmitBlock(FinallyJump);
1761
1762 CGF.EmitBlock(FinallyRethrow);
1763 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1764 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001765 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001766
1767 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001768}
1769
1770void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001771 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001772 llvm::Value *ExceptionAsObject;
1773
1774 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1775 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1776 ExceptionAsObject =
1777 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1778 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001779 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001780 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001781 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001782 }
1783
1784 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001785 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001786
1787 // Clear the insertion point to indicate we are in unreachable code.
1788 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001789}
1790
Daniel Dunbar898d5082008-09-30 01:06:03 +00001791void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1792 llvm::BasicBlock *Dst,
1793 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001794 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001795 return;
1796
1797 // Find the destination code for this block. We always use 0 for the
1798 // fallthrough block (default destination).
1799 llvm::SwitchInst *SI = E->FinallySwitch;
1800 llvm::ConstantInt *ID;
1801 if (Dst == SI->getDefaultDest()) {
1802 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1803 } else {
1804 ID = SI->findCaseDest(Dst);
1805 if (!ID) {
1806 // No code found, get a new unique one by just using the number
1807 // of switch successors.
1808 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1809 SI->addCase(ID, Dst);
1810 }
1811 }
1812
1813 // Set the destination code and branch.
1814 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001815 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001816}
1817
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001818/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001819/// object: objc_read_weak (id *src)
1820///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001821llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001822 llvm::Value *AddrWeakObj)
1823{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001824 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001825 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001826 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001827 return read_weak;
1828}
1829
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001830/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1831/// objc_assign_weak (id src, id *dst)
1832///
1833void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1834 llvm::Value *src, llvm::Value *dst)
1835{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001836 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1837 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001838 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1839 src, dst, "weakassign");
1840 return;
1841}
1842
Fariborz Jahanian58626502008-11-19 00:59:10 +00001843/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1844/// objc_assign_global (id src, id *dst)
1845///
1846void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1847 llvm::Value *src, llvm::Value *dst)
1848{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001849 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1850 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001851 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1852 src, dst, "globalassign");
1853 return;
1854}
1855
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001856/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1857/// objc_assign_ivar (id src, id *dst)
1858///
1859void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1860 llvm::Value *src, llvm::Value *dst)
1861{
1862 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1863 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1864 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1865 src, dst, "assignivar");
1866 return;
1867}
1868
Fariborz Jahanian58626502008-11-19 00:59:10 +00001869/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1870/// objc_assign_strongCast (id src, id *dst)
1871///
1872void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1873 llvm::Value *src, llvm::Value *dst)
1874{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001875 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1876 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001877 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1878 src, dst, "weakassign");
1879 return;
1880}
1881
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001882/* *** Private Interface *** */
1883
1884/// EmitImageInfo - Emit the image info marker used to encode some module
1885/// level information.
1886///
1887/// See: <rdr://4810609&4810587&4810587>
1888/// struct IMAGE_INFO {
1889/// unsigned version;
1890/// unsigned flags;
1891/// };
1892enum ImageInfoFlags {
1893 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1894 eImageInfo_GarbageCollected = (1 << 1),
1895 eImageInfo_GCOnly = (1 << 2)
1896};
1897
1898void CGObjCMac::EmitImageInfo() {
1899 unsigned version = 0; // Version is unused?
1900 unsigned flags = 0;
1901
1902 // FIXME: Fix and continue?
1903 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1904 flags |= eImageInfo_GarbageCollected;
1905 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1906 flags |= eImageInfo_GCOnly;
1907
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001908 // Emitted as int[2];
1909 llvm::Constant *values[2] = {
1910 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1911 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1912 };
1913 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001914 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001915 new llvm::GlobalVariable(AT, true,
1916 llvm::GlobalValue::InternalLinkage,
1917 llvm::ConstantArray::get(AT, values, 2),
1918 "\01L_OBJC_IMAGE_INFO",
1919 &CGM.getModule());
1920
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001921 if (ObjCABI == 1) {
1922 GV->setSection("__OBJC, __image_info,regular");
1923 } else {
1924 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1925 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001926
1927 UsedGlobals.push_back(GV);
1928}
1929
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001930
1931// struct objc_module {
1932// unsigned long version;
1933// unsigned long size;
1934// const char *name;
1935// Symtab symtab;
1936// };
1937
1938// FIXME: Get from somewhere
1939static const int ModuleVersion = 7;
1940
1941void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001942 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1943
1944 std::vector<llvm::Constant*> Values(4);
1945 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1946 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001947 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001948 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001949 Values[3] = EmitModuleSymbols();
1950
1951 llvm::GlobalVariable *GV =
1952 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1953 llvm::GlobalValue::InternalLinkage,
1954 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1955 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001956 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001957 &CGM.getModule());
1958 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1959 UsedGlobals.push_back(GV);
1960}
1961
1962llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001963 unsigned NumClasses = DefinedClasses.size();
1964 unsigned NumCategories = DefinedCategories.size();
1965
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001966 // Return null if no symbols were defined.
1967 if (!NumClasses && !NumCategories)
1968 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1969
1970 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001971 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1972 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1973 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1974 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1975
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001976 // The runtime expects exactly the list of defined classes followed
1977 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001978 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001979 for (unsigned i=0; i<NumClasses; i++)
1980 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1981 ObjCTypes.Int8PtrTy);
1982 for (unsigned i=0; i<NumCategories; i++)
1983 Symbols[NumClasses + i] =
1984 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1985 ObjCTypes.Int8PtrTy);
1986
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001987 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001988 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001989 NumClasses + NumCategories),
1990 Symbols);
1991
1992 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1993
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001994 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001995 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001996 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001997 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001998 "\01L_OBJC_SYMBOLS",
1999 &CGM.getModule());
2000 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2001 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002002 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2003}
2004
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002005llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002006 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002007 LazySymbols.insert(ID->getIdentifier());
2008
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002009 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2010
2011 if (!Entry) {
2012 llvm::Constant *Casted =
2013 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2014 ObjCTypes.ClassPtrTy);
2015 Entry =
2016 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2017 llvm::GlobalValue::InternalLinkage,
2018 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2019 &CGM.getModule());
2020 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2021 UsedGlobals.push_back(Entry);
2022 }
2023
2024 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002025}
2026
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002027llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002028 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2029
2030 if (!Entry) {
2031 llvm::Constant *Casted =
2032 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2033 ObjCTypes.SelectorPtrTy);
2034 Entry =
2035 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2036 llvm::GlobalValue::InternalLinkage,
2037 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2038 &CGM.getModule());
2039 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2040 UsedGlobals.push_back(Entry);
2041 }
2042
2043 return Builder.CreateLoad(Entry, false, "tmp");
2044}
2045
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002046llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2047 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002048
2049 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002050 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002051 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002052 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002053 llvm::GlobalValue::InternalLinkage,
2054 C, "\01L_OBJC_CLASS_NAME_",
2055 &CGM.getModule());
2056 Entry->setSection("__TEXT,__cstring,cstring_literals");
2057 UsedGlobals.push_back(Entry);
2058 }
2059
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002060 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002061}
2062
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002063llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2064 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2065
2066 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002067 // FIXME: Avoid std::string copying.
2068 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002069 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002070 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002071 llvm::GlobalValue::InternalLinkage,
2072 C, "\01L_OBJC_METH_VAR_NAME_",
2073 &CGM.getModule());
2074 Entry->setSection("__TEXT,__cstring,cstring_literals");
2075 UsedGlobals.push_back(Entry);
2076 }
2077
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002078 return getConstantGEP(Entry, 0, 0);
2079}
2080
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002081// FIXME: Merge into a single cstring creation function.
2082llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2083 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2084}
2085
2086// FIXME: Merge into a single cstring creation function.
2087llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2088 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2089}
2090
2091llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2092 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002093
2094 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002095 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002096 Entry =
2097 new llvm::GlobalVariable(C->getType(), false,
2098 llvm::GlobalValue::InternalLinkage,
2099 C, "\01L_OBJC_METH_VAR_TYPE_",
2100 &CGM.getModule());
2101 Entry->setSection("__TEXT,__cstring,cstring_literals");
2102 UsedGlobals.push_back(Entry);
2103 }
2104
2105 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002106}
2107
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002108// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002109llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002110 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002111 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2112 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002113 return GetMethodVarType(TypeStr);
2114}
2115
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002116// FIXME: Merge into a single cstring creation function.
2117llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2118 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2119
2120 if (!Entry) {
2121 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2122 Entry =
2123 new llvm::GlobalVariable(C->getType(), false,
2124 llvm::GlobalValue::InternalLinkage,
2125 C, "\01L_OBJC_PROP_NAME_ATTR_",
2126 &CGM.getModule());
2127 Entry->setSection("__TEXT,__cstring,cstring_literals");
2128 UsedGlobals.push_back(Entry);
2129 }
2130
2131 return getConstantGEP(Entry, 0, 0);
2132}
2133
2134// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002135// FIXME: This Decl should be more precise.
2136llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2137 const Decl *Container) {
2138 std::string TypeStr;
2139 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002140 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2141}
2142
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002143void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2144 std::string &NameOut) {
2145 // FIXME: Find the mangling GCC uses.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002146 NameOut = (D->isInstance() ? "-" : "+");
2147 NameOut += '[';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002148 NameOut += D->getClassInterface()->getNameAsString();
Chris Lattner077bf5e2008-11-24 03:33:13 +00002149 NameOut += ' ';
2150 NameOut += D->getSelector().getAsString();
2151 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002152}
2153
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002154void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002155 EmitModuleInfo();
2156
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002157 // Emit the dummy bodies for any protocols which were referenced but
2158 // never defined.
2159 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2160 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2161 if (i->second->hasInitializer())
2162 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002163
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002164 std::vector<llvm::Constant*> Values(5);
2165 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2166 Values[1] = GetClassName(i->first);
2167 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2168 Values[3] = Values[4] =
2169 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2170 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2171 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2172 Values));
2173 }
2174
2175 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002176 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002177 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002178 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002179 }
2180
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002181 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002182 llvm::GlobalValue *GV =
2183 new llvm::GlobalVariable(AT, false,
2184 llvm::GlobalValue::AppendingLinkage,
2185 llvm::ConstantArray::get(AT, Used),
2186 "llvm.used",
2187 &CGM.getModule());
2188
2189 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002190
2191 // Add assembler directives to add lazy undefined symbol references
2192 // for classes which are referenced but not defined. This is
2193 // important for correct linker interaction.
2194
2195 // FIXME: Uh, this isn't particularly portable.
2196 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002197
2198 if (!CGM.getModule().getModuleInlineAsm().empty())
2199 s << "\n";
2200
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002201 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2202 e = LazySymbols.end(); i != e; ++i) {
2203 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2204 }
2205 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2206 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002207 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002208 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2209 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002210
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002211 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002212}
2213
2214/* *** */
2215
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002216ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002217 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002218{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002219 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2220 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002221
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002222 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002223 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002224 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002225 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2226
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002227 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002228 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002229 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002230
2231 // FIXME: It would be nice to unify this with the opaque type, so
2232 // that the IR comes out a bit cleaner.
2233 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2234 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002235
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002236 MethodDescriptionTy =
2237 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002238 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002239 NULL);
2240 CGM.getModule().addTypeName("struct._objc_method_description",
2241 MethodDescriptionTy);
2242
2243 MethodDescriptionListTy =
2244 llvm::StructType::get(IntTy,
2245 llvm::ArrayType::get(MethodDescriptionTy, 0),
2246 NULL);
2247 CGM.getModule().addTypeName("struct._objc_method_description_list",
2248 MethodDescriptionListTy);
2249 MethodDescriptionListPtrTy =
2250 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2251
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002252 PropertyTy = llvm::StructType::get(Int8PtrTy,
2253 Int8PtrTy,
2254 NULL);
2255 CGM.getModule().addTypeName("struct._objc_property",
2256 PropertyTy);
2257
2258 PropertyListTy = llvm::StructType::get(IntTy,
2259 IntTy,
2260 llvm::ArrayType::get(PropertyTy, 0),
2261 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002262 CGM.getModule().addTypeName("struct._objc_property_list",
2263 PropertyListTy);
2264 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2265
2266 // Protocol description structures
2267
2268 ProtocolExtensionTy =
2269 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2270 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2271 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2272 PropertyListPtrTy,
2273 NULL);
2274 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2275 ProtocolExtensionTy);
2276 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2277
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002278 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002279
2280 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2281 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2282
2283 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2284 LongTy,
2285 llvm::ArrayType::get(ProtocolTyHolder, 0),
2286 NULL);
2287 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2288
2289 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002290 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002291 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2292 MethodDescriptionListPtrTy,
2293 MethodDescriptionListPtrTy,
2294 NULL);
2295 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2296
2297 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2298 CGM.getModule().addTypeName("struct._objc_protocol_list",
2299 ProtocolListTy);
2300 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2301
2302 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2303 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2304 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002305
2306 // Class description structures
2307
2308 IvarTy = llvm::StructType::get(Int8PtrTy,
2309 Int8PtrTy,
2310 IntTy,
2311 NULL);
2312 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2313
2314 IvarListTy = llvm::OpaqueType::get();
2315 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2316 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2317
2318 MethodTy = llvm::StructType::get(SelectorPtrTy,
2319 Int8PtrTy,
2320 Int8PtrTy,
2321 NULL);
2322 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2323
2324 MethodListTy = llvm::OpaqueType::get();
2325 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2326 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2327
2328 CacheTy = llvm::OpaqueType::get();
2329 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2330 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2331
2332 ClassExtensionTy =
2333 llvm::StructType::get(IntTy,
2334 Int8PtrTy,
2335 PropertyListPtrTy,
2336 NULL);
2337 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2338 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2339
2340 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2341
2342 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2343 llvm::PointerType::getUnqual(ClassTyHolder),
2344 Int8PtrTy,
2345 LongTy,
2346 LongTy,
2347 LongTy,
2348 IvarListPtrTy,
2349 MethodListPtrTy,
2350 CachePtrTy,
2351 ProtocolListPtrTy,
2352 Int8PtrTy,
2353 ClassExtensionPtrTy,
2354 NULL);
2355 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2356
2357 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2358 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2359 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2360
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002361 CategoryTy = llvm::StructType::get(Int8PtrTy,
2362 Int8PtrTy,
2363 MethodListPtrTy,
2364 MethodListPtrTy,
2365 ProtocolListPtrTy,
2366 IntTy,
2367 PropertyListPtrTy,
2368 NULL);
2369 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2370
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002371 // I'm not sure I like this. The implicit coordination is a bit
2372 // gross. We should solve this in a reasonable fashion because this
2373 // is a pretty common task (match some runtime data structure with
2374 // an LLVM data structure).
2375
2376 // FIXME: This is leaked.
2377 // FIXME: Merge with rewriter code?
2378 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2379 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002380 &Ctx.Idents.get("_objc_super"));
Douglas Gregor44b43212008-12-11 16:49:14 +00002381 RD->addDecl(Ctx,
2382 FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2383 Ctx.getObjCIdType(), 0, false, 0),
2384 true);
2385 RD->addDecl(Ctx,
2386 FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2387 Ctx.getObjCClassType(), 0, false, 0),
2388 true);
2389 RD->completeDefinition(Ctx);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002390
2391 SuperCTy = Ctx.getTagDeclType(RD);
2392 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2393
2394 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002395 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002396
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002397 // Global metadata structures
2398
2399 SymtabTy = llvm::StructType::get(LongTy,
2400 SelectorPtrTy,
2401 ShortTy,
2402 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002403 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002404 NULL);
2405 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2406 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2407
2408 ModuleTy =
2409 llvm::StructType::get(LongTy,
2410 LongTy,
2411 Int8PtrTy,
2412 SymtabPtrTy,
2413 NULL);
2414 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002415
Daniel Dunbar49f66022008-09-24 03:38:44 +00002416 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002417
2418 std::vector<const llvm::Type*> Params;
2419 Params.push_back(ObjectPtrTy);
2420 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002421 MessageSendFn =
2422 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2423 Params,
2424 true),
2425 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002426
2427 Params.clear();
2428 Params.push_back(Int8PtrTy);
2429 Params.push_back(ObjectPtrTy);
2430 Params.push_back(SelectorPtrTy);
2431 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002432 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2433 Params,
2434 true),
2435 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002436
2437 Params.clear();
2438 Params.push_back(ObjectPtrTy);
2439 Params.push_back(SelectorPtrTy);
2440 // FIXME: This should be long double on x86_64?
2441 MessageSendFpretFn =
2442 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2443 Params,
2444 true),
2445 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002446
2447 Params.clear();
2448 Params.push_back(SuperPtrTy);
2449 Params.push_back(SelectorPtrTy);
2450 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002451 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2452 Params,
2453 true),
2454 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002455
2456 Params.clear();
2457 Params.push_back(Int8PtrTy);
2458 Params.push_back(SuperPtrTy);
2459 Params.push_back(SelectorPtrTy);
2460 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002461 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2462 Params,
2463 true),
2464 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002465
2466 // There is no objc_msgSendSuper_fpret? How can that work?
2467 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002468
Daniel Dunbar49f66022008-09-24 03:38:44 +00002469 // Property manipulation functions.
2470
2471 Params.clear();
2472 Params.push_back(ObjectPtrTy);
2473 Params.push_back(SelectorPtrTy);
2474 Params.push_back(LongTy);
2475 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2476 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002477 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2478 Params,
2479 false),
2480 "objc_getProperty");
2481
Daniel Dunbar49f66022008-09-24 03:38:44 +00002482 Params.clear();
2483 Params.push_back(ObjectPtrTy);
2484 Params.push_back(SelectorPtrTy);
2485 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002486 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002487 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2488 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2489 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002490 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2491 Params,
2492 false),
2493 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002494
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002495 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002496
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002497 Params.clear();
2498 Params.push_back(ObjectPtrTy);
2499 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002500 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2501 Params,
2502 false),
2503 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002504
2505 // FIXME: This is the size of the setjmp buffer and should be
2506 // target specific. 18 is what's used on 32-bit X86.
2507 uint64_t SetJmpBufferSize = 18;
2508
2509 // Exceptions
2510 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002511 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002512
2513 ExceptionDataTy =
2514 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2515 SetJmpBufferSize),
2516 StackPtrTy, NULL);
2517 CGM.getModule().addTypeName("struct._objc_exception_data",
2518 ExceptionDataTy);
2519
2520 Params.clear();
2521 Params.push_back(ObjectPtrTy);
2522 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002523 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2524 Params,
2525 false),
2526 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002527
2528 Params.clear();
2529 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2530 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002531 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2532 Params,
2533 false),
2534 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002535 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2537 Params,
2538 false),
2539 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002540 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002541 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2542 Params,
2543 false),
2544 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002545
2546 Params.clear();
2547 Params.push_back(ClassPtrTy);
2548 Params.push_back(ObjectPtrTy);
2549 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002550 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2551 Params,
2552 false),
2553 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002554
2555 // synchronized APIs
2556 // void objc_sync_enter (id)
2557 Params.clear();
2558 Params.push_back(ObjectPtrTy);
2559 SyncEnterFn =
2560 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2561 Params,
2562 false),
2563 "objc_sync_enter");
2564 // void objc_sync_exit (id)
2565 SyncExitFn =
2566 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2567 Params,
2568 false),
2569 "objc_sync_exit");
2570
Anders Carlsson124526b2008-09-09 10:10:21 +00002571
2572 Params.clear();
2573 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2574 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002575 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2576 Params,
2577 false),
2578 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002579
2580 // gc's API
2581 // id objc_read_weak (id *)
2582 Params.clear();
2583 Params.push_back(PtrObjectPtrTy);
2584 GcReadWeakFn =
2585 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2586 Params,
2587 false),
2588 "objc_read_weak");
2589 // id objc_assign_weak (id, id *)
2590 Params.clear();
2591 Params.push_back(ObjectPtrTy);
2592 Params.push_back(PtrObjectPtrTy);
2593 GcAssignWeakFn =
2594 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2595 Params,
2596 false),
2597 "objc_assign_weak");
2598 GcAssignGlobalFn =
2599 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2600 Params,
2601 false),
2602 "objc_assign_global");
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002603 GcAssignIvarFn =
2604 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2605 Params,
2606 false),
2607 "objc_assign_ivar");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002608 GcAssignStrongCastFn =
2609 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2610 Params,
2611 false),
2612 "objc_assign_strongCast");
2613
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002614}
2615
2616ObjCTypesHelper::~ObjCTypesHelper() {
2617}
2618
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002619/* *** */
2620
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002621CodeGen::CGObjCRuntime *
2622CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002623 return new CGObjCMac(CGM);
2624}