blob: 8a9d1fed0afbfe609e75ff1a0f48fafc3634da65 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000038/// ObjCTypesHelper - Helper class that encapsulates lazy
39/// construction of varies types used during ObjC generation.
40class ObjCTypesHelper {
41private:
42 CodeGen::CodeGenModule &CGM;
43
Daniel Dunbar5669e572008-10-17 03:24:53 +000044 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46 *MessageSendSuperFpretFn;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000047
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000048public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000049 const llvm::Type *ShortTy, *IntTy, *LongTy;
50 const llvm::Type *Int8PtrTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000051
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000052 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000054
55 /// PtrObjectPtrTy - LLVM type for id *
56 const llvm::Type *PtrObjectPtrTy;
57
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000058 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000059 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000060 /// ProtocolPtrTy - LLVM type for external protocol handles
61 /// (typeof(Protocol))
62 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000063
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000064 // SuperCTy - clang type for struct objc_super.
65 QualType SuperCTy;
66 // SuperPtrCTy - clang type for struct objc_super *.
67 QualType SuperPtrCTy;
68
Daniel Dunbare8b470d2008-08-23 04:28:29 +000069 /// SuperTy - LLVM type for struct objc_super.
70 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000071 /// SuperPtrTy - LLVM type for struct objc_super *.
72 const llvm::Type *SuperPtrTy;
Daniel Dunbare8b470d2008-08-23 04:28:29 +000073
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000074 /// SymtabTy - LLVM type for struct objc_symtab.
75 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000076 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000078 /// ModuleTy - LLVM type for struct objc_module.
79 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000080
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000081 /// ProtocolTy - LLVM type for struct objc_protocol.
82 const llvm::StructType *ProtocolTy;
83 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
84 const llvm::Type *ProtocolPtrTy;
85 /// ProtocolExtensionTy - LLVM type for struct
86 /// objc_protocol_extension.
87 const llvm::StructType *ProtocolExtensionTy;
88 /// ProtocolExtensionTy - LLVM type for struct
89 /// objc_protocol_extension *.
90 const llvm::Type *ProtocolExtensionPtrTy;
91 /// MethodDescriptionTy - LLVM type for struct
92 /// objc_method_description.
93 const llvm::StructType *MethodDescriptionTy;
94 /// MethodDescriptionListTy - LLVM type for struct
95 /// objc_method_description_list.
96 const llvm::StructType *MethodDescriptionListTy;
97 /// MethodDescriptionListPtrTy - LLVM type for struct
98 /// objc_method_description_list *.
99 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000100 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
101 /// in GCC parlance).
102 const llvm::StructType *PropertyTy;
103 /// PropertyListTy - LLVM type for struct objc_property_list
104 /// (_prop_list_t in GCC parlance).
105 const llvm::StructType *PropertyListTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000106 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
107 const llvm::Type *PropertyListPtrTy;
108 /// ProtocolListTy - LLVM type for struct objc_property_list.
109 const llvm::Type *ProtocolListTy;
110 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
111 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000112 /// CategoryTy - LLVM type for struct objc_category.
113 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000114 /// ClassTy - LLVM type for struct objc_class.
115 const llvm::StructType *ClassTy;
116 /// ClassPtrTy - LLVM type for struct objc_class *.
117 const llvm::Type *ClassPtrTy;
118 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
119 const llvm::StructType *ClassExtensionTy;
120 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
121 const llvm::Type *ClassExtensionPtrTy;
122 /// CacheTy - LLVM type for struct objc_cache.
123 const llvm::Type *CacheTy;
124 /// CachePtrTy - LLVM type for struct objc_cache *.
125 const llvm::Type *CachePtrTy;
126 // IvarTy - LLVM type for struct objc_ivar.
127 const llvm::StructType *IvarTy;
128 /// IvarListTy - LLVM type for struct objc_ivar_list.
129 const llvm::Type *IvarListTy;
130 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
131 const llvm::Type *IvarListPtrTy;
132 // MethodTy - LLVM type for struct objc_method.
133 const llvm::StructType *MethodTy;
134 /// MethodListTy - LLVM type for struct objc_method_list.
135 const llvm::Type *MethodListTy;
136 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
137 const llvm::Type *MethodListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000138
Daniel Dunbar49f66022008-09-24 03:38:44 +0000139 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000140 llvm::Function *EnumerationMutationFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000141
142 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
143 const llvm::Type *ExceptionDataTy;
144
145 /// ExceptionThrowFn - LLVM objc_exception_throw function.
146 llvm::Function *ExceptionThrowFn;
147
148 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
149 llvm::Function *ExceptionTryEnterFn;
150
151 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
152 llvm::Function *ExceptionTryExitFn;
153
154 /// ExceptionExtractFn - LLVM objc_exception_extract function.
155 llvm::Function *ExceptionExtractFn;
156
157 /// ExceptionMatchFn - LLVM objc_exception_match function.
158 llvm::Function *ExceptionMatchFn;
159
160 /// SetJmpFn - LLVM _setjmp function.
161 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000162
163 /// SyncEnterFn - LLVM object_sync_enter function.
164 llvm::Function *SyncEnterFn;
165
166 /// SyncExitFn - LLVM object_sync_exit function.
167 llvm::Function *SyncExitFn;
168
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000169 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
170 llvm::Function *GcReadWeakFn;
171
172 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
173 llvm::Function *GcAssignWeakFn;
174
175 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
176 llvm::Function *GcAssignGlobalFn;
177
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000178 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
179 llvm::Function *GcAssignIvarFn;
180
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000181 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
182 llvm::Function *GcAssignStrongCastFn;
183
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000184public:
185 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
186 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000187
188
189 llvm::Function *getSendFn(bool IsSuper) {
190 return IsSuper ? MessageSendSuperFn : MessageSendFn;
191 }
192
193 llvm::Function *getSendStretFn(bool IsSuper) {
194 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
195 }
196
197 llvm::Function *getSendFpretFn(bool IsSuper) {
198 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
199 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000200};
201
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000202class CGObjCMac : public CodeGen::CGObjCRuntime {
203private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204 CodeGen::CodeGenModule &CGM;
205 ObjCTypesHelper ObjCTypes;
206 /// ObjCABI - FIXME: Not sure yet.
207 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000208
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000209 /// LazySymbols - Symbols to generate a lazy reference for. See
210 /// DefinedSymbols and FinishModule().
211 std::set<IdentifierInfo*> LazySymbols;
212
213 /// DefinedSymbols - External symbols which are defined by this
214 /// module. The symbols in this list and LazySymbols are used to add
215 /// special linker symbols which ensure that Objective-C modules are
216 /// linked properly.
217 std::set<IdentifierInfo*> DefinedSymbols;
218
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000219 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000220 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000221
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000222 /// MethodVarNames - uniqued method variable names.
223 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
224
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000225 /// MethodVarTypes - uniqued method type signatures. We have to use
226 /// a StringMap here because have no other unique reference.
227 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
228
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000229 /// MethodDefinitions - map of methods which have been defined in
230 /// this translation unit.
231 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
232
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000233 /// PropertyNames - uniqued method variable names.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
235
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000236 /// ClassReferences - uniqued class references.
237 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
238
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000239 /// SelectorReferences - uniqued selector references.
240 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
241
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000242 /// Protocols - Protocols for which an objc_protocol structure has
243 /// been emitted. Forward declarations are handled by creating an
244 /// empty structure whose initializer is filled in when/if defined.
245 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
246
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000247 /// DefinedProtocols - Protocols which have actually been
248 /// defined. We should not need this, see FIXME in GenerateProtocol.
249 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
250
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000251 /// DefinedClasses - List of defined classes.
252 std::vector<llvm::GlobalValue*> DefinedClasses;
253
254 /// DefinedCategories - List of defined categories.
255 std::vector<llvm::GlobalValue*> DefinedCategories;
256
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000257 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000258 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000259 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000260
261 /// EmitImageInfo - Emit the image info marker used to encode some module
262 /// level information.
263 void EmitImageInfo();
264
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000265 /// EmitModuleInfo - Another marker encoding module level
266 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000267 void EmitModuleInfo();
268
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000269 /// EmitModuleSymols - Emit module symbols, the list of defined
270 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000271 llvm::Constant *EmitModuleSymbols();
272
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000273 /// FinishModule - Write out global data structures at the end of
274 /// processing a translation unit.
275 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000276
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000277 /// EmitClassExtension - Generate the class extension structure used
278 /// to store the weak ivar layout and properties. The return value
279 /// has type ClassExtensionPtrTy.
280 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
281
282 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
283 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000284 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000285 const ObjCInterfaceDecl *ID);
286
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000287 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000288 QualType ResultType,
289 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000290 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000291 QualType Arg0Ty,
292 bool IsSuper,
293 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000294
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000295 /// EmitIvarList - Emit the ivar list for the given
296 /// implementation. If ForClass is true the list of class ivars
297 /// (i.e. metaclass ivars) is emitted, otherwise the list of
298 /// interface ivars will be emitted. The return value has type
299 /// IvarListPtrTy.
300 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
301 bool ForClass,
302 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000303
304 /// EmitMetaClass - Emit a forward reference to the class structure
305 /// for the metaclass of the given interface. The return value has
306 /// type ClassPtrTy.
307 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
308
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000309 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000310 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000311 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
312 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000313 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000314 const ConstantVector &Methods);
315
316 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
317
318 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000319
320 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000321 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000322 llvm::Constant *EmitMethodList(const std::string &Name,
323 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000324 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000325
326 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000327 /// method declarations.
328 /// - TypeName: The name for the type containing the methods.
329 /// - IsProtocol: True iff these methods are for a protocol.
330 /// - ClassMethds: True iff these are class methods.
331 /// - Required: When true, only "required" methods are
332 /// listed. Similarly, when false only "optional" methods are
333 /// listed. For classes this should always be true.
334 /// - begin, end: The method list to output.
335 ///
336 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000337 llvm::Constant *EmitMethodDescList(const std::string &Name,
338 const char *Section,
339 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000340
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000341 /// EmitPropertyList - Emit the given property list. The return
342 /// value has type PropertyListPtrTy.
343 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000344 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000345 ObjCPropertyDecl * const *begin,
346 ObjCPropertyDecl * const *end);
347
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000348 /// GetOrEmitProtocol - Get the protocol object for the given
349 /// declaration, emitting it if necessary. The return value has type
350 /// ProtocolPtrTy.
351 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
352
353 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
354 /// object for the given declaration, emitting it if needed. These
355 /// forward references will be filled in with empty bodies if no
356 /// definition is seen. The return value has type ProtocolPtrTy.
357 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
358
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000359 /// EmitProtocolExtension - Generate the protocol extension
360 /// structure used to store optional instance and class methods, and
361 /// protocol properties. The return value has type
362 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000363 llvm::Constant *
364 EmitProtocolExtension(const ObjCProtocolDecl *PD,
365 const ConstantVector &OptInstanceMethods,
366 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000367
368 /// EmitProtocolList - Generate the list of referenced
369 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000370 llvm::Constant *EmitProtocolList(const std::string &Name,
371 ObjCProtocolDecl::protocol_iterator begin,
372 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000373
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000374 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
375 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000376 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000377
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000378 /// GetProtocolRef - Return a reference to the internal protocol
379 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000380 /// defined. The return value has type ProtocolPtrTy.
381 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000383 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000384 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000385 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000386
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000387 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000388 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000389 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000390 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000392
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000393 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000394 /// selector's name. The return value has type char *.
395
396 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000397 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000399
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000400 /// GetPropertyName - Return a unique constant for the given
401 /// name. The return value has type char *.
402 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
403
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000404 // FIXME: This can be dropped once string functions are unified.
405 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
406 const Decl *Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000407
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 std::string &NameOut);
412
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000413public:
414 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000415 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000416
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000417 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000418 QualType ResultType,
419 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000420 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000421 bool IsClassMessage,
422 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000423
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000424 virtual CodeGen::RValue
425 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000426 QualType ResultType,
427 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000428 const ObjCInterfaceDecl *Class,
429 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000430 bool IsClassMessage,
431 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000432
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000434 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000435
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000436 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000437
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000438 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000439
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000440 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000441
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000442 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000443
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000444 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000445 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000446
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000447 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000448
449 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000450 virtual llvm::Function *GetPropertyGetFunction();
451 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000452 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000453
454 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
455 const ObjCAtTryStmt &S);
456 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
457 const ObjCAtThrowStmt &S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000458 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
459 const ObjCAtSynchronizedStmt &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
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000669 const char *ProtocolName = PD->getIdentifierName();
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] =
700 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
701 PD->protocol_begin(),
702 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000703 Values[3] =
704 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
705 + PD->getName(),
706 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
707 InstanceMethods);
708 Values[4] =
709 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
710 + PD->getName(),
711 "__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,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000747 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
748 &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] =
775 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
776 + PD->getName(),
777 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
778 OptInstanceMethods);
779 Values[2] =
780 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
781 + PD->getName(),
782 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
783 OptClassMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000784 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
785 PD->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000786 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000787 PD->classprop_begin(),
788 PD->classprop_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,
801 (std::string("\01L_OBJC_PROTOCOLEXT_") +
802 PD->getName()),
803 &CGM.getModule());
804 // No special section, but goes in llvm.used
805 UsedGlobals.push_back(GV);
806
807 return GV;
808}
809
810/*
811 struct objc_protocol_list {
812 struct objc_protocol_list *next;
813 long count;
814 Protocol *list[];
815 };
816*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000817llvm::Constant *
818CGObjCMac::EmitProtocolList(const std::string &Name,
819 ObjCProtocolDecl::protocol_iterator begin,
820 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000821 std::vector<llvm::Constant*> ProtocolRefs;
822
Daniel Dunbardbc933702008-08-21 21:57:41 +0000823 for (; begin != end; ++begin)
824 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000825
826 // Just return null for empty protocol lists
827 if (ProtocolRefs.empty())
828 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
829
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000830 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000831 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
832
833 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000834 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000835 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
836 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
837 Values[2] =
838 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
839 ProtocolRefs.size()),
840 ProtocolRefs);
841
842 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
843 llvm::GlobalVariable *GV =
844 new llvm::GlobalVariable(Init->getType(), false,
845 llvm::GlobalValue::InternalLinkage,
846 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000847 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000848 &CGM.getModule());
849 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
850 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
851}
852
853/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000854 struct _objc_property {
855 const char * const name;
856 const char * const attributes;
857 };
858
859 struct _objc_property_list {
860 uint32_t entsize; // sizeof (struct _objc_property)
861 uint32_t prop_count;
862 struct _objc_property[prop_count];
863 };
864*/
865llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000866 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000867 ObjCPropertyDecl * const *begin,
868 ObjCPropertyDecl * const *end) {
869 std::vector<llvm::Constant*> Properties, Prop(2);
870 for (; begin != end; ++begin) {
871 const ObjCPropertyDecl *PD = *begin;
872 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000873 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000874 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
875 Prop));
876 }
877
878 // Return null for empty list.
879 if (Properties.empty())
880 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
881
882 unsigned PropertySize =
883 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
884 std::vector<llvm::Constant*> Values(3);
885 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
886 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
887 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
888 Properties.size());
889 Values[2] = llvm::ConstantArray::get(AT, Properties);
890 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
891
892 llvm::GlobalVariable *GV =
893 new llvm::GlobalVariable(Init->getType(), false,
894 llvm::GlobalValue::InternalLinkage,
895 Init,
896 Name,
897 &CGM.getModule());
898 // No special section on property lists?
899 UsedGlobals.push_back(GV);
900 return llvm::ConstantExpr::getBitCast(GV,
901 ObjCTypes.PropertyListPtrTy);
902
903}
904
905/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000906 struct objc_method_description_list {
907 int count;
908 struct objc_method_description list[];
909 };
910*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000911llvm::Constant *
912CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
913 std::vector<llvm::Constant*> Desc(2);
914 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
915 ObjCTypes.SelectorPtrTy);
916 Desc[1] = GetMethodVarType(MD);
917 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
918 Desc);
919}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000920
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000921llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
922 const char *Section,
923 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000924 // Return null for empty list.
925 if (Methods.empty())
926 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
927
928 std::vector<llvm::Constant*> Values(2);
929 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
930 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
931 Methods.size());
932 Values[1] = llvm::ConstantArray::get(AT, Methods);
933 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
934
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000935 llvm::GlobalVariable *GV =
936 new llvm::GlobalVariable(Init->getType(), false,
937 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000938 Init, Name, &CGM.getModule());
939 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000940 UsedGlobals.push_back(GV);
941 return llvm::ConstantExpr::getBitCast(GV,
942 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000943}
944
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000945/*
946 struct _objc_category {
947 char *category_name;
948 char *class_name;
949 struct _objc_method_list *instance_methods;
950 struct _objc_method_list *class_methods;
951 struct _objc_protocol_list *protocols;
952 uint32_t size; // <rdar://4585769>
953 struct _objc_property_list *instance_properties;
954 };
955 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000956void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000957 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
958
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000959 // FIXME: This is poor design, the OCD should have a pointer to the
960 // category decl. Additionally, note that Category can be null for
961 // the @implementation w/o an @interface case. Sema should just
962 // create one for us as it does for @implementation so everyone else
963 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000964 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000965 const ObjCCategoryDecl *Category =
966 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000967 std::string ExtName(std::string(Interface->getName()) +
968 "_" +
969 OCD->getName());
970
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000971 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
972 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
973 e = OCD->instmeth_end(); i != e; ++i) {
974 // Instance methods should always be defined.
975 InstanceMethods.push_back(GetMethodConstant(*i));
976 }
977 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
978 e = OCD->classmeth_end(); i != e; ++i) {
979 // Class methods should always be defined.
980 ClassMethods.push_back(GetMethodConstant(*i));
981 }
982
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000983 std::vector<llvm::Constant*> Values(7);
984 Values[0] = GetClassName(OCD->getIdentifier());
985 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000986 Values[2] =
987 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
988 ExtName,
989 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000990 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000991 Values[3] =
992 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
993 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000994 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000995 if (Category) {
996 Values[4] =
997 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
998 Category->protocol_begin(),
999 Category->protocol_end());
1000 } else {
1001 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1002 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001003 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001004
1005 // If there is no category @interface then there can be no properties.
1006 if (Category) {
1007 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001008 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001009 Category->classprop_begin(),
1010 Category->classprop_end());
1011 } else {
1012 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1013 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001014
1015 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1016 Values);
1017
1018 llvm::GlobalVariable *GV =
1019 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1020 llvm::GlobalValue::InternalLinkage,
1021 Init,
1022 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1023 &CGM.getModule());
1024 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1025 UsedGlobals.push_back(GV);
1026 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001027}
1028
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001029// FIXME: Get from somewhere?
1030enum ClassFlags {
1031 eClassFlags_Factory = 0x00001,
1032 eClassFlags_Meta = 0x00002,
1033 // <rdr://5142207>
1034 eClassFlags_HasCXXStructors = 0x02000,
1035 eClassFlags_Hidden = 0x20000,
1036 eClassFlags_ABI2_Hidden = 0x00010,
1037 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1038};
1039
1040// <rdr://5142207&4705298&4843145>
1041static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1042 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1043 // FIXME: Support -fvisibility
1044 switch (attr->getVisibility()) {
1045 default:
1046 assert(0 && "Unknown visibility");
1047 return false;
1048 case VisibilityAttr::DefaultVisibility:
1049 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1050 return false;
1051 case VisibilityAttr::HiddenVisibility:
1052 return true;
1053 }
1054 } else {
1055 return false; // FIXME: Support -fvisibility
1056 }
1057}
1058
1059/*
1060 struct _objc_class {
1061 Class isa;
1062 Class super_class;
1063 const char *name;
1064 long version;
1065 long info;
1066 long instance_size;
1067 struct _objc_ivar_list *ivars;
1068 struct _objc_method_list *methods;
1069 struct _objc_cache *cache;
1070 struct _objc_protocol_list *protocols;
1071 // Objective-C 1.0 extensions (<rdr://4585769>)
1072 const char *ivar_layout;
1073 struct _objc_class_ext *ext;
1074 };
1075
1076 See EmitClassExtension();
1077 */
1078void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001079 DefinedSymbols.insert(ID->getIdentifier());
1080
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001081 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001082 // FIXME: Gross
1083 ObjCInterfaceDecl *Interface =
1084 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001085 llvm::Constant *Protocols =
1086 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1087 Interface->protocol_begin(),
1088 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001089 const llvm::Type *InterfaceTy =
1090 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1091 unsigned Flags = eClassFlags_Factory;
1092 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1093
1094 // FIXME: Set CXX-structors flag.
1095 if (IsClassHidden(ID->getClassInterface()))
1096 Flags |= eClassFlags_Hidden;
1097
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001098 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1099 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1100 e = ID->instmeth_end(); i != e; ++i) {
1101 // Instance methods should always be defined.
1102 InstanceMethods.push_back(GetMethodConstant(*i));
1103 }
1104 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1105 e = ID->classmeth_end(); i != e; ++i) {
1106 // Class methods should always be defined.
1107 ClassMethods.push_back(GetMethodConstant(*i));
1108 }
1109
1110 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1111 e = ID->propimpl_end(); i != e; ++i) {
1112 ObjCPropertyImplDecl *PID = *i;
1113
1114 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1115 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1116
1117 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1118 if (llvm::Constant *C = GetMethodConstant(MD))
1119 InstanceMethods.push_back(C);
1120 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1121 if (llvm::Constant *C = GetMethodConstant(MD))
1122 InstanceMethods.push_back(C);
1123 }
1124 }
1125
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001126 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001127 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001128 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001129 // Record a reference to the super class.
1130 LazySymbols.insert(Super->getIdentifier());
1131
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001132 Values[ 1] =
1133 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1134 ObjCTypes.ClassPtrTy);
1135 } else {
1136 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1137 }
1138 Values[ 2] = GetClassName(ID->getIdentifier());
1139 // Version is always 0.
1140 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1141 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1142 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1143 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001144 Values[ 7] =
1145 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1146 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001147 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001148 // cache is always NULL.
1149 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1150 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001151 // FIXME: Set ivar_layout
1152 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001153 Values[11] = EmitClassExtension(ID);
1154 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1155 Values);
1156
1157 llvm::GlobalVariable *GV =
1158 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1159 llvm::GlobalValue::InternalLinkage,
1160 Init,
1161 std::string("\01L_OBJC_CLASS_")+ClassName,
1162 &CGM.getModule());
1163 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1164 UsedGlobals.push_back(GV);
1165 // FIXME: Why?
1166 GV->setAlignment(32);
1167 DefinedClasses.push_back(GV);
1168}
1169
1170llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1171 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001172 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001173 const ConstantVector &Methods) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001174 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001175 unsigned Flags = eClassFlags_Meta;
1176 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1177
1178 if (IsClassHidden(ID->getClassInterface()))
1179 Flags |= eClassFlags_Hidden;
1180
1181 std::vector<llvm::Constant*> Values(12);
1182 // The isa for the metaclass is the root of the hierarchy.
1183 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1184 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1185 Root = Super;
1186 Values[ 0] =
1187 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1188 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001189 // The super class for the metaclass is emitted as the name of the
1190 // super class. The runtime fixes this up to point to the
1191 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001192 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1193 Values[ 1] =
1194 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1195 ObjCTypes.ClassPtrTy);
1196 } else {
1197 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1198 }
1199 Values[ 2] = GetClassName(ID->getIdentifier());
1200 // Version is always 0.
1201 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1202 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1203 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1204 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001205 Values[ 7] =
1206 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1207 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001208 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001209 // cache is always NULL.
1210 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1211 Values[ 9] = Protocols;
1212 // ivar_layout for metaclass is always NULL.
1213 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1214 // The class extension is always unused for metaclasses.
1215 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1216 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1217 Values);
1218
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001219 std::string Name("\01L_OBJC_METACLASS_");
1220 Name += ClassName;
1221
1222 // Check for a forward reference.
1223 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1224 if (GV) {
1225 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1226 "Forward metaclass reference has incorrect type.");
1227 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1228 GV->setInitializer(Init);
1229 } else {
1230 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1231 llvm::GlobalValue::InternalLinkage,
1232 Init, Name,
1233 &CGM.getModule());
1234 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001235 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1236 UsedGlobals.push_back(GV);
1237 // FIXME: Why?
1238 GV->setAlignment(32);
1239
1240 return GV;
1241}
1242
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001243llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1244 std::string Name("\01L_OBJC_METACLASS_");
1245 Name += ID->getName();
1246
1247 // FIXME: Should we look these up somewhere other than the
1248 // module. Its a bit silly since we only generate these while
1249 // processing an implementation, so exactly one pointer would work
1250 // if know when we entered/exitted an implementation block.
1251
1252 // Check for an existing forward reference.
1253 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1254 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1255 "Forward metaclass reference has incorrect type.");
1256 return GV;
1257 } else {
1258 // Generate as an external reference to keep a consistent
1259 // module. This will be patched up when we emit the metaclass.
1260 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1261 llvm::GlobalValue::ExternalLinkage,
1262 0,
1263 Name,
1264 &CGM.getModule());
1265 }
1266}
1267
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001268/*
1269 struct objc_class_ext {
1270 uint32_t size;
1271 const char *weak_ivar_layout;
1272 struct _objc_property_list *properties;
1273 };
1274*/
1275llvm::Constant *
1276CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1277 uint64_t Size =
1278 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1279
1280 std::vector<llvm::Constant*> Values(3);
1281 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001282 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001283 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001284 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1285 ID->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001286 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001287 ID->getClassInterface()->classprop_begin(),
1288 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001289
1290 // Return null if no extension bits are used.
1291 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1292 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1293
1294 llvm::Constant *Init =
1295 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1296 llvm::GlobalVariable *GV =
1297 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1298 llvm::GlobalValue::InternalLinkage,
1299 Init,
1300 (std::string("\01L_OBJC_CLASSEXT_") +
1301 ID->getName()),
1302 &CGM.getModule());
1303 // No special section, but goes in llvm.used
1304 UsedGlobals.push_back(GV);
1305
1306 return GV;
1307}
1308
1309/*
1310 struct objc_ivar {
1311 char *ivar_name;
1312 char *ivar_type;
1313 int ivar_offset;
1314 };
1315
1316 struct objc_ivar_list {
1317 int ivar_count;
1318 struct objc_ivar list[count];
1319 };
1320 */
1321llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1322 bool ForClass,
1323 const llvm::Type *InterfaceTy) {
1324 std::vector<llvm::Constant*> Ivars, Ivar(3);
1325
1326 // When emitting the root class GCC emits ivar entries for the
1327 // actual class structure. It is not clear if we need to follow this
1328 // behavior; for now lets try and get away with not doing it. If so,
1329 // the cleanest solution would be to make up an ObjCInterfaceDecl
1330 // for the class.
1331 if (ForClass)
1332 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1333
1334 const llvm::StructLayout *Layout =
1335 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1336 for (ObjCInterfaceDecl::ivar_iterator
1337 i = ID->getClassInterface()->ivar_begin(),
1338 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1339 ObjCIvarDecl *V = *i;
1340 unsigned Offset =
1341 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1342 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001343 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001344 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001345 Ivar[1] = GetMethodVarType(TypeStr);
1346 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001347 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001348 }
1349
1350 // Return null for empty list.
1351 if (Ivars.empty())
1352 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1353
1354 std::vector<llvm::Constant*> Values(2);
1355 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1356 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1357 Ivars.size());
1358 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1359 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1360
1361 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1362 "\01L_OBJC_INSTANCE_VARIABLES_");
1363 llvm::GlobalVariable *GV =
1364 new llvm::GlobalVariable(Init->getType(), false,
1365 llvm::GlobalValue::InternalLinkage,
1366 Init,
1367 std::string(Prefix) + ID->getName(),
1368 &CGM.getModule());
1369 if (ForClass) {
1370 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1371 // FIXME: Why is this only here?
1372 GV->setAlignment(32);
1373 } else {
1374 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1375 }
1376 UsedGlobals.push_back(GV);
1377 return llvm::ConstantExpr::getBitCast(GV,
1378 ObjCTypes.IvarListPtrTy);
1379}
1380
1381/*
1382 struct objc_method {
1383 SEL method_name;
1384 char *method_types;
1385 void *method;
1386 };
1387
1388 struct objc_method_list {
1389 struct objc_method_list *obsolete;
1390 int count;
1391 struct objc_method methods_list[count];
1392 };
1393*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001394
1395/// GetMethodConstant - Return a struct objc_method constant for the
1396/// given method if it has been defined. The result is null if the
1397/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001398llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001399 // FIXME: Use DenseMap::lookup
1400 llvm::Function *Fn = MethodDefinitions[MD];
1401 if (!Fn)
1402 return 0;
1403
1404 std::vector<llvm::Constant*> Method(3);
1405 Method[0] =
1406 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1407 ObjCTypes.SelectorPtrTy);
1408 Method[1] = GetMethodVarType(MD);
1409 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1410 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1411}
1412
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001413llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1414 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001415 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001416 // Return null for empty list.
1417 if (Methods.empty())
1418 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1419
1420 std::vector<llvm::Constant*> Values(3);
1421 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1422 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1423 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1424 Methods.size());
1425 Values[2] = llvm::ConstantArray::get(AT, Methods);
1426 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1427
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001428 llvm::GlobalVariable *GV =
1429 new llvm::GlobalVariable(Init->getType(), false,
1430 llvm::GlobalValue::InternalLinkage,
1431 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001432 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001433 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001434 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001435 UsedGlobals.push_back(GV);
1436 return llvm::ConstantExpr::getBitCast(GV,
1437 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001438}
1439
1440llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001441 std::string Name;
1442 GetNameForMethod(OMD, Name);
1443
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.
1556
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001557*/
1558
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001559void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001560 const ObjCAtTryStmt &S) {
1561 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001562 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1563 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1564 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1565 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001566 llvm::Value *DestCode =
1567 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1568
1569 // Generate jump code. Done here so we can directly add things to
1570 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001571 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001572 llvm::SwitchInst *FinallySwitch =
1573 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1574 FinallyEnd, 10, FinallyJump);
1575
1576 // Push an EH context entry, used for handling rethrows and jumps
1577 // through finally.
1578 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1579 FinallySwitch, DestCode);
1580 CGF.ObjCEHStack.push_back(&EHEntry);
1581
1582 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001583 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1584 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001585 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1586 "_rethrow");
Anders Carlsson80f25672008-09-09 17:59:25 +00001587
1588 // Enter a new try block and call setjmp.
1589 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1590 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1591 "jmpbufarray");
1592 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1593 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1594 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001595
Daniel Dunbar55e87422008-11-11 02:29:29 +00001596 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1597 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001598 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001599 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001600
1601 // Emit the @try block.
1602 CGF.EmitBlock(TryBlock);
1603 CGF.EmitStmt(S.getTryBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001604 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001605
1606 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001607 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001608
1609 // Retrieve the exception object. We may emit multiple blocks but
1610 // nothing can cross this so the value is already in SSA form.
1611 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1612 ExceptionData,
1613 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001614 EHEntry.Exception = Caught;
Daniel Dunbar55e40722008-09-27 07:03:52 +00001615 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1616 // Enter a new exception try block (in case a @catch block throws
1617 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001618 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001619
Anders Carlsson80f25672008-09-09 17:59:25 +00001620 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1621 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001622 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001623
Daniel Dunbar55e87422008-11-11 02:29:29 +00001624 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1625 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001626 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001627
1628 CGF.EmitBlock(CatchBlock);
1629
Daniel Dunbar55e40722008-09-27 07:03:52 +00001630 // Handle catch list. As a special case we check if everything is
1631 // matched and avoid generating code for falling off the end if
1632 // so.
1633 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001634 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001635 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001636
Anders Carlssondde0a942008-09-11 09:15:33 +00001637 const DeclStmt *CatchParam =
1638 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001639 const VarDecl *VD = 0;
1640 const PointerType *PT = 0;
1641
Anders Carlsson80f25672008-09-09 17:59:25 +00001642 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001643 if (!CatchParam) {
1644 AllMatched = true;
1645 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001646 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001647 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001648
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001649 // catch(id e) always matches.
1650 // FIXME: For the time being we also match id<X>; this should
1651 // be rejected by Sema instead.
1652 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1653 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001654 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001655 }
1656
Daniel Dunbar55e40722008-09-27 07:03:52 +00001657 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001658 if (CatchParam) {
1659 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001660 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001661 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001662 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001663
Anders Carlssondde0a942008-09-11 09:15:33 +00001664 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001665 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001666 break;
1667 }
1668
Daniel Dunbar129271a2008-09-27 07:36:24 +00001669 assert(PT && "Unexpected non-pointer type in @catch");
1670 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001671 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001672 assert(ObjCType && "Catch parameter must have Objective-C type!");
1673
1674 // Check if the @catch block matches the exception object.
1675 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1676
Anders Carlsson80f25672008-09-09 17:59:25 +00001677 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1678 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001679
Daniel Dunbar55e87422008-11-11 02:29:29 +00001680 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001681
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001682 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001683 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001684
1685 // Emit the @catch block.
1686 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001687 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001688 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001689
1690 llvm::Value *Tmp =
1691 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1692 "tmp");
1693 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001694
1695 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001696 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001697
1698 CGF.EmitBlock(NextCatchBlock);
1699 }
1700
Daniel Dunbar55e40722008-09-27 07:03:52 +00001701 if (!AllMatched) {
1702 // None of the handlers caught the exception, so store it to be
1703 // rethrown at the end of the @finally block.
1704 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001705 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001706 }
1707
1708 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001709 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001710 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1711 ExceptionData),
1712 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001713 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001714 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001715 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001716 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001717 }
1718
Daniel Dunbar898d5082008-09-30 01:06:03 +00001719 // Pop the exception-handling stack entry. It is important to do
1720 // this now, because the code in the @finally block is not in this
1721 // context.
1722 CGF.ObjCEHStack.pop_back();
1723
Anders Carlsson80f25672008-09-09 17:59:25 +00001724 // Emit the @finally block.
1725 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001726 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001727
1728 CGF.EmitBlock(FinallyNoExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00001729 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1730 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1731
Daniel Dunbar898d5082008-09-30 01:06:03 +00001732 CGF.EmitBlock(FinallyJump);
1733
1734 CGF.EmitBlock(FinallyRethrow);
1735 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1736 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001737 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001738
1739 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001740}
1741
1742void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001743 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001744 llvm::Value *ExceptionAsObject;
1745
1746 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1747 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1748 ExceptionAsObject =
1749 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1750 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001751 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001752 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001753 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001754 }
1755
1756 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001757 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001758
1759 // Clear the insertion point to indicate we are in unreachable code.
1760 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001761}
1762
Daniel Dunbar898d5082008-09-30 01:06:03 +00001763void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1764 llvm::BasicBlock *Dst,
1765 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001766 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001767 return;
1768
1769 // Find the destination code for this block. We always use 0 for the
1770 // fallthrough block (default destination).
1771 llvm::SwitchInst *SI = E->FinallySwitch;
1772 llvm::ConstantInt *ID;
1773 if (Dst == SI->getDefaultDest()) {
1774 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1775 } else {
1776 ID = SI->findCaseDest(Dst);
1777 if (!ID) {
1778 // No code found, get a new unique one by just using the number
1779 // of switch successors.
1780 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1781 SI->addCase(ID, Dst);
1782 }
1783 }
1784
1785 // Set the destination code and branch.
1786 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001787 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001788}
1789
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001790/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001791/// object: objc_read_weak (id *src)
1792///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001793llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001794 llvm::Value *AddrWeakObj)
1795{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001796 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001797 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001798 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001799 return read_weak;
1800}
1801
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001802/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1803/// objc_assign_weak (id src, id *dst)
1804///
1805void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1806 llvm::Value *src, llvm::Value *dst)
1807{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001808 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1809 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001810 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1811 src, dst, "weakassign");
1812 return;
1813}
1814
Fariborz Jahanian58626502008-11-19 00:59:10 +00001815/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1816/// objc_assign_global (id src, id *dst)
1817///
1818void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1819 llvm::Value *src, llvm::Value *dst)
1820{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001821 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1822 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001823 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1824 src, dst, "globalassign");
1825 return;
1826}
1827
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001828/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1829/// objc_assign_ivar (id src, id *dst)
1830///
1831void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1832 llvm::Value *src, llvm::Value *dst)
1833{
1834 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1835 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1836 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1837 src, dst, "assignivar");
1838 return;
1839}
1840
Fariborz Jahanian58626502008-11-19 00:59:10 +00001841/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1842/// objc_assign_strongCast (id src, id *dst)
1843///
1844void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1845 llvm::Value *src, llvm::Value *dst)
1846{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001847 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1848 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001849 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1850 src, dst, "weakassign");
1851 return;
1852}
1853
Chris Lattner10cac6f2008-11-15 21:26:17 +00001854/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1855/// Effectively generating code for:
1856/// objc_sync_enter(expr);
1857/// @try stmt @finally { objc_sync_exit(expr); }
1858void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1859 const ObjCAtSynchronizedStmt &S) {
1860 // Create various blocks we refer to for handling @finally.
1861 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1862 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1863 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1864 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1865 llvm::Value *DestCode =
1866 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1867
1868 // Generate jump code. Done here so we can directly add things to
1869 // the switch instruction.
1870 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1871 llvm::SwitchInst *FinallySwitch =
1872 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1873 FinallyEnd, 10, FinallyJump);
1874
1875 // Push an EH context entry, used for handling rethrows and jumps
1876 // through finally.
1877 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1878 FinallySwitch, DestCode);
1879 CGF.ObjCEHStack.push_back(&EHEntry);
1880
1881 // Allocate memory for the exception data and rethrow pointer.
1882 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1883 "exceptiondata.ptr");
1884 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1885 "_rethrow");
1886 // Call objc_sync_enter(sync.expr)
1887 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1888 CGF.EmitScalarExpr(S.getSynchExpr()));
1889
1890 // Enter a new try block and call setjmp.
1891 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1892 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1893 "jmpbufarray");
1894 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1895 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1896 JmpBufPtr, "result");
1897
1898 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1899 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1900 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1901 TryHandler, TryBlock);
1902
1903 // Emit the @try block.
1904 CGF.EmitBlock(TryBlock);
1905 CGF.EmitStmt(S.getSynchBody());
1906 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1907
1908 // Emit the "exception in @try" block.
1909 CGF.EmitBlock(TryHandler);
1910
1911 // Retrieve the exception object. We may emit multiple blocks but
1912 // nothing can cross this so the value is already in SSA form.
1913 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1914 ExceptionData,
1915 "caught");
1916 EHEntry.Exception = Caught;
1917 CGF.Builder.CreateStore(Caught, RethrowPtr);
1918 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1919
1920 // Pop the exception-handling stack entry. It is important to do
1921 // this now, because the code in the @finally block is not in this
1922 // context.
1923 CGF.ObjCEHStack.pop_back();
1924
1925 // Emit the @finally block.
1926 CGF.EmitBlock(FinallyBlock);
1927 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1928
1929 CGF.EmitBlock(FinallyNoExit);
1930 // objc_sync_exit(expr); As finally's sole statement.
1931 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1932 CGF.EmitScalarExpr(S.getSynchExpr()));
1933
1934 CGF.EmitBlock(FinallyJump);
1935
1936 CGF.EmitBlock(FinallyRethrow);
1937 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1938 CGF.Builder.CreateLoad(RethrowPtr));
1939 CGF.Builder.CreateUnreachable();
1940
1941 CGF.EmitBlock(FinallyEnd);
1942}
1943
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001944/* *** Private Interface *** */
1945
1946/// EmitImageInfo - Emit the image info marker used to encode some module
1947/// level information.
1948///
1949/// See: <rdr://4810609&4810587&4810587>
1950/// struct IMAGE_INFO {
1951/// unsigned version;
1952/// unsigned flags;
1953/// };
1954enum ImageInfoFlags {
1955 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1956 eImageInfo_GarbageCollected = (1 << 1),
1957 eImageInfo_GCOnly = (1 << 2)
1958};
1959
1960void CGObjCMac::EmitImageInfo() {
1961 unsigned version = 0; // Version is unused?
1962 unsigned flags = 0;
1963
1964 // FIXME: Fix and continue?
1965 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1966 flags |= eImageInfo_GarbageCollected;
1967 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1968 flags |= eImageInfo_GCOnly;
1969
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001970 // Emitted as int[2];
1971 llvm::Constant *values[2] = {
1972 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1973 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1974 };
1975 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001976 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001977 new llvm::GlobalVariable(AT, true,
1978 llvm::GlobalValue::InternalLinkage,
1979 llvm::ConstantArray::get(AT, values, 2),
1980 "\01L_OBJC_IMAGE_INFO",
1981 &CGM.getModule());
1982
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001983 if (ObjCABI == 1) {
1984 GV->setSection("__OBJC, __image_info,regular");
1985 } else {
1986 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1987 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001988
1989 UsedGlobals.push_back(GV);
1990}
1991
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001992
1993// struct objc_module {
1994// unsigned long version;
1995// unsigned long size;
1996// const char *name;
1997// Symtab symtab;
1998// };
1999
2000// FIXME: Get from somewhere
2001static const int ModuleVersion = 7;
2002
2003void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002004 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
2005
2006 std::vector<llvm::Constant*> Values(4);
2007 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2008 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002009 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002010 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002011 Values[3] = EmitModuleSymbols();
2012
2013 llvm::GlobalVariable *GV =
2014 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2015 llvm::GlobalValue::InternalLinkage,
2016 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2017 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002018 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002019 &CGM.getModule());
2020 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2021 UsedGlobals.push_back(GV);
2022}
2023
2024llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002025 unsigned NumClasses = DefinedClasses.size();
2026 unsigned NumCategories = DefinedCategories.size();
2027
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002028 // Return null if no symbols were defined.
2029 if (!NumClasses && !NumCategories)
2030 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2031
2032 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002033 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2034 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2035 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2036 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2037
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002038 // The runtime expects exactly the list of defined classes followed
2039 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002040 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002041 for (unsigned i=0; i<NumClasses; i++)
2042 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2043 ObjCTypes.Int8PtrTy);
2044 for (unsigned i=0; i<NumCategories; i++)
2045 Symbols[NumClasses + i] =
2046 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2047 ObjCTypes.Int8PtrTy);
2048
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002049 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002050 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002051 NumClasses + NumCategories),
2052 Symbols);
2053
2054 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2055
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002056 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002057 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002058 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002059 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002060 "\01L_OBJC_SYMBOLS",
2061 &CGM.getModule());
2062 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2063 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002064 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2065}
2066
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002067llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002068 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002069 LazySymbols.insert(ID->getIdentifier());
2070
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002071 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2072
2073 if (!Entry) {
2074 llvm::Constant *Casted =
2075 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2076 ObjCTypes.ClassPtrTy);
2077 Entry =
2078 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2079 llvm::GlobalValue::InternalLinkage,
2080 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2081 &CGM.getModule());
2082 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2083 UsedGlobals.push_back(Entry);
2084 }
2085
2086 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002087}
2088
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002089llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002090 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2091
2092 if (!Entry) {
2093 llvm::Constant *Casted =
2094 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2095 ObjCTypes.SelectorPtrTy);
2096 Entry =
2097 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2098 llvm::GlobalValue::InternalLinkage,
2099 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2100 &CGM.getModule());
2101 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2102 UsedGlobals.push_back(Entry);
2103 }
2104
2105 return Builder.CreateLoad(Entry, false, "tmp");
2106}
2107
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002108llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2109 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002110
2111 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002112 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002113 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002114 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002115 llvm::GlobalValue::InternalLinkage,
2116 C, "\01L_OBJC_CLASS_NAME_",
2117 &CGM.getModule());
2118 Entry->setSection("__TEXT,__cstring,cstring_literals");
2119 UsedGlobals.push_back(Entry);
2120 }
2121
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002122 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002123}
2124
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002125llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2126 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2127
2128 if (!Entry) {
2129 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2130 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002131 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002132 llvm::GlobalValue::InternalLinkage,
2133 C, "\01L_OBJC_METH_VAR_NAME_",
2134 &CGM.getModule());
2135 Entry->setSection("__TEXT,__cstring,cstring_literals");
2136 UsedGlobals.push_back(Entry);
2137 }
2138
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002139 return getConstantGEP(Entry, 0, 0);
2140}
2141
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002142// FIXME: Merge into a single cstring creation function.
2143llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2144 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2145}
2146
2147// FIXME: Merge into a single cstring creation function.
2148llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2149 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2150}
2151
2152llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2153 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002154
2155 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002156 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002157 Entry =
2158 new llvm::GlobalVariable(C->getType(), false,
2159 llvm::GlobalValue::InternalLinkage,
2160 C, "\01L_OBJC_METH_VAR_TYPE_",
2161 &CGM.getModule());
2162 Entry->setSection("__TEXT,__cstring,cstring_literals");
2163 UsedGlobals.push_back(Entry);
2164 }
2165
2166 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002167}
2168
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002169// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002170llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002171 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002172 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2173 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002174 return GetMethodVarType(TypeStr);
2175}
2176
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002177// FIXME: Merge into a single cstring creation function.
2178llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2179 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2180
2181 if (!Entry) {
2182 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2183 Entry =
2184 new llvm::GlobalVariable(C->getType(), false,
2185 llvm::GlobalValue::InternalLinkage,
2186 C, "\01L_OBJC_PROP_NAME_ATTR_",
2187 &CGM.getModule());
2188 Entry->setSection("__TEXT,__cstring,cstring_literals");
2189 UsedGlobals.push_back(Entry);
2190 }
2191
2192 return getConstantGEP(Entry, 0, 0);
2193}
2194
2195// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002196// FIXME: This Decl should be more precise.
2197llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2198 const Decl *Container) {
2199 std::string TypeStr;
2200 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002201 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2202}
2203
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002204void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2205 std::string &NameOut) {
2206 // FIXME: Find the mangling GCC uses.
2207 std::stringstream s;
2208 s << (D->isInstance() ? "-" : "+");
2209 s << "[";
2210 s << D->getClassInterface()->getName();
2211 s << " ";
2212 s << D->getSelector().getName();
2213 s << "]";
2214 NameOut = s.str();
2215}
2216
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002217void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002218 EmitModuleInfo();
2219
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002220 // Emit the dummy bodies for any protocols which were referenced but
2221 // never defined.
2222 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2223 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2224 if (i->second->hasInitializer())
2225 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002226
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002227 std::vector<llvm::Constant*> Values(5);
2228 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2229 Values[1] = GetClassName(i->first);
2230 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2231 Values[3] = Values[4] =
2232 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2233 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2234 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2235 Values));
2236 }
2237
2238 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002239 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002240 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002241 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002242 }
2243
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002244 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002245 llvm::GlobalValue *GV =
2246 new llvm::GlobalVariable(AT, false,
2247 llvm::GlobalValue::AppendingLinkage,
2248 llvm::ConstantArray::get(AT, Used),
2249 "llvm.used",
2250 &CGM.getModule());
2251
2252 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002253
2254 // Add assembler directives to add lazy undefined symbol references
2255 // for classes which are referenced but not defined. This is
2256 // important for correct linker interaction.
2257
2258 // FIXME: Uh, this isn't particularly portable.
2259 std::stringstream s;
2260 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2261 e = LazySymbols.end(); i != e; ++i) {
2262 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2263 }
2264 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2265 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002266 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002267 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2268 }
2269 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002270}
2271
2272/* *** */
2273
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002274ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002275 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002276{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002277 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2278 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002279
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002280 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002281 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002282 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002283 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2284
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002285 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002286 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002287 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002288
2289 // FIXME: It would be nice to unify this with the opaque type, so
2290 // that the IR comes out a bit cleaner.
2291 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2292 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002293
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002294 MethodDescriptionTy =
2295 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002296 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002297 NULL);
2298 CGM.getModule().addTypeName("struct._objc_method_description",
2299 MethodDescriptionTy);
2300
2301 MethodDescriptionListTy =
2302 llvm::StructType::get(IntTy,
2303 llvm::ArrayType::get(MethodDescriptionTy, 0),
2304 NULL);
2305 CGM.getModule().addTypeName("struct._objc_method_description_list",
2306 MethodDescriptionListTy);
2307 MethodDescriptionListPtrTy =
2308 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2309
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002310 PropertyTy = llvm::StructType::get(Int8PtrTy,
2311 Int8PtrTy,
2312 NULL);
2313 CGM.getModule().addTypeName("struct._objc_property",
2314 PropertyTy);
2315
2316 PropertyListTy = llvm::StructType::get(IntTy,
2317 IntTy,
2318 llvm::ArrayType::get(PropertyTy, 0),
2319 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002320 CGM.getModule().addTypeName("struct._objc_property_list",
2321 PropertyListTy);
2322 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2323
2324 // Protocol description structures
2325
2326 ProtocolExtensionTy =
2327 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2328 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2329 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2330 PropertyListPtrTy,
2331 NULL);
2332 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2333 ProtocolExtensionTy);
2334 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2335
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002336 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002337
2338 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2339 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2340
2341 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2342 LongTy,
2343 llvm::ArrayType::get(ProtocolTyHolder, 0),
2344 NULL);
2345 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2346
2347 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002348 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002349 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2350 MethodDescriptionListPtrTy,
2351 MethodDescriptionListPtrTy,
2352 NULL);
2353 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2354
2355 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2356 CGM.getModule().addTypeName("struct._objc_protocol_list",
2357 ProtocolListTy);
2358 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2359
2360 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2361 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2362 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002363
2364 // Class description structures
2365
2366 IvarTy = llvm::StructType::get(Int8PtrTy,
2367 Int8PtrTy,
2368 IntTy,
2369 NULL);
2370 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2371
2372 IvarListTy = llvm::OpaqueType::get();
2373 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2374 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2375
2376 MethodTy = llvm::StructType::get(SelectorPtrTy,
2377 Int8PtrTy,
2378 Int8PtrTy,
2379 NULL);
2380 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2381
2382 MethodListTy = llvm::OpaqueType::get();
2383 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2384 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2385
2386 CacheTy = llvm::OpaqueType::get();
2387 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2388 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2389
2390 ClassExtensionTy =
2391 llvm::StructType::get(IntTy,
2392 Int8PtrTy,
2393 PropertyListPtrTy,
2394 NULL);
2395 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2396 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2397
2398 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2399
2400 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2401 llvm::PointerType::getUnqual(ClassTyHolder),
2402 Int8PtrTy,
2403 LongTy,
2404 LongTy,
2405 LongTy,
2406 IvarListPtrTy,
2407 MethodListPtrTy,
2408 CachePtrTy,
2409 ProtocolListPtrTy,
2410 Int8PtrTy,
2411 ClassExtensionPtrTy,
2412 NULL);
2413 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2414
2415 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2416 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2417 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2418
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002419 CategoryTy = llvm::StructType::get(Int8PtrTy,
2420 Int8PtrTy,
2421 MethodListPtrTy,
2422 MethodListPtrTy,
2423 ProtocolListPtrTy,
2424 IntTy,
2425 PropertyListPtrTy,
2426 NULL);
2427 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2428
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002429 // I'm not sure I like this. The implicit coordination is a bit
2430 // gross. We should solve this in a reasonable fashion because this
2431 // is a pretty common task (match some runtime data structure with
2432 // an LLVM data structure).
2433
2434 // FIXME: This is leaked.
2435 // FIXME: Merge with rewriter code?
2436 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2437 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002438 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002439 FieldDecl *FieldDecls[2];
2440 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2441 Ctx.getObjCIdType());
2442 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2443 Ctx.getObjCClassType());
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002444 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002445
2446 SuperCTy = Ctx.getTagDeclType(RD);
2447 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2448
2449 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002450 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002451
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002452 // Global metadata structures
2453
2454 SymtabTy = llvm::StructType::get(LongTy,
2455 SelectorPtrTy,
2456 ShortTy,
2457 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002458 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002459 NULL);
2460 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2461 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2462
2463 ModuleTy =
2464 llvm::StructType::get(LongTy,
2465 LongTy,
2466 Int8PtrTy,
2467 SymtabPtrTy,
2468 NULL);
2469 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002470
Daniel Dunbar49f66022008-09-24 03:38:44 +00002471 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002472
2473 std::vector<const llvm::Type*> Params;
2474 Params.push_back(ObjectPtrTy);
2475 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002476 MessageSendFn =
2477 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2478 Params,
2479 true),
2480 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002481
2482 Params.clear();
2483 Params.push_back(Int8PtrTy);
2484 Params.push_back(ObjectPtrTy);
2485 Params.push_back(SelectorPtrTy);
2486 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002487 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2488 Params,
2489 true),
2490 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002491
2492 Params.clear();
2493 Params.push_back(ObjectPtrTy);
2494 Params.push_back(SelectorPtrTy);
2495 // FIXME: This should be long double on x86_64?
2496 MessageSendFpretFn =
2497 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2498 Params,
2499 true),
2500 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002501
2502 Params.clear();
2503 Params.push_back(SuperPtrTy);
2504 Params.push_back(SelectorPtrTy);
2505 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002506 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2507 Params,
2508 true),
2509 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002510
2511 Params.clear();
2512 Params.push_back(Int8PtrTy);
2513 Params.push_back(SuperPtrTy);
2514 Params.push_back(SelectorPtrTy);
2515 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002516 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2517 Params,
2518 true),
2519 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002520
2521 // There is no objc_msgSendSuper_fpret? How can that work?
2522 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002523
Daniel Dunbar49f66022008-09-24 03:38:44 +00002524 // Property manipulation functions.
2525
2526 Params.clear();
2527 Params.push_back(ObjectPtrTy);
2528 Params.push_back(SelectorPtrTy);
2529 Params.push_back(LongTy);
2530 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2531 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002532 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2533 Params,
2534 false),
2535 "objc_getProperty");
2536
Daniel Dunbar49f66022008-09-24 03:38:44 +00002537 Params.clear();
2538 Params.push_back(ObjectPtrTy);
2539 Params.push_back(SelectorPtrTy);
2540 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002541 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002542 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2543 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2544 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002545 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2546 Params,
2547 false),
2548 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002549
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002550 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002551
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002552 Params.clear();
2553 Params.push_back(ObjectPtrTy);
2554 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002555 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2556 Params,
2557 false),
2558 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002559
2560 // FIXME: This is the size of the setjmp buffer and should be
2561 // target specific. 18 is what's used on 32-bit X86.
2562 uint64_t SetJmpBufferSize = 18;
2563
2564 // Exceptions
2565 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002566 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002567
2568 ExceptionDataTy =
2569 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2570 SetJmpBufferSize),
2571 StackPtrTy, NULL);
2572 CGM.getModule().addTypeName("struct._objc_exception_data",
2573 ExceptionDataTy);
2574
2575 Params.clear();
2576 Params.push_back(ObjectPtrTy);
2577 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002578 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2579 Params,
2580 false),
2581 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002582
2583 Params.clear();
2584 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2585 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002586 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2587 Params,
2588 false),
2589 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002590 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2592 Params,
2593 false),
2594 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002595 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2597 Params,
2598 false),
2599 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002600
2601 Params.clear();
2602 Params.push_back(ClassPtrTy);
2603 Params.push_back(ObjectPtrTy);
2604 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002605 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2606 Params,
2607 false),
2608 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002609
2610 // synchronized APIs
2611 // void objc_sync_enter (id)
2612 Params.clear();
2613 Params.push_back(ObjectPtrTy);
2614 SyncEnterFn =
2615 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2616 Params,
2617 false),
2618 "objc_sync_enter");
2619 // void objc_sync_exit (id)
2620 SyncExitFn =
2621 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2622 Params,
2623 false),
2624 "objc_sync_exit");
2625
Anders Carlsson124526b2008-09-09 10:10:21 +00002626
2627 Params.clear();
2628 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2629 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002630 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2631 Params,
2632 false),
2633 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002634
2635 // gc's API
2636 // id objc_read_weak (id *)
2637 Params.clear();
2638 Params.push_back(PtrObjectPtrTy);
2639 GcReadWeakFn =
2640 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2641 Params,
2642 false),
2643 "objc_read_weak");
2644 // id objc_assign_weak (id, id *)
2645 Params.clear();
2646 Params.push_back(ObjectPtrTy);
2647 Params.push_back(PtrObjectPtrTy);
2648 GcAssignWeakFn =
2649 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2650 Params,
2651 false),
2652 "objc_assign_weak");
2653 GcAssignGlobalFn =
2654 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2655 Params,
2656 false),
2657 "objc_assign_global");
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002658 GcAssignIvarFn =
2659 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2660 Params,
2661 false),
2662 "objc_assign_ivar");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002663 GcAssignStrongCastFn =
2664 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2665 Params,
2666 false),
2667 "objc_assign_strongCast");
2668
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002669}
2670
2671ObjCTypesHelper::~ObjCTypesHelper() {
2672}
2673
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002674/* *** */
2675
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002676CodeGen::CGObjCRuntime *
2677CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002678 return new CGObjCMac(CGM);
2679}