blob: 637edf3feae282eae6f97fa3d1681bb47e660b56 [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,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000411 const ObjCContainerDecl *CD,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000412 std::string &NameOut);
413
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000414public:
415 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000416 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000417
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000418 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000419 QualType ResultType,
420 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000421 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000422 bool IsClassMessage,
423 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000424
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000425 virtual CodeGen::RValue
426 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000427 QualType ResultType,
428 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000429 const ObjCInterfaceDecl *Class,
430 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000431 bool IsClassMessage,
432 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000433
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000434 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000435 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000436
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000437 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000438
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000439 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
440 const ObjCContainerDecl *CD=0);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000441
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000442 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000443
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000444 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000445
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000446 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000447 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000448
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000449 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000450
451 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000452 virtual llvm::Function *GetPropertyGetFunction();
453 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000454 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000455
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000456 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
457 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000458 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
459 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000460 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000461 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000462 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
463 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000464 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
465 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000466 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
467 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000468 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
469 llvm::Value *src, llvm::Value *dest);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000470};
471} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000472
473/* *** Helper Functions *** */
474
475/// getConstantGEP() - Help routine to construct simple GEPs.
476static llvm::Constant *getConstantGEP(llvm::Constant *C,
477 unsigned idx0,
478 unsigned idx1) {
479 llvm::Value *Idxs[] = {
480 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
481 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
482 };
483 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
484}
485
486/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000487
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000488CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
489 : CGM(cgm),
490 ObjCTypes(cgm),
491 ObjCABI(1)
492{
493 // FIXME: How does this get set in GCC? And what does it even mean?
494 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
495 ObjCABI = 2;
496
497 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000498}
499
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000500/// GetClass - Return a reference to the class for the given interface
501/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000502llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000503 const ObjCInterfaceDecl *ID) {
504 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000505}
506
507/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000508llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000509 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000510}
511
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000512/// Generate a constant CFString object.
513/*
514 struct __builtin_CFString {
515 const int *isa; // point to __CFConstantStringClassReference
516 int flags;
517 const char *str;
518 long length;
519 };
520*/
521
522llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000523 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000524}
525
526/// Generates a message send where the super is the receiver. This is
527/// a message send to self with special delivery semantics indicating
528/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000529CodeGen::RValue
530CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000531 QualType ResultType,
532 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000533 const ObjCInterfaceDecl *Class,
534 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000535 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000536 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000537 // Create and init a super structure; this is a (receiver, class)
538 // pair we will pass to objc_msgSendSuper.
539 llvm::Value *ObjCSuper =
540 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
541 llvm::Value *ReceiverAsObject =
542 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
543 CGF.Builder.CreateStore(ReceiverAsObject,
544 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000545
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000546 // If this is a class message the metaclass is passed as the target.
547 llvm::Value *Target;
548 if (IsClassMessage) {
549 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
550 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
551 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
552 Target = Super;
553 } else {
554 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
555 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000556 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
557 // and ObjCTypes types.
558 const llvm::Type *ClassTy =
559 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000560 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000561 CGF.Builder.CreateStore(Target,
562 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
563
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000564 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000565 ObjCSuper, ObjCTypes.SuperPtrCTy,
566 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000567}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000568
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000569/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000570CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000571 QualType ResultType,
572 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000573 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000574 bool IsClassMessage,
575 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000576 llvm::Value *Arg0 =
577 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000578 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000579 Arg0, CGF.getContext().getObjCIdType(),
580 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000581}
582
583CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000584 QualType ResultType,
585 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000586 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000587 QualType Arg0Ty,
588 bool IsSuper,
589 const CallArgList &CallArgs) {
590 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000591 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
592 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
593 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000594 CGF.getContext().getObjCSelType()));
595 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000596
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000597 const llvm::FunctionType *FTy =
598 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
599 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000600
601 llvm::Constant *Fn;
602 if (CGM.ReturnTypeUsesSret(ResultType)) {
603 Fn = ObjCTypes.getSendStretFn(IsSuper);
604 } else if (ResultType->isFloatingType()) {
605 // FIXME: Sadly, this is wrong. This actually depends on the
606 // architecture. This happens to be right for x86-32 though.
607 Fn = ObjCTypes.getSendFpretFn(IsSuper);
608 } else {
609 Fn = ObjCTypes.getSendFn(IsSuper);
610 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000611 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000612 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000613}
614
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000615llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000616 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000617 // FIXME: I don't understand why gcc generates this, or where it is
618 // resolved. Investigate. Its also wasteful to look this up over and
619 // over.
620 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
621
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000622 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
623 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000624}
625
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000626void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
627 // FIXME: We shouldn't need this, the protocol decl should contain
628 // enough information to tell us whether this was a declaration or a
629 // definition.
630 DefinedProtocols.insert(PD->getIdentifier());
631
632 // If we have generated a forward reference to this protocol, emit
633 // it now. Otherwise do nothing, the protocol objects are lazily
634 // emitted.
635 if (Protocols.count(PD->getIdentifier()))
636 GetOrEmitProtocol(PD);
637}
638
639llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
640 if (DefinedProtocols.count(PD->getIdentifier()))
641 return GetOrEmitProtocol(PD);
642 return GetOrEmitProtocolRef(PD);
643}
644
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000645/*
646 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
647 struct _objc_protocol {
648 struct _objc_protocol_extension *isa;
649 char *protocol_name;
650 struct _objc_protocol_list *protocol_list;
651 struct _objc__method_prototype_list *instance_methods;
652 struct _objc__method_prototype_list *class_methods
653 };
654
655 See EmitProtocolExtension().
656*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000657llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
658 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
659
660 // Early exit if a defining object has already been generated.
661 if (Entry && Entry->hasInitializer())
662 return Entry;
663
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000664 // FIXME: I don't understand why gcc generates this, or where it is
665 // resolved. Investigate. Its also wasteful to look this up over and
666 // over.
667 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
668
Chris Lattner8ec03f52008-11-24 03:54:41 +0000669 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000670
671 // Construct method lists.
672 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
673 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
674 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
675 e = PD->instmeth_end(); i != e; ++i) {
676 ObjCMethodDecl *MD = *i;
677 llvm::Constant *C = GetMethodDescriptionConstant(MD);
678 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
679 OptInstanceMethods.push_back(C);
680 } else {
681 InstanceMethods.push_back(C);
682 }
683 }
684
685 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
686 e = PD->classmeth_end(); i != e; ++i) {
687 ObjCMethodDecl *MD = *i;
688 llvm::Constant *C = GetMethodDescriptionConstant(MD);
689 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
690 OptClassMethods.push_back(C);
691 } else {
692 ClassMethods.push_back(C);
693 }
694 }
695
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000696 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000697 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000698 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000699 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000700 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +0000701 PD->protocol_begin(),
702 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000703 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000704 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
705 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000706 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
707 InstanceMethods);
708 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000709 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
710 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000711 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
712 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000713 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
714 Values);
715
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000716 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000717 // Already created, fix the linkage and update the initializer.
718 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000719 Entry->setInitializer(Init);
720 } else {
721 Entry =
722 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
723 llvm::GlobalValue::InternalLinkage,
724 Init,
725 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
726 &CGM.getModule());
727 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
728 UsedGlobals.push_back(Entry);
729 // FIXME: Is this necessary? Why only for protocol?
730 Entry->setAlignment(4);
731 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000732
733 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000734}
735
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000736llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000737 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
738
739 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000740 // We use the initializer as a marker of whether this is a forward
741 // reference or not. At module finalization we add the empty
742 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000743 Entry =
744 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000745 llvm::GlobalValue::ExternalLinkage,
746 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000747 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000748 &CGM.getModule());
749 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
750 UsedGlobals.push_back(Entry);
751 // FIXME: Is this necessary? Why only for protocol?
752 Entry->setAlignment(4);
753 }
754
755 return Entry;
756}
757
758/*
759 struct _objc_protocol_extension {
760 uint32_t size;
761 struct objc_method_description_list *optional_instance_methods;
762 struct objc_method_description_list *optional_class_methods;
763 struct objc_property_list *instance_properties;
764 };
765*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000766llvm::Constant *
767CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
768 const ConstantVector &OptInstanceMethods,
769 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000770 uint64_t Size =
771 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
772 std::vector<llvm::Constant*> Values(4);
773 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000774 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000775 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
776 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000777 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
778 OptInstanceMethods);
779 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000780 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
781 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000782 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
783 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000784 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
785 PD->getNameAsString(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000786 0,
Steve Naroff09c47192009-01-09 15:36:25 +0000787 PD->prop_begin(),
788 PD->prop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000789
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000790 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000791 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
792 Values[3]->isNullValue())
793 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
794
795 llvm::Constant *Init =
796 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
797 llvm::GlobalVariable *GV =
798 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
799 llvm::GlobalValue::InternalLinkage,
800 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000801 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000802 &CGM.getModule());
803 // No special section, but goes in llvm.used
804 UsedGlobals.push_back(GV);
805
806 return GV;
807}
808
809/*
810 struct objc_protocol_list {
811 struct objc_protocol_list *next;
812 long count;
813 Protocol *list[];
814 };
815*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000816llvm::Constant *
817CGObjCMac::EmitProtocolList(const std::string &Name,
818 ObjCProtocolDecl::protocol_iterator begin,
819 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000820 std::vector<llvm::Constant*> ProtocolRefs;
821
Daniel Dunbardbc933702008-08-21 21:57:41 +0000822 for (; begin != end; ++begin)
823 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000824
825 // Just return null for empty protocol lists
826 if (ProtocolRefs.empty())
827 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
828
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000829 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000830 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
831
832 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000833 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000834 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
835 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
836 Values[2] =
837 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
838 ProtocolRefs.size()),
839 ProtocolRefs);
840
841 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
842 llvm::GlobalVariable *GV =
843 new llvm::GlobalVariable(Init->getType(), false,
844 llvm::GlobalValue::InternalLinkage,
845 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000846 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000847 &CGM.getModule());
848 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
849 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
850}
851
852/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000853 struct _objc_property {
854 const char * const name;
855 const char * const attributes;
856 };
857
858 struct _objc_property_list {
859 uint32_t entsize; // sizeof (struct _objc_property)
860 uint32_t prop_count;
861 struct _objc_property[prop_count];
862 };
863*/
864llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000865 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000866 ObjCPropertyDecl * const *begin,
867 ObjCPropertyDecl * const *end) {
868 std::vector<llvm::Constant*> Properties, Prop(2);
869 for (; begin != end; ++begin) {
870 const ObjCPropertyDecl *PD = *begin;
871 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000872 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000873 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
874 Prop));
875 }
876
877 // Return null for empty list.
878 if (Properties.empty())
879 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
880
881 unsigned PropertySize =
882 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
883 std::vector<llvm::Constant*> Values(3);
884 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
885 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
886 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
887 Properties.size());
888 Values[2] = llvm::ConstantArray::get(AT, Properties);
889 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
890
891 llvm::GlobalVariable *GV =
892 new llvm::GlobalVariable(Init->getType(), false,
893 llvm::GlobalValue::InternalLinkage,
894 Init,
895 Name,
896 &CGM.getModule());
897 // No special section on property lists?
898 UsedGlobals.push_back(GV);
899 return llvm::ConstantExpr::getBitCast(GV,
900 ObjCTypes.PropertyListPtrTy);
901
902}
903
904/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000905 struct objc_method_description_list {
906 int count;
907 struct objc_method_description list[];
908 };
909*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000910llvm::Constant *
911CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
912 std::vector<llvm::Constant*> Desc(2);
913 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
914 ObjCTypes.SelectorPtrTy);
915 Desc[1] = GetMethodVarType(MD);
916 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
917 Desc);
918}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000919
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000920llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
921 const char *Section,
922 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000923 // Return null for empty list.
924 if (Methods.empty())
925 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
926
927 std::vector<llvm::Constant*> Values(2);
928 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
929 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
930 Methods.size());
931 Values[1] = llvm::ConstantArray::get(AT, Methods);
932 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
933
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000934 llvm::GlobalVariable *GV =
935 new llvm::GlobalVariable(Init->getType(), false,
936 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000937 Init, Name, &CGM.getModule());
938 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000939 UsedGlobals.push_back(GV);
940 return llvm::ConstantExpr::getBitCast(GV,
941 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000942}
943
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000944/*
945 struct _objc_category {
946 char *category_name;
947 char *class_name;
948 struct _objc_method_list *instance_methods;
949 struct _objc_method_list *class_methods;
950 struct _objc_protocol_list *protocols;
951 uint32_t size; // <rdar://4585769>
952 struct _objc_property_list *instance_properties;
953 };
954 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000955void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000956 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
957
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000958 // FIXME: This is poor design, the OCD should have a pointer to the
959 // category decl. Additionally, note that Category can be null for
960 // the @implementation w/o an @interface case. Sema should just
961 // create one for us as it does for @implementation so everyone else
962 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000963 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000964 const ObjCCategoryDecl *Category =
965 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000966 std::string ExtName(Interface->getNameAsString() + "_" +
967 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000968
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000969 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
970 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
971 e = OCD->instmeth_end(); i != e; ++i) {
972 // Instance methods should always be defined.
973 InstanceMethods.push_back(GetMethodConstant(*i));
974 }
975 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
976 e = OCD->classmeth_end(); i != e; ++i) {
977 // Class methods should always be defined.
978 ClassMethods.push_back(GetMethodConstant(*i));
979 }
980
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000981 std::vector<llvm::Constant*> Values(7);
982 Values[0] = GetClassName(OCD->getIdentifier());
983 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000984 Values[2] =
985 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
986 ExtName,
987 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000988 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000989 Values[3] =
990 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
991 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000992 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000993 if (Category) {
994 Values[4] =
995 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
996 Category->protocol_begin(),
997 Category->protocol_end());
998 } else {
999 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1000 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001001 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001002
1003 // If there is no category @interface then there can be no properties.
1004 if (Category) {
1005 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001006 OCD,
Steve Naroff09c47192009-01-09 15:36:25 +00001007 Category->prop_begin(),
1008 Category->prop_end());
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001009 } else {
1010 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1011 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001012
1013 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1014 Values);
1015
1016 llvm::GlobalVariable *GV =
1017 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1018 llvm::GlobalValue::InternalLinkage,
1019 Init,
1020 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1021 &CGM.getModule());
1022 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1023 UsedGlobals.push_back(GV);
1024 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001025}
1026
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001027// FIXME: Get from somewhere?
1028enum ClassFlags {
1029 eClassFlags_Factory = 0x00001,
1030 eClassFlags_Meta = 0x00002,
1031 // <rdr://5142207>
1032 eClassFlags_HasCXXStructors = 0x02000,
1033 eClassFlags_Hidden = 0x20000,
1034 eClassFlags_ABI2_Hidden = 0x00010,
1035 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1036};
1037
1038// <rdr://5142207&4705298&4843145>
1039static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1040 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1041 // FIXME: Support -fvisibility
1042 switch (attr->getVisibility()) {
1043 default:
1044 assert(0 && "Unknown visibility");
1045 return false;
1046 case VisibilityAttr::DefaultVisibility:
1047 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1048 return false;
1049 case VisibilityAttr::HiddenVisibility:
1050 return true;
1051 }
1052 } else {
1053 return false; // FIXME: Support -fvisibility
1054 }
1055}
1056
1057/*
1058 struct _objc_class {
1059 Class isa;
1060 Class super_class;
1061 const char *name;
1062 long version;
1063 long info;
1064 long instance_size;
1065 struct _objc_ivar_list *ivars;
1066 struct _objc_method_list *methods;
1067 struct _objc_cache *cache;
1068 struct _objc_protocol_list *protocols;
1069 // Objective-C 1.0 extensions (<rdr://4585769>)
1070 const char *ivar_layout;
1071 struct _objc_class_ext *ext;
1072 };
1073
1074 See EmitClassExtension();
1075 */
1076void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001077 DefinedSymbols.insert(ID->getIdentifier());
1078
Chris Lattner8ec03f52008-11-24 03:54:41 +00001079 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001080 // FIXME: Gross
1081 ObjCInterfaceDecl *Interface =
1082 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001083 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001084 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001085 Interface->protocol_begin(),
1086 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001087 const llvm::Type *InterfaceTy =
1088 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1089 unsigned Flags = eClassFlags_Factory;
1090 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1091
1092 // FIXME: Set CXX-structors flag.
1093 if (IsClassHidden(ID->getClassInterface()))
1094 Flags |= eClassFlags_Hidden;
1095
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001096 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1097 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1098 e = ID->instmeth_end(); i != e; ++i) {
1099 // Instance methods should always be defined.
1100 InstanceMethods.push_back(GetMethodConstant(*i));
1101 }
1102 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1103 e = ID->classmeth_end(); i != e; ++i) {
1104 // Class methods should always be defined.
1105 ClassMethods.push_back(GetMethodConstant(*i));
1106 }
1107
1108 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1109 e = ID->propimpl_end(); i != e; ++i) {
1110 ObjCPropertyImplDecl *PID = *i;
1111
1112 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1113 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1114
1115 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1116 if (llvm::Constant *C = GetMethodConstant(MD))
1117 InstanceMethods.push_back(C);
1118 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1119 if (llvm::Constant *C = GetMethodConstant(MD))
1120 InstanceMethods.push_back(C);
1121 }
1122 }
1123
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001124 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001125 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001126 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001127 // Record a reference to the super class.
1128 LazySymbols.insert(Super->getIdentifier());
1129
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001130 Values[ 1] =
1131 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1132 ObjCTypes.ClassPtrTy);
1133 } else {
1134 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1135 }
1136 Values[ 2] = GetClassName(ID->getIdentifier());
1137 // Version is always 0.
1138 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1139 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1140 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1141 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001142 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001143 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001144 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001145 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001146 // cache is always NULL.
1147 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1148 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001149 // FIXME: Set ivar_layout
1150 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001151 Values[11] = EmitClassExtension(ID);
1152 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1153 Values);
1154
1155 llvm::GlobalVariable *GV =
1156 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1157 llvm::GlobalValue::InternalLinkage,
1158 Init,
1159 std::string("\01L_OBJC_CLASS_")+ClassName,
1160 &CGM.getModule());
1161 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1162 UsedGlobals.push_back(GV);
1163 // FIXME: Why?
1164 GV->setAlignment(32);
1165 DefinedClasses.push_back(GV);
1166}
1167
1168llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1169 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001170 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001171 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001172 unsigned Flags = eClassFlags_Meta;
1173 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1174
1175 if (IsClassHidden(ID->getClassInterface()))
1176 Flags |= eClassFlags_Hidden;
1177
1178 std::vector<llvm::Constant*> Values(12);
1179 // The isa for the metaclass is the root of the hierarchy.
1180 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1181 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1182 Root = Super;
1183 Values[ 0] =
1184 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1185 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001186 // The super class for the metaclass is emitted as the name of the
1187 // super class. The runtime fixes this up to point to the
1188 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001189 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1190 Values[ 1] =
1191 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1192 ObjCTypes.ClassPtrTy);
1193 } else {
1194 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1195 }
1196 Values[ 2] = GetClassName(ID->getIdentifier());
1197 // Version is always 0.
1198 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1199 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1200 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1201 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001202 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001204 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001205 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001206 // cache is always NULL.
1207 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1208 Values[ 9] = Protocols;
1209 // ivar_layout for metaclass is always NULL.
1210 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1211 // The class extension is always unused for metaclasses.
1212 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1213 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1214 Values);
1215
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001216 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001217 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001218
1219 // Check for a forward reference.
1220 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1221 if (GV) {
1222 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1223 "Forward metaclass reference has incorrect type.");
1224 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1225 GV->setInitializer(Init);
1226 } else {
1227 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1228 llvm::GlobalValue::InternalLinkage,
1229 Init, Name,
1230 &CGM.getModule());
1231 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001232 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1233 UsedGlobals.push_back(GV);
1234 // FIXME: Why?
1235 GV->setAlignment(32);
1236
1237 return GV;
1238}
1239
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001240llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001241 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001242
1243 // FIXME: Should we look these up somewhere other than the
1244 // module. Its a bit silly since we only generate these while
1245 // processing an implementation, so exactly one pointer would work
1246 // if know when we entered/exitted an implementation block.
1247
1248 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001249 // Previously, metaclass with internal linkage may have been defined.
1250 // pass 'true' as 2nd argument so it is returned.
1251 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001252 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1253 "Forward metaclass reference has incorrect type.");
1254 return GV;
1255 } else {
1256 // Generate as an external reference to keep a consistent
1257 // module. This will be patched up when we emit the metaclass.
1258 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1259 llvm::GlobalValue::ExternalLinkage,
1260 0,
1261 Name,
1262 &CGM.getModule());
1263 }
1264}
1265
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001266/*
1267 struct objc_class_ext {
1268 uint32_t size;
1269 const char *weak_ivar_layout;
1270 struct _objc_property_list *properties;
1271 };
1272*/
1273llvm::Constant *
1274CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1275 uint64_t Size =
1276 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1277
1278 std::vector<llvm::Constant*> Values(3);
1279 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001280 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001281 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001282 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001283 ID,
Steve Naroff09c47192009-01-09 15:36:25 +00001284 ID->getClassInterface()->prop_begin(),
1285 ID->getClassInterface()->prop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001286
1287 // Return null if no extension bits are used.
1288 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1289 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1290
1291 llvm::Constant *Init =
1292 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1293 llvm::GlobalVariable *GV =
1294 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1295 llvm::GlobalValue::InternalLinkage,
1296 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001297 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001298 &CGM.getModule());
1299 // No special section, but goes in llvm.used
1300 UsedGlobals.push_back(GV);
1301
1302 return GV;
1303}
1304
1305/*
1306 struct objc_ivar {
1307 char *ivar_name;
1308 char *ivar_type;
1309 int ivar_offset;
1310 };
1311
1312 struct objc_ivar_list {
1313 int ivar_count;
1314 struct objc_ivar list[count];
1315 };
1316 */
1317llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1318 bool ForClass,
1319 const llvm::Type *InterfaceTy) {
1320 std::vector<llvm::Constant*> Ivars, Ivar(3);
1321
1322 // When emitting the root class GCC emits ivar entries for the
1323 // actual class structure. It is not clear if we need to follow this
1324 // behavior; for now lets try and get away with not doing it. If so,
1325 // the cleanest solution would be to make up an ObjCInterfaceDecl
1326 // for the class.
1327 if (ForClass)
1328 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1329
1330 const llvm::StructLayout *Layout =
1331 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1332 for (ObjCInterfaceDecl::ivar_iterator
1333 i = ID->getClassInterface()->ivar_begin(),
1334 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +00001335 const ObjCIvarDecl *V = *i;
1336 ObjCInterfaceDecl *OID =
1337 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1338 FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), V);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001339 unsigned Offset =
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +00001340 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001341 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001342 Ivar[0] = GetMethodVarName(V->getIdentifier());
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00001343 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001344 Ivar[1] = GetMethodVarType(TypeStr);
1345 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001346 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001347 }
1348
1349 // Return null for empty list.
1350 if (Ivars.empty())
1351 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1352
1353 std::vector<llvm::Constant*> Values(2);
1354 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1355 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1356 Ivars.size());
1357 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1358 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1359
1360 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1361 "\01L_OBJC_INSTANCE_VARIABLES_");
1362 llvm::GlobalVariable *GV =
1363 new llvm::GlobalVariable(Init->getType(), false,
1364 llvm::GlobalValue::InternalLinkage,
1365 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001366 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001367 &CGM.getModule());
1368 if (ForClass) {
1369 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1370 // FIXME: Why is this only here?
1371 GV->setAlignment(32);
1372 } else {
1373 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1374 }
1375 UsedGlobals.push_back(GV);
1376 return llvm::ConstantExpr::getBitCast(GV,
1377 ObjCTypes.IvarListPtrTy);
1378}
1379
1380/*
1381 struct objc_method {
1382 SEL method_name;
1383 char *method_types;
1384 void *method;
1385 };
1386
1387 struct objc_method_list {
1388 struct objc_method_list *obsolete;
1389 int count;
1390 struct objc_method methods_list[count];
1391 };
1392*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001393
1394/// GetMethodConstant - Return a struct objc_method constant for the
1395/// given method if it has been defined. The result is null if the
1396/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001397llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001398 // FIXME: Use DenseMap::lookup
1399 llvm::Function *Fn = MethodDefinitions[MD];
1400 if (!Fn)
1401 return 0;
1402
1403 std::vector<llvm::Constant*> Method(3);
1404 Method[0] =
1405 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1406 ObjCTypes.SelectorPtrTy);
1407 Method[1] = GetMethodVarType(MD);
1408 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1409 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1410}
1411
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001412llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1413 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001414 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001415 // Return null for empty list.
1416 if (Methods.empty())
1417 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1418
1419 std::vector<llvm::Constant*> Values(3);
1420 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1421 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1422 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1423 Methods.size());
1424 Values[2] = llvm::ConstantArray::get(AT, Methods);
1425 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1426
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427 llvm::GlobalVariable *GV =
1428 new llvm::GlobalVariable(Init->getType(), false,
1429 llvm::GlobalValue::InternalLinkage,
1430 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001431 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001432 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001433 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001434 UsedGlobals.push_back(GV);
1435 return llvm::ConstantExpr::getBitCast(GV,
1436 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001437}
1438
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001439llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD,
1440 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001441 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001442 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001443
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001444 const llvm::FunctionType *MethodTy =
1445 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001446 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001447 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001448 llvm::GlobalValue::InternalLinkage,
1449 Name,
1450 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001451 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001452
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001453 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001454}
1455
1456llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001457 // Abuse this interface function as a place to finalize.
1458 FinishModule();
1459
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001460 return NULL;
1461}
1462
Daniel Dunbar49f66022008-09-24 03:38:44 +00001463llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1464 return ObjCTypes.GetPropertyFn;
1465}
1466
1467llvm::Function *CGObjCMac::GetPropertySetFunction() {
1468 return ObjCTypes.SetPropertyFn;
1469}
1470
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001471llvm::Function *CGObjCMac::EnumerationMutationFunction()
1472{
1473 return ObjCTypes.EnumerationMutationFn;
1474}
1475
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001476/*
1477
1478Objective-C setjmp-longjmp (sjlj) Exception Handling
1479--
1480
1481The basic framework for a @try-catch-finally is as follows:
1482{
1483 objc_exception_data d;
1484 id _rethrow = null;
1485
1486 objc_exception_try_enter(&d);
1487 if (!setjmp(d.jmp_buf)) {
1488 ... try body ...
1489 } else {
1490 // exception path
1491 id _caught = objc_exception_extract(&d);
1492
1493 // enter new try scope for handlers
1494 if (!setjmp(d.jmp_buf)) {
1495 ... match exception and execute catch blocks ...
1496
1497 // fell off end, rethrow.
1498 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001499 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001500 } else {
1501 // exception in catch block
1502 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001503 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001504 }
1505 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001506 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001507
1508finally:
1509 // match either the initial try_enter or the catch try_enter,
1510 // depending on the path followed.
1511 objc_exception_try_exit(&d);
1512finally_no_exit:
1513 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001514 ... dispatch to finally destination ...
1515
1516finally_rethrow:
1517 objc_exception_throw(_rethrow);
1518
1519finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001520}
1521
1522This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001523uses _rethrow to determine if objc_exception_try_exit should be called
1524and if the object should be rethrown. This breaks in the face of
1525throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001526
1527We specialize this framework for a few particular circumstances:
1528
1529 - If there are no catch blocks, then we avoid emitting the second
1530 exception handling context.
1531
1532 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1533 e)) we avoid emitting the code to rethrow an uncaught exception.
1534
1535 - FIXME: If there is no @finally block we can do a few more
1536 simplifications.
1537
1538Rethrows and Jumps-Through-Finally
1539--
1540
1541Support for implicit rethrows and jumping through the finally block is
1542handled by storing the current exception-handling context in
1543ObjCEHStack.
1544
Daniel Dunbar898d5082008-09-30 01:06:03 +00001545In order to implement proper @finally semantics, we support one basic
1546mechanism for jumping through the finally block to an arbitrary
1547destination. Constructs which generate exits from a @try or @catch
1548block use this mechanism to implement the proper semantics by chaining
1549jumps, as necessary.
1550
1551This mechanism works like the one used for indirect goto: we
1552arbitrarily assign an ID to each destination and store the ID for the
1553destination in a variable prior to entering the finally block. At the
1554end of the finally block we simply create a switch to the proper
1555destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001556
1557Code gen for @synchronized(expr) stmt;
1558Effectively generating code for:
1559objc_sync_enter(expr);
1560@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001561*/
1562
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001563void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1564 const Stmt &S) {
1565 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001566 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001567 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1568 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1569 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1570 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001571 llvm::Value *DestCode =
1572 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1573
1574 // Generate jump code. Done here so we can directly add things to
1575 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001576 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001577 llvm::SwitchInst *FinallySwitch =
1578 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1579 FinallyEnd, 10, FinallyJump);
1580
1581 // Push an EH context entry, used for handling rethrows and jumps
1582 // through finally.
1583 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1584 FinallySwitch, DestCode);
1585 CGF.ObjCEHStack.push_back(&EHEntry);
1586
1587 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001588 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1589 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001590 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1591 "_rethrow");
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001592 if (!isTry) {
1593 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001594 llvm::Value *Arg = CGF.EmitScalarExpr(
1595 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1596 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1597 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001598 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001599
1600 // Enter a new try block and call setjmp.
1601 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1602 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1603 "jmpbufarray");
1604 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1605 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1606 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001607
Daniel Dunbar55e87422008-11-11 02:29:29 +00001608 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1609 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001610 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001611 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001612
1613 // Emit the @try block.
1614 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001615 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1616 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001617 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001618
1619 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001620 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001621
1622 // Retrieve the exception object. We may emit multiple blocks but
1623 // nothing can cross this so the value is already in SSA form.
1624 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1625 ExceptionData,
1626 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001627 EHEntry.Exception = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001628 if (!isTry)
1629 {
1630 CGF.Builder.CreateStore(Caught, RethrowPtr);
1631 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1632 }
1633 else if (const ObjCAtCatchStmt* CatchStmt =
1634 cast<ObjCAtTryStmt>(S).getCatchStmts())
1635 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001636 // Enter a new exception try block (in case a @catch block throws
1637 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001638 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001639
Anders Carlsson80f25672008-09-09 17:59:25 +00001640 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1641 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001642 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001643
Daniel Dunbar55e87422008-11-11 02:29:29 +00001644 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1645 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001646 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001647
1648 CGF.EmitBlock(CatchBlock);
1649
Daniel Dunbar55e40722008-09-27 07:03:52 +00001650 // Handle catch list. As a special case we check if everything is
1651 // matched and avoid generating code for falling off the end if
1652 // so.
1653 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001654 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001655 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001656
Anders Carlssondde0a942008-09-11 09:15:33 +00001657 const DeclStmt *CatchParam =
1658 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001659 const VarDecl *VD = 0;
1660 const PointerType *PT = 0;
1661
Anders Carlsson80f25672008-09-09 17:59:25 +00001662 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001663 if (!CatchParam) {
1664 AllMatched = true;
1665 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001666 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001667 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001668
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001669 // catch(id e) always matches.
1670 // FIXME: For the time being we also match id<X>; this should
1671 // be rejected by Sema instead.
1672 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1673 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001674 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001675 }
1676
Daniel Dunbar55e40722008-09-27 07:03:52 +00001677 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001678 if (CatchParam) {
1679 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001680 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001681 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001682 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001683
Anders Carlssondde0a942008-09-11 09:15:33 +00001684 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001685 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001686 break;
1687 }
1688
Daniel Dunbar129271a2008-09-27 07:36:24 +00001689 assert(PT && "Unexpected non-pointer type in @catch");
1690 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001691 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001692 assert(ObjCType && "Catch parameter must have Objective-C type!");
1693
1694 // Check if the @catch block matches the exception object.
1695 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1696
Anders Carlsson80f25672008-09-09 17:59:25 +00001697 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1698 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001699
Daniel Dunbar55e87422008-11-11 02:29:29 +00001700 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001701
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001702 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001703 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001704
1705 // Emit the @catch block.
1706 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001707 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001708 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001709
1710 llvm::Value *Tmp =
1711 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1712 "tmp");
1713 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001714
1715 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001716 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001717
1718 CGF.EmitBlock(NextCatchBlock);
1719 }
1720
Daniel Dunbar55e40722008-09-27 07:03:52 +00001721 if (!AllMatched) {
1722 // None of the handlers caught the exception, so store it to be
1723 // rethrown at the end of the @finally block.
1724 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001725 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001726 }
1727
1728 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001729 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001730 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1731 ExceptionData),
1732 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001733 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001734 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001735 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001736 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001737 }
1738
Daniel Dunbar898d5082008-09-30 01:06:03 +00001739 // Pop the exception-handling stack entry. It is important to do
1740 // this now, because the code in the @finally block is not in this
1741 // context.
1742 CGF.ObjCEHStack.pop_back();
1743
Anders Carlsson80f25672008-09-09 17:59:25 +00001744 // Emit the @finally block.
1745 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001746 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001747
1748 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001749 if (isTry) {
1750 if (const ObjCAtFinallyStmt* FinallyStmt =
1751 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1752 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1753 }
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001754 else {
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001755 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001756 // For @synchronized, call objc_sync_enter(sync.expr)
1757 llvm::Value *Arg = CGF.EmitScalarExpr(
1758 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1759 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1760 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1761 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001762
Daniel Dunbar898d5082008-09-30 01:06:03 +00001763 CGF.EmitBlock(FinallyJump);
1764
1765 CGF.EmitBlock(FinallyRethrow);
1766 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1767 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001768 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001769
1770 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001771}
1772
1773void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001774 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001775 llvm::Value *ExceptionAsObject;
1776
1777 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1778 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1779 ExceptionAsObject =
1780 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1781 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001782 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001783 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001784 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001785 }
1786
1787 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001788 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001789
1790 // Clear the insertion point to indicate we are in unreachable code.
1791 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001792}
1793
Daniel Dunbar898d5082008-09-30 01:06:03 +00001794void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1795 llvm::BasicBlock *Dst,
1796 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001797 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001798 return;
1799
1800 // Find the destination code for this block. We always use 0 for the
1801 // fallthrough block (default destination).
1802 llvm::SwitchInst *SI = E->FinallySwitch;
1803 llvm::ConstantInt *ID;
1804 if (Dst == SI->getDefaultDest()) {
1805 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1806 } else {
1807 ID = SI->findCaseDest(Dst);
1808 if (!ID) {
1809 // No code found, get a new unique one by just using the number
1810 // of switch successors.
1811 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1812 SI->addCase(ID, Dst);
1813 }
1814 }
1815
1816 // Set the destination code and branch.
1817 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001818 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001819}
1820
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001821/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001822/// object: objc_read_weak (id *src)
1823///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001824llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001825 llvm::Value *AddrWeakObj)
1826{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001827 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001828 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001829 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001830 return read_weak;
1831}
1832
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001833/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1834/// objc_assign_weak (id src, id *dst)
1835///
1836void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1837 llvm::Value *src, llvm::Value *dst)
1838{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001839 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1840 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001841 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1842 src, dst, "weakassign");
1843 return;
1844}
1845
Fariborz Jahanian58626502008-11-19 00:59:10 +00001846/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1847/// objc_assign_global (id src, id *dst)
1848///
1849void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1850 llvm::Value *src, llvm::Value *dst)
1851{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001852 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1853 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001854 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1855 src, dst, "globalassign");
1856 return;
1857}
1858
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001859/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1860/// objc_assign_ivar (id src, id *dst)
1861///
1862void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1863 llvm::Value *src, llvm::Value *dst)
1864{
1865 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1866 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1867 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1868 src, dst, "assignivar");
1869 return;
1870}
1871
Fariborz Jahanian58626502008-11-19 00:59:10 +00001872/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1873/// objc_assign_strongCast (id src, id *dst)
1874///
1875void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1876 llvm::Value *src, llvm::Value *dst)
1877{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001878 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1879 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001880 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1881 src, dst, "weakassign");
1882 return;
1883}
1884
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001885/* *** Private Interface *** */
1886
1887/// EmitImageInfo - Emit the image info marker used to encode some module
1888/// level information.
1889///
1890/// See: <rdr://4810609&4810587&4810587>
1891/// struct IMAGE_INFO {
1892/// unsigned version;
1893/// unsigned flags;
1894/// };
1895enum ImageInfoFlags {
1896 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1897 eImageInfo_GarbageCollected = (1 << 1),
1898 eImageInfo_GCOnly = (1 << 2)
1899};
1900
1901void CGObjCMac::EmitImageInfo() {
1902 unsigned version = 0; // Version is unused?
1903 unsigned flags = 0;
1904
1905 // FIXME: Fix and continue?
1906 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1907 flags |= eImageInfo_GarbageCollected;
1908 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1909 flags |= eImageInfo_GCOnly;
1910
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001911 // Emitted as int[2];
1912 llvm::Constant *values[2] = {
1913 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1914 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1915 };
1916 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001917 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001918 new llvm::GlobalVariable(AT, true,
1919 llvm::GlobalValue::InternalLinkage,
1920 llvm::ConstantArray::get(AT, values, 2),
1921 "\01L_OBJC_IMAGE_INFO",
1922 &CGM.getModule());
1923
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001924 if (ObjCABI == 1) {
1925 GV->setSection("__OBJC, __image_info,regular");
1926 } else {
1927 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1928 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001929
1930 UsedGlobals.push_back(GV);
1931}
1932
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001933
1934// struct objc_module {
1935// unsigned long version;
1936// unsigned long size;
1937// const char *name;
1938// Symtab symtab;
1939// };
1940
1941// FIXME: Get from somewhere
1942static const int ModuleVersion = 7;
1943
1944void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001945 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1946
1947 std::vector<llvm::Constant*> Values(4);
1948 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1949 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001950 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001951 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001952 Values[3] = EmitModuleSymbols();
1953
1954 llvm::GlobalVariable *GV =
1955 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1956 llvm::GlobalValue::InternalLinkage,
1957 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1958 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001959 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001960 &CGM.getModule());
1961 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1962 UsedGlobals.push_back(GV);
1963}
1964
1965llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001966 unsigned NumClasses = DefinedClasses.size();
1967 unsigned NumCategories = DefinedCategories.size();
1968
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001969 // Return null if no symbols were defined.
1970 if (!NumClasses && !NumCategories)
1971 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1972
1973 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001974 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1975 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1976 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1977 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1978
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001979 // The runtime expects exactly the list of defined classes followed
1980 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001981 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001982 for (unsigned i=0; i<NumClasses; i++)
1983 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1984 ObjCTypes.Int8PtrTy);
1985 for (unsigned i=0; i<NumCategories; i++)
1986 Symbols[NumClasses + i] =
1987 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1988 ObjCTypes.Int8PtrTy);
1989
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001990 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001991 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001992 NumClasses + NumCategories),
1993 Symbols);
1994
1995 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1996
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001997 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001998 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001999 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002001 "\01L_OBJC_SYMBOLS",
2002 &CGM.getModule());
2003 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2004 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002005 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2006}
2007
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002008llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002009 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002010 LazySymbols.insert(ID->getIdentifier());
2011
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002012 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2013
2014 if (!Entry) {
2015 llvm::Constant *Casted =
2016 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2017 ObjCTypes.ClassPtrTy);
2018 Entry =
2019 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2020 llvm::GlobalValue::InternalLinkage,
2021 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2022 &CGM.getModule());
2023 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2024 UsedGlobals.push_back(Entry);
2025 }
2026
2027 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002028}
2029
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002030llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002031 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2032
2033 if (!Entry) {
2034 llvm::Constant *Casted =
2035 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2036 ObjCTypes.SelectorPtrTy);
2037 Entry =
2038 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2039 llvm::GlobalValue::InternalLinkage,
2040 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2041 &CGM.getModule());
2042 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2043 UsedGlobals.push_back(Entry);
2044 }
2045
2046 return Builder.CreateLoad(Entry, false, "tmp");
2047}
2048
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002049llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2050 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002051
2052 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002053 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002054 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002055 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002056 llvm::GlobalValue::InternalLinkage,
2057 C, "\01L_OBJC_CLASS_NAME_",
2058 &CGM.getModule());
2059 Entry->setSection("__TEXT,__cstring,cstring_literals");
2060 UsedGlobals.push_back(Entry);
2061 }
2062
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002063 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002064}
2065
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002066llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2067 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2068
2069 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002070 // FIXME: Avoid std::string copying.
2071 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002072 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002073 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002074 llvm::GlobalValue::InternalLinkage,
2075 C, "\01L_OBJC_METH_VAR_NAME_",
2076 &CGM.getModule());
2077 Entry->setSection("__TEXT,__cstring,cstring_literals");
2078 UsedGlobals.push_back(Entry);
2079 }
2080
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002081 return getConstantGEP(Entry, 0, 0);
2082}
2083
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002084// FIXME: Merge into a single cstring creation function.
2085llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2086 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2087}
2088
2089// FIXME: Merge into a single cstring creation function.
2090llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2091 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2092}
2093
2094llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2095 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002096
2097 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002098 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002099 Entry =
2100 new llvm::GlobalVariable(C->getType(), false,
2101 llvm::GlobalValue::InternalLinkage,
2102 C, "\01L_OBJC_METH_VAR_TYPE_",
2103 &CGM.getModule());
2104 Entry->setSection("__TEXT,__cstring,cstring_literals");
2105 UsedGlobals.push_back(Entry);
2106 }
2107
2108 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002109}
2110
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002111// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002112llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002113 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002114 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2115 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002116 return GetMethodVarType(TypeStr);
2117}
2118
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002119// FIXME: Merge into a single cstring creation function.
2120llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2121 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2122
2123 if (!Entry) {
2124 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2125 Entry =
2126 new llvm::GlobalVariable(C->getType(), false,
2127 llvm::GlobalValue::InternalLinkage,
2128 C, "\01L_OBJC_PROP_NAME_ATTR_",
2129 &CGM.getModule());
2130 Entry->setSection("__TEXT,__cstring,cstring_literals");
2131 UsedGlobals.push_back(Entry);
2132 }
2133
2134 return getConstantGEP(Entry, 0, 0);
2135}
2136
2137// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002138// FIXME: This Decl should be more precise.
2139llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2140 const Decl *Container) {
2141 std::string TypeStr;
2142 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002143 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2144}
2145
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002146void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002147 const ObjCContainerDecl *CD,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002148 std::string &NameOut) {
2149 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002150 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002151 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002152 assert (CD && "Missing container decl in GetNameForMethod");
2153 NameOut += CD->getNameAsString();
Chris Lattner077bf5e2008-11-24 03:33:13 +00002154 NameOut += ' ';
2155 NameOut += D->getSelector().getAsString();
2156 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002157}
2158
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002159void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002160 EmitModuleInfo();
2161
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002162 // Emit the dummy bodies for any protocols which were referenced but
2163 // never defined.
2164 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2165 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2166 if (i->second->hasInitializer())
2167 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002168
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002169 std::vector<llvm::Constant*> Values(5);
2170 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2171 Values[1] = GetClassName(i->first);
2172 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2173 Values[3] = Values[4] =
2174 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2175 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2176 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2177 Values));
2178 }
2179
2180 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002181 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002182 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002183 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002184 }
2185
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002186 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002187 llvm::GlobalValue *GV =
2188 new llvm::GlobalVariable(AT, false,
2189 llvm::GlobalValue::AppendingLinkage,
2190 llvm::ConstantArray::get(AT, Used),
2191 "llvm.used",
2192 &CGM.getModule());
2193
2194 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002195
2196 // Add assembler directives to add lazy undefined symbol references
2197 // for classes which are referenced but not defined. This is
2198 // important for correct linker interaction.
2199
2200 // FIXME: Uh, this isn't particularly portable.
2201 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002202
2203 if (!CGM.getModule().getModuleInlineAsm().empty())
2204 s << "\n";
2205
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002206 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2207 e = LazySymbols.end(); i != e; ++i) {
2208 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2209 }
2210 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2211 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002212 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002213 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2214 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002215
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002216 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002217}
2218
2219/* *** */
2220
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002221ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002222 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002223{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002224 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2225 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002226
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002227 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002228 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002229 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002230 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2231
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002232 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002233 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002234 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002235
2236 // FIXME: It would be nice to unify this with the opaque type, so
2237 // that the IR comes out a bit cleaner.
2238 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2239 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002240
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002241 MethodDescriptionTy =
2242 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002243 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002244 NULL);
2245 CGM.getModule().addTypeName("struct._objc_method_description",
2246 MethodDescriptionTy);
2247
2248 MethodDescriptionListTy =
2249 llvm::StructType::get(IntTy,
2250 llvm::ArrayType::get(MethodDescriptionTy, 0),
2251 NULL);
2252 CGM.getModule().addTypeName("struct._objc_method_description_list",
2253 MethodDescriptionListTy);
2254 MethodDescriptionListPtrTy =
2255 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2256
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002257 PropertyTy = llvm::StructType::get(Int8PtrTy,
2258 Int8PtrTy,
2259 NULL);
2260 CGM.getModule().addTypeName("struct._objc_property",
2261 PropertyTy);
2262
2263 PropertyListTy = llvm::StructType::get(IntTy,
2264 IntTy,
2265 llvm::ArrayType::get(PropertyTy, 0),
2266 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002267 CGM.getModule().addTypeName("struct._objc_property_list",
2268 PropertyListTy);
2269 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2270
2271 // Protocol description structures
2272
2273 ProtocolExtensionTy =
2274 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2275 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2276 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2277 PropertyListPtrTy,
2278 NULL);
2279 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2280 ProtocolExtensionTy);
2281 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2282
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002283 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002284
2285 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2286 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2287
2288 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2289 LongTy,
2290 llvm::ArrayType::get(ProtocolTyHolder, 0),
2291 NULL);
2292 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2293
2294 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002295 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002296 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2297 MethodDescriptionListPtrTy,
2298 MethodDescriptionListPtrTy,
2299 NULL);
2300 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2301
2302 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2303 CGM.getModule().addTypeName("struct._objc_protocol_list",
2304 ProtocolListTy);
2305 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2306
2307 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2308 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2309 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002310
2311 // Class description structures
2312
2313 IvarTy = llvm::StructType::get(Int8PtrTy,
2314 Int8PtrTy,
2315 IntTy,
2316 NULL);
2317 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2318
2319 IvarListTy = llvm::OpaqueType::get();
2320 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2321 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2322
2323 MethodTy = llvm::StructType::get(SelectorPtrTy,
2324 Int8PtrTy,
2325 Int8PtrTy,
2326 NULL);
2327 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2328
2329 MethodListTy = llvm::OpaqueType::get();
2330 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2331 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2332
2333 CacheTy = llvm::OpaqueType::get();
2334 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2335 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2336
2337 ClassExtensionTy =
2338 llvm::StructType::get(IntTy,
2339 Int8PtrTy,
2340 PropertyListPtrTy,
2341 NULL);
2342 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2343 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2344
2345 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2346
2347 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2348 llvm::PointerType::getUnqual(ClassTyHolder),
2349 Int8PtrTy,
2350 LongTy,
2351 LongTy,
2352 LongTy,
2353 IvarListPtrTy,
2354 MethodListPtrTy,
2355 CachePtrTy,
2356 ProtocolListPtrTy,
2357 Int8PtrTy,
2358 ClassExtensionPtrTy,
2359 NULL);
2360 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2361
2362 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2363 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2364 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2365
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002366 CategoryTy = llvm::StructType::get(Int8PtrTy,
2367 Int8PtrTy,
2368 MethodListPtrTy,
2369 MethodListPtrTy,
2370 ProtocolListPtrTy,
2371 IntTy,
2372 PropertyListPtrTy,
2373 NULL);
2374 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2375
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002376 // I'm not sure I like this. The implicit coordination is a bit
2377 // gross. We should solve this in a reasonable fashion because this
2378 // is a pretty common task (match some runtime data structure with
2379 // an LLVM data structure).
2380
2381 // FIXME: This is leaked.
2382 // FIXME: Merge with rewriter code?
2383 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2384 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002385 &Ctx.Idents.get("_objc_super"));
Douglas Gregor44b43212008-12-11 16:49:14 +00002386 RD->addDecl(Ctx,
2387 FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2388 Ctx.getObjCIdType(), 0, false, 0),
2389 true);
2390 RD->addDecl(Ctx,
2391 FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2392 Ctx.getObjCClassType(), 0, false, 0),
2393 true);
2394 RD->completeDefinition(Ctx);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002395
2396 SuperCTy = Ctx.getTagDeclType(RD);
2397 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2398
2399 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002400 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002401
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002402 // Global metadata structures
2403
2404 SymtabTy = llvm::StructType::get(LongTy,
2405 SelectorPtrTy,
2406 ShortTy,
2407 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002408 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002409 NULL);
2410 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2411 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2412
2413 ModuleTy =
2414 llvm::StructType::get(LongTy,
2415 LongTy,
2416 Int8PtrTy,
2417 SymtabPtrTy,
2418 NULL);
2419 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002420
Daniel Dunbar49f66022008-09-24 03:38:44 +00002421 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002422
2423 std::vector<const llvm::Type*> Params;
2424 Params.push_back(ObjectPtrTy);
2425 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002426 MessageSendFn =
2427 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2428 Params,
2429 true),
2430 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002431
2432 Params.clear();
2433 Params.push_back(Int8PtrTy);
2434 Params.push_back(ObjectPtrTy);
2435 Params.push_back(SelectorPtrTy);
2436 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002437 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2438 Params,
2439 true),
2440 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002441
2442 Params.clear();
2443 Params.push_back(ObjectPtrTy);
2444 Params.push_back(SelectorPtrTy);
2445 // FIXME: This should be long double on x86_64?
2446 MessageSendFpretFn =
2447 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2448 Params,
2449 true),
2450 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002451
2452 Params.clear();
2453 Params.push_back(SuperPtrTy);
2454 Params.push_back(SelectorPtrTy);
2455 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002456 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2457 Params,
2458 true),
2459 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002460
2461 Params.clear();
2462 Params.push_back(Int8PtrTy);
2463 Params.push_back(SuperPtrTy);
2464 Params.push_back(SelectorPtrTy);
2465 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002466 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2467 Params,
2468 true),
2469 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002470
2471 // There is no objc_msgSendSuper_fpret? How can that work?
2472 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002473
Daniel Dunbar49f66022008-09-24 03:38:44 +00002474 // Property manipulation functions.
2475
2476 Params.clear();
2477 Params.push_back(ObjectPtrTy);
2478 Params.push_back(SelectorPtrTy);
2479 Params.push_back(LongTy);
2480 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2481 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002482 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2483 Params,
2484 false),
2485 "objc_getProperty");
2486
Daniel Dunbar49f66022008-09-24 03:38:44 +00002487 Params.clear();
2488 Params.push_back(ObjectPtrTy);
2489 Params.push_back(SelectorPtrTy);
2490 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002491 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002492 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2493 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2494 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002495 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2496 Params,
2497 false),
2498 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002499
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002500 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002501
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002502 Params.clear();
2503 Params.push_back(ObjectPtrTy);
2504 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002505 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2506 Params,
2507 false),
2508 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002509
2510 // FIXME: This is the size of the setjmp buffer and should be
2511 // target specific. 18 is what's used on 32-bit X86.
2512 uint64_t SetJmpBufferSize = 18;
2513
2514 // Exceptions
2515 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002516 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002517
2518 ExceptionDataTy =
2519 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2520 SetJmpBufferSize),
2521 StackPtrTy, NULL);
2522 CGM.getModule().addTypeName("struct._objc_exception_data",
2523 ExceptionDataTy);
2524
2525 Params.clear();
2526 Params.push_back(ObjectPtrTy);
2527 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002528 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2529 Params,
2530 false),
2531 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002532
2533 Params.clear();
2534 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2535 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2537 Params,
2538 false),
2539 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002540 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002541 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2542 Params,
2543 false),
2544 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002545 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002546 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2547 Params,
2548 false),
2549 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002550
2551 Params.clear();
2552 Params.push_back(ClassPtrTy);
2553 Params.push_back(ObjectPtrTy);
2554 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002555 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2556 Params,
2557 false),
2558 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002559
2560 // synchronized APIs
2561 // void objc_sync_enter (id)
2562 Params.clear();
2563 Params.push_back(ObjectPtrTy);
2564 SyncEnterFn =
2565 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2566 Params,
2567 false),
2568 "objc_sync_enter");
2569 // void objc_sync_exit (id)
2570 SyncExitFn =
2571 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2572 Params,
2573 false),
2574 "objc_sync_exit");
2575
Anders Carlsson124526b2008-09-09 10:10:21 +00002576
2577 Params.clear();
2578 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2579 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2581 Params,
2582 false),
2583 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002584
2585 // gc's API
2586 // id objc_read_weak (id *)
2587 Params.clear();
2588 Params.push_back(PtrObjectPtrTy);
2589 GcReadWeakFn =
2590 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2591 Params,
2592 false),
2593 "objc_read_weak");
2594 // id objc_assign_weak (id, id *)
2595 Params.clear();
2596 Params.push_back(ObjectPtrTy);
2597 Params.push_back(PtrObjectPtrTy);
2598 GcAssignWeakFn =
2599 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2600 Params,
2601 false),
2602 "objc_assign_weak");
2603 GcAssignGlobalFn =
2604 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2605 Params,
2606 false),
2607 "objc_assign_global");
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002608 GcAssignIvarFn =
2609 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2610 Params,
2611 false),
2612 "objc_assign_ivar");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002613 GcAssignStrongCastFn =
2614 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2615 Params,
2616 false),
2617 "objc_assign_strongCast");
2618
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002619}
2620
2621ObjCTypesHelper::~ObjCTypesHelper() {
2622}
2623
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002624/* *** */
2625
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002626CodeGen::CGObjCRuntime *
2627CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002628 return new CGObjCMac(CGM);
2629}