blob: e6c2650a2e82aa79cbac3970ca17d4520c87550c [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
178 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
179 llvm::Function *GcAssignStrongCastFn;
180
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000181public:
182 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
183 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000184
185
186 llvm::Function *getSendFn(bool IsSuper) {
187 return IsSuper ? MessageSendSuperFn : MessageSendFn;
188 }
189
190 llvm::Function *getSendStretFn(bool IsSuper) {
191 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
192 }
193
194 llvm::Function *getSendFpretFn(bool IsSuper) {
195 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
196 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000197};
198
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000199class CGObjCMac : public CodeGen::CGObjCRuntime {
200private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000201 CodeGen::CodeGenModule &CGM;
202 ObjCTypesHelper ObjCTypes;
203 /// ObjCABI - FIXME: Not sure yet.
204 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000205
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000206 /// LazySymbols - Symbols to generate a lazy reference for. See
207 /// DefinedSymbols and FinishModule().
208 std::set<IdentifierInfo*> LazySymbols;
209
210 /// DefinedSymbols - External symbols which are defined by this
211 /// module. The symbols in this list and LazySymbols are used to add
212 /// special linker symbols which ensure that Objective-C modules are
213 /// linked properly.
214 std::set<IdentifierInfo*> DefinedSymbols;
215
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000216 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000217 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000218
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000219 /// MethodVarNames - uniqued method variable names.
220 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
221
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000222 /// MethodVarTypes - uniqued method type signatures. We have to use
223 /// a StringMap here because have no other unique reference.
224 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
225
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000226 /// MethodDefinitions - map of methods which have been defined in
227 /// this translation unit.
228 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
229
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000230 /// PropertyNames - uniqued method variable names.
231 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
232
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000233 /// ClassReferences - uniqued class references.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
235
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000236 /// SelectorReferences - uniqued selector references.
237 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
238
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000239 /// Protocols - Protocols for which an objc_protocol structure has
240 /// been emitted. Forward declarations are handled by creating an
241 /// empty structure whose initializer is filled in when/if defined.
242 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
243
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000244 /// DefinedProtocols - Protocols which have actually been
245 /// defined. We should not need this, see FIXME in GenerateProtocol.
246 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
247
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000248 /// DefinedClasses - List of defined classes.
249 std::vector<llvm::GlobalValue*> DefinedClasses;
250
251 /// DefinedCategories - List of defined categories.
252 std::vector<llvm::GlobalValue*> DefinedCategories;
253
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000254 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000255 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000256 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000257
258 /// EmitImageInfo - Emit the image info marker used to encode some module
259 /// level information.
260 void EmitImageInfo();
261
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000262 /// EmitModuleInfo - Another marker encoding module level
263 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000264 void EmitModuleInfo();
265
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000266 /// EmitModuleSymols - Emit module symbols, the list of defined
267 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000268 llvm::Constant *EmitModuleSymbols();
269
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000270 /// FinishModule - Write out global data structures at the end of
271 /// processing a translation unit.
272 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000273
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000274 /// EmitClassExtension - Generate the class extension structure used
275 /// to store the weak ivar layout and properties. The return value
276 /// has type ClassExtensionPtrTy.
277 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
278
279 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
280 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000281 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000282 const ObjCInterfaceDecl *ID);
283
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000284 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000285 QualType ResultType,
286 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000287 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000288 QualType Arg0Ty,
289 bool IsSuper,
290 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000291
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000292 /// EmitIvarList - Emit the ivar list for the given
293 /// implementation. If ForClass is true the list of class ivars
294 /// (i.e. metaclass ivars) is emitted, otherwise the list of
295 /// interface ivars will be emitted. The return value has type
296 /// IvarListPtrTy.
297 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
298 bool ForClass,
299 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000300
301 /// EmitMetaClass - Emit a forward reference to the class structure
302 /// for the metaclass of the given interface. The return value has
303 /// type ClassPtrTy.
304 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
305
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000306 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000307 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000308 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
309 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000310 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000311 const ConstantVector &Methods);
312
313 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
314
315 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000316
317 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000318 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000319 llvm::Constant *EmitMethodList(const std::string &Name,
320 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000321 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000322
323 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000324 /// method declarations.
325 /// - TypeName: The name for the type containing the methods.
326 /// - IsProtocol: True iff these methods are for a protocol.
327 /// - ClassMethds: True iff these are class methods.
328 /// - Required: When true, only "required" methods are
329 /// listed. Similarly, when false only "optional" methods are
330 /// listed. For classes this should always be true.
331 /// - begin, end: The method list to output.
332 ///
333 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000334 llvm::Constant *EmitMethodDescList(const std::string &Name,
335 const char *Section,
336 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000337
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000338 /// EmitPropertyList - Emit the given property list. The return
339 /// value has type PropertyListPtrTy.
340 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000341 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000342 ObjCPropertyDecl * const *begin,
343 ObjCPropertyDecl * const *end);
344
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000345 /// GetOrEmitProtocol - Get the protocol object for the given
346 /// declaration, emitting it if necessary. The return value has type
347 /// ProtocolPtrTy.
348 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
349
350 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
351 /// object for the given declaration, emitting it if needed. These
352 /// forward references will be filled in with empty bodies if no
353 /// definition is seen. The return value has type ProtocolPtrTy.
354 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
355
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000356 /// EmitProtocolExtension - Generate the protocol extension
357 /// structure used to store optional instance and class methods, and
358 /// protocol properties. The return value has type
359 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000360 llvm::Constant *
361 EmitProtocolExtension(const ObjCProtocolDecl *PD,
362 const ConstantVector &OptInstanceMethods,
363 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000364
365 /// EmitProtocolList - Generate the list of referenced
366 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000367 llvm::Constant *EmitProtocolList(const std::string &Name,
368 ObjCProtocolDecl::protocol_iterator begin,
369 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000370
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000371 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
372 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000373 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000374
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000375 /// GetProtocolRef - Return a reference to the internal protocol
376 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000377 /// defined. The return value has type ProtocolPtrTy.
378 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000379
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000380 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000381 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000383
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000384 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000385 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000387 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000389
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000390 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000391 /// selector's name. The return value has type char *.
392
393 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000394 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000395 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000396
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000397 /// GetPropertyName - Return a unique constant for the given
398 /// name. The return value has type char *.
399 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
400
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000401 // FIXME: This can be dropped once string functions are unified.
402 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
403 const Decl *Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000404
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000405 /// GetNameForMethod - Return a name for the given method.
406 /// \param[out] NameOut - The return value.
407 void GetNameForMethod(const ObjCMethodDecl *OMD,
408 std::string &NameOut);
409
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000410public:
411 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000412 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000413
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000414 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000415 QualType ResultType,
416 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000417 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000418 bool IsClassMessage,
419 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000420
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000421 virtual CodeGen::RValue
422 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000423 QualType ResultType,
424 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000425 const ObjCInterfaceDecl *Class,
426 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000427 bool IsClassMessage,
428 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000429
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000430 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000431 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000432
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000434
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000435 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000436
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000437 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000438
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000439 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000440
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000441 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000442 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000443
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000444 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000445
446 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000447 virtual llvm::Function *GetPropertyGetFunction();
448 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000449 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000450
451 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
452 const ObjCAtTryStmt &S);
453 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
454 const ObjCAtThrowStmt &S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000455 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456 const ObjCAtSynchronizedStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000457 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000458 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000459 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
460 llvm::Value *src, llvm::Value *dst);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000461};
462} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000463
464/* *** Helper Functions *** */
465
466/// getConstantGEP() - Help routine to construct simple GEPs.
467static llvm::Constant *getConstantGEP(llvm::Constant *C,
468 unsigned idx0,
469 unsigned idx1) {
470 llvm::Value *Idxs[] = {
471 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
472 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
473 };
474 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
475}
476
477/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000478
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000479CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
480 : CGM(cgm),
481 ObjCTypes(cgm),
482 ObjCABI(1)
483{
484 // FIXME: How does this get set in GCC? And what does it even mean?
485 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
486 ObjCABI = 2;
487
488 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000489}
490
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000491/// GetClass - Return a reference to the class for the given interface
492/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000493llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000494 const ObjCInterfaceDecl *ID) {
495 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000496}
497
498/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000499llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000500 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000501}
502
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000503/// Generate a constant CFString object.
504/*
505 struct __builtin_CFString {
506 const int *isa; // point to __CFConstantStringClassReference
507 int flags;
508 const char *str;
509 long length;
510 };
511*/
512
513llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000514 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000515}
516
517/// Generates a message send where the super is the receiver. This is
518/// a message send to self with special delivery semantics indicating
519/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000520CodeGen::RValue
521CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000522 QualType ResultType,
523 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000524 const ObjCInterfaceDecl *Class,
525 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000526 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000527 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000528 // Create and init a super structure; this is a (receiver, class)
529 // pair we will pass to objc_msgSendSuper.
530 llvm::Value *ObjCSuper =
531 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
532 llvm::Value *ReceiverAsObject =
533 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
534 CGF.Builder.CreateStore(ReceiverAsObject,
535 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000536
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000537 // If this is a class message the metaclass is passed as the target.
538 llvm::Value *Target;
539 if (IsClassMessage) {
540 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
541 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
542 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
543 Target = Super;
544 } else {
545 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
546 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000547 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
548 // and ObjCTypes types.
549 const llvm::Type *ClassTy =
550 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000551 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000552 CGF.Builder.CreateStore(Target,
553 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
554
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000555 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000556 ObjCSuper, ObjCTypes.SuperPtrCTy,
557 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000558}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000559
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000560/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000561CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000562 QualType ResultType,
563 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000564 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000565 bool IsClassMessage,
566 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567 llvm::Value *Arg0 =
568 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000569 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000570 Arg0, CGF.getContext().getObjCIdType(),
571 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000572}
573
574CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000575 QualType ResultType,
576 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000577 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000578 QualType Arg0Ty,
579 bool IsSuper,
580 const CallArgList &CallArgs) {
581 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000582 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
583 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
584 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000585 CGF.getContext().getObjCSelType()));
586 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000587
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000588 const llvm::FunctionType *FTy =
589 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
590 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000591
592 llvm::Constant *Fn;
593 if (CGM.ReturnTypeUsesSret(ResultType)) {
594 Fn = ObjCTypes.getSendStretFn(IsSuper);
595 } else if (ResultType->isFloatingType()) {
596 // FIXME: Sadly, this is wrong. This actually depends on the
597 // architecture. This happens to be right for x86-32 though.
598 Fn = ObjCTypes.getSendFpretFn(IsSuper);
599 } else {
600 Fn = ObjCTypes.getSendFn(IsSuper);
601 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000602 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000603 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000604}
605
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000606llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000607 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000608 // FIXME: I don't understand why gcc generates this, or where it is
609 // resolved. Investigate. Its also wasteful to look this up over and
610 // over.
611 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
612
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000613 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
614 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000615}
616
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000617void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
618 // FIXME: We shouldn't need this, the protocol decl should contain
619 // enough information to tell us whether this was a declaration or a
620 // definition.
621 DefinedProtocols.insert(PD->getIdentifier());
622
623 // If we have generated a forward reference to this protocol, emit
624 // it now. Otherwise do nothing, the protocol objects are lazily
625 // emitted.
626 if (Protocols.count(PD->getIdentifier()))
627 GetOrEmitProtocol(PD);
628}
629
630llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
631 if (DefinedProtocols.count(PD->getIdentifier()))
632 return GetOrEmitProtocol(PD);
633 return GetOrEmitProtocolRef(PD);
634}
635
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000636/*
637 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
638 struct _objc_protocol {
639 struct _objc_protocol_extension *isa;
640 char *protocol_name;
641 struct _objc_protocol_list *protocol_list;
642 struct _objc__method_prototype_list *instance_methods;
643 struct _objc__method_prototype_list *class_methods
644 };
645
646 See EmitProtocolExtension().
647*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000648llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
649 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
650
651 // Early exit if a defining object has already been generated.
652 if (Entry && Entry->hasInitializer())
653 return Entry;
654
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000655 // FIXME: I don't understand why gcc generates this, or where it is
656 // resolved. Investigate. Its also wasteful to look this up over and
657 // over.
658 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
659
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000660 const char *ProtocolName = PD->getIdentifierName();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000661
662 // Construct method lists.
663 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
664 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
665 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
666 e = PD->instmeth_end(); i != e; ++i) {
667 ObjCMethodDecl *MD = *i;
668 llvm::Constant *C = GetMethodDescriptionConstant(MD);
669 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
670 OptInstanceMethods.push_back(C);
671 } else {
672 InstanceMethods.push_back(C);
673 }
674 }
675
676 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
677 e = PD->classmeth_end(); i != e; ++i) {
678 ObjCMethodDecl *MD = *i;
679 llvm::Constant *C = GetMethodDescriptionConstant(MD);
680 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
681 OptClassMethods.push_back(C);
682 } else {
683 ClassMethods.push_back(C);
684 }
685 }
686
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000687 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000688 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000689 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000690 Values[2] =
691 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
692 PD->protocol_begin(),
693 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000694 Values[3] =
695 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
696 + PD->getName(),
697 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
698 InstanceMethods);
699 Values[4] =
700 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
701 + PD->getName(),
702 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
703 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000704 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
705 Values);
706
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000707 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000708 // Already created, fix the linkage and update the initializer.
709 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000710 Entry->setInitializer(Init);
711 } else {
712 Entry =
713 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
714 llvm::GlobalValue::InternalLinkage,
715 Init,
716 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
717 &CGM.getModule());
718 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
719 UsedGlobals.push_back(Entry);
720 // FIXME: Is this necessary? Why only for protocol?
721 Entry->setAlignment(4);
722 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000723
724 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000725}
726
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000727llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000728 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
729
730 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000731 // We use the initializer as a marker of whether this is a forward
732 // reference or not. At module finalization we add the empty
733 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000734 Entry =
735 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000736 llvm::GlobalValue::ExternalLinkage,
737 0,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000738 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
739 &CGM.getModule());
740 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
741 UsedGlobals.push_back(Entry);
742 // FIXME: Is this necessary? Why only for protocol?
743 Entry->setAlignment(4);
744 }
745
746 return Entry;
747}
748
749/*
750 struct _objc_protocol_extension {
751 uint32_t size;
752 struct objc_method_description_list *optional_instance_methods;
753 struct objc_method_description_list *optional_class_methods;
754 struct objc_property_list *instance_properties;
755 };
756*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000757llvm::Constant *
758CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
759 const ConstantVector &OptInstanceMethods,
760 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000761 uint64_t Size =
762 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
763 std::vector<llvm::Constant*> Values(4);
764 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000765 Values[1] =
766 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
767 + PD->getName(),
768 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
769 OptInstanceMethods);
770 Values[2] =
771 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
772 + PD->getName(),
773 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
774 OptClassMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000775 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
776 PD->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000777 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000778 PD->classprop_begin(),
779 PD->classprop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000780
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000781 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000782 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
783 Values[3]->isNullValue())
784 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
785
786 llvm::Constant *Init =
787 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
788 llvm::GlobalVariable *GV =
789 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
790 llvm::GlobalValue::InternalLinkage,
791 Init,
792 (std::string("\01L_OBJC_PROTOCOLEXT_") +
793 PD->getName()),
794 &CGM.getModule());
795 // No special section, but goes in llvm.used
796 UsedGlobals.push_back(GV);
797
798 return GV;
799}
800
801/*
802 struct objc_protocol_list {
803 struct objc_protocol_list *next;
804 long count;
805 Protocol *list[];
806 };
807*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000808llvm::Constant *
809CGObjCMac::EmitProtocolList(const std::string &Name,
810 ObjCProtocolDecl::protocol_iterator begin,
811 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000812 std::vector<llvm::Constant*> ProtocolRefs;
813
Daniel Dunbardbc933702008-08-21 21:57:41 +0000814 for (; begin != end; ++begin)
815 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000816
817 // Just return null for empty protocol lists
818 if (ProtocolRefs.empty())
819 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
820
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000821 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000822 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
823
824 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000825 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000826 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
827 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
828 Values[2] =
829 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
830 ProtocolRefs.size()),
831 ProtocolRefs);
832
833 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
834 llvm::GlobalVariable *GV =
835 new llvm::GlobalVariable(Init->getType(), false,
836 llvm::GlobalValue::InternalLinkage,
837 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000838 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000839 &CGM.getModule());
840 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
841 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
842}
843
844/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000845 struct _objc_property {
846 const char * const name;
847 const char * const attributes;
848 };
849
850 struct _objc_property_list {
851 uint32_t entsize; // sizeof (struct _objc_property)
852 uint32_t prop_count;
853 struct _objc_property[prop_count];
854 };
855*/
856llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000857 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000858 ObjCPropertyDecl * const *begin,
859 ObjCPropertyDecl * const *end) {
860 std::vector<llvm::Constant*> Properties, Prop(2);
861 for (; begin != end; ++begin) {
862 const ObjCPropertyDecl *PD = *begin;
863 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000864 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000865 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
866 Prop));
867 }
868
869 // Return null for empty list.
870 if (Properties.empty())
871 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
872
873 unsigned PropertySize =
874 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
875 std::vector<llvm::Constant*> Values(3);
876 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
877 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
878 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
879 Properties.size());
880 Values[2] = llvm::ConstantArray::get(AT, Properties);
881 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
882
883 llvm::GlobalVariable *GV =
884 new llvm::GlobalVariable(Init->getType(), false,
885 llvm::GlobalValue::InternalLinkage,
886 Init,
887 Name,
888 &CGM.getModule());
889 // No special section on property lists?
890 UsedGlobals.push_back(GV);
891 return llvm::ConstantExpr::getBitCast(GV,
892 ObjCTypes.PropertyListPtrTy);
893
894}
895
896/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000897 struct objc_method_description_list {
898 int count;
899 struct objc_method_description list[];
900 };
901*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000902llvm::Constant *
903CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
904 std::vector<llvm::Constant*> Desc(2);
905 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
906 ObjCTypes.SelectorPtrTy);
907 Desc[1] = GetMethodVarType(MD);
908 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
909 Desc);
910}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000911
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000912llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
913 const char *Section,
914 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000915 // Return null for empty list.
916 if (Methods.empty())
917 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
918
919 std::vector<llvm::Constant*> Values(2);
920 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
921 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
922 Methods.size());
923 Values[1] = llvm::ConstantArray::get(AT, Methods);
924 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
925
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000926 llvm::GlobalVariable *GV =
927 new llvm::GlobalVariable(Init->getType(), false,
928 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000929 Init, Name, &CGM.getModule());
930 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000931 UsedGlobals.push_back(GV);
932 return llvm::ConstantExpr::getBitCast(GV,
933 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000934}
935
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000936/*
937 struct _objc_category {
938 char *category_name;
939 char *class_name;
940 struct _objc_method_list *instance_methods;
941 struct _objc_method_list *class_methods;
942 struct _objc_protocol_list *protocols;
943 uint32_t size; // <rdar://4585769>
944 struct _objc_property_list *instance_properties;
945 };
946 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000947void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000948 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
949
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000950 // FIXME: This is poor design, the OCD should have a pointer to the
951 // category decl. Additionally, note that Category can be null for
952 // the @implementation w/o an @interface case. Sema should just
953 // create one for us as it does for @implementation so everyone else
954 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000955 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000956 const ObjCCategoryDecl *Category =
957 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000958 std::string ExtName(std::string(Interface->getName()) +
959 "_" +
960 OCD->getName());
961
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000962 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
963 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
964 e = OCD->instmeth_end(); i != e; ++i) {
965 // Instance methods should always be defined.
966 InstanceMethods.push_back(GetMethodConstant(*i));
967 }
968 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
969 e = OCD->classmeth_end(); i != e; ++i) {
970 // Class methods should always be defined.
971 ClassMethods.push_back(GetMethodConstant(*i));
972 }
973
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000974 std::vector<llvm::Constant*> Values(7);
975 Values[0] = GetClassName(OCD->getIdentifier());
976 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000977 Values[2] =
978 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
979 ExtName,
980 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000981 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000982 Values[3] =
983 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
984 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000985 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000986 if (Category) {
987 Values[4] =
988 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
989 Category->protocol_begin(),
990 Category->protocol_end());
991 } else {
992 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
993 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000994 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000995
996 // If there is no category @interface then there can be no properties.
997 if (Category) {
998 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000999 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001000 Category->classprop_begin(),
1001 Category->classprop_end());
1002 } else {
1003 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1004 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001005
1006 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1007 Values);
1008
1009 llvm::GlobalVariable *GV =
1010 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1011 llvm::GlobalValue::InternalLinkage,
1012 Init,
1013 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1014 &CGM.getModule());
1015 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1016 UsedGlobals.push_back(GV);
1017 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001018}
1019
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001020// FIXME: Get from somewhere?
1021enum ClassFlags {
1022 eClassFlags_Factory = 0x00001,
1023 eClassFlags_Meta = 0x00002,
1024 // <rdr://5142207>
1025 eClassFlags_HasCXXStructors = 0x02000,
1026 eClassFlags_Hidden = 0x20000,
1027 eClassFlags_ABI2_Hidden = 0x00010,
1028 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1029};
1030
1031// <rdr://5142207&4705298&4843145>
1032static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1033 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1034 // FIXME: Support -fvisibility
1035 switch (attr->getVisibility()) {
1036 default:
1037 assert(0 && "Unknown visibility");
1038 return false;
1039 case VisibilityAttr::DefaultVisibility:
1040 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1041 return false;
1042 case VisibilityAttr::HiddenVisibility:
1043 return true;
1044 }
1045 } else {
1046 return false; // FIXME: Support -fvisibility
1047 }
1048}
1049
1050/*
1051 struct _objc_class {
1052 Class isa;
1053 Class super_class;
1054 const char *name;
1055 long version;
1056 long info;
1057 long instance_size;
1058 struct _objc_ivar_list *ivars;
1059 struct _objc_method_list *methods;
1060 struct _objc_cache *cache;
1061 struct _objc_protocol_list *protocols;
1062 // Objective-C 1.0 extensions (<rdr://4585769>)
1063 const char *ivar_layout;
1064 struct _objc_class_ext *ext;
1065 };
1066
1067 See EmitClassExtension();
1068 */
1069void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001070 DefinedSymbols.insert(ID->getIdentifier());
1071
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001072 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001073 // FIXME: Gross
1074 ObjCInterfaceDecl *Interface =
1075 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001076 llvm::Constant *Protocols =
1077 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1078 Interface->protocol_begin(),
1079 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001080 const llvm::Type *InterfaceTy =
1081 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1082 unsigned Flags = eClassFlags_Factory;
1083 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1084
1085 // FIXME: Set CXX-structors flag.
1086 if (IsClassHidden(ID->getClassInterface()))
1087 Flags |= eClassFlags_Hidden;
1088
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001089 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1090 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1091 e = ID->instmeth_end(); i != e; ++i) {
1092 // Instance methods should always be defined.
1093 InstanceMethods.push_back(GetMethodConstant(*i));
1094 }
1095 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1096 e = ID->classmeth_end(); i != e; ++i) {
1097 // Class methods should always be defined.
1098 ClassMethods.push_back(GetMethodConstant(*i));
1099 }
1100
1101 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1102 e = ID->propimpl_end(); i != e; ++i) {
1103 ObjCPropertyImplDecl *PID = *i;
1104
1105 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1106 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1107
1108 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1109 if (llvm::Constant *C = GetMethodConstant(MD))
1110 InstanceMethods.push_back(C);
1111 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1112 if (llvm::Constant *C = GetMethodConstant(MD))
1113 InstanceMethods.push_back(C);
1114 }
1115 }
1116
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001117 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001118 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001119 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001120 // Record a reference to the super class.
1121 LazySymbols.insert(Super->getIdentifier());
1122
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001123 Values[ 1] =
1124 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1125 ObjCTypes.ClassPtrTy);
1126 } else {
1127 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1128 }
1129 Values[ 2] = GetClassName(ID->getIdentifier());
1130 // Version is always 0.
1131 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1132 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1133 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1134 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001135 Values[ 7] =
1136 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1137 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001138 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001139 // cache is always NULL.
1140 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1141 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001142 // FIXME: Set ivar_layout
1143 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001144 Values[11] = EmitClassExtension(ID);
1145 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1146 Values);
1147
1148 llvm::GlobalVariable *GV =
1149 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1150 llvm::GlobalValue::InternalLinkage,
1151 Init,
1152 std::string("\01L_OBJC_CLASS_")+ClassName,
1153 &CGM.getModule());
1154 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1155 UsedGlobals.push_back(GV);
1156 // FIXME: Why?
1157 GV->setAlignment(32);
1158 DefinedClasses.push_back(GV);
1159}
1160
1161llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1162 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001163 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001164 const ConstantVector &Methods) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001165 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001166 unsigned Flags = eClassFlags_Meta;
1167 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1168
1169 if (IsClassHidden(ID->getClassInterface()))
1170 Flags |= eClassFlags_Hidden;
1171
1172 std::vector<llvm::Constant*> Values(12);
1173 // The isa for the metaclass is the root of the hierarchy.
1174 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1175 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1176 Root = Super;
1177 Values[ 0] =
1178 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1179 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001180 // The super class for the metaclass is emitted as the name of the
1181 // super class. The runtime fixes this up to point to the
1182 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001183 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1184 Values[ 1] =
1185 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1186 ObjCTypes.ClassPtrTy);
1187 } else {
1188 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1189 }
1190 Values[ 2] = GetClassName(ID->getIdentifier());
1191 // Version is always 0.
1192 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1193 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1194 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1195 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001196 Values[ 7] =
1197 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1198 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001199 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001200 // cache is always NULL.
1201 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1202 Values[ 9] = Protocols;
1203 // ivar_layout for metaclass is always NULL.
1204 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1205 // The class extension is always unused for metaclasses.
1206 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1207 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1208 Values);
1209
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001210 std::string Name("\01L_OBJC_METACLASS_");
1211 Name += ClassName;
1212
1213 // Check for a forward reference.
1214 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1215 if (GV) {
1216 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1217 "Forward metaclass reference has incorrect type.");
1218 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1219 GV->setInitializer(Init);
1220 } else {
1221 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1222 llvm::GlobalValue::InternalLinkage,
1223 Init, Name,
1224 &CGM.getModule());
1225 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001226 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1227 UsedGlobals.push_back(GV);
1228 // FIXME: Why?
1229 GV->setAlignment(32);
1230
1231 return GV;
1232}
1233
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001234llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1235 std::string Name("\01L_OBJC_METACLASS_");
1236 Name += ID->getName();
1237
1238 // FIXME: Should we look these up somewhere other than the
1239 // module. Its a bit silly since we only generate these while
1240 // processing an implementation, so exactly one pointer would work
1241 // if know when we entered/exitted an implementation block.
1242
1243 // Check for an existing forward reference.
1244 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1245 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1246 "Forward metaclass reference has incorrect type.");
1247 return GV;
1248 } else {
1249 // Generate as an external reference to keep a consistent
1250 // module. This will be patched up when we emit the metaclass.
1251 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1252 llvm::GlobalValue::ExternalLinkage,
1253 0,
1254 Name,
1255 &CGM.getModule());
1256 }
1257}
1258
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001259/*
1260 struct objc_class_ext {
1261 uint32_t size;
1262 const char *weak_ivar_layout;
1263 struct _objc_property_list *properties;
1264 };
1265*/
1266llvm::Constant *
1267CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1268 uint64_t Size =
1269 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1270
1271 std::vector<llvm::Constant*> Values(3);
1272 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001273 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001274 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001275 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1276 ID->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001277 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001278 ID->getClassInterface()->classprop_begin(),
1279 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001280
1281 // Return null if no extension bits are used.
1282 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1283 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1284
1285 llvm::Constant *Init =
1286 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1287 llvm::GlobalVariable *GV =
1288 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1289 llvm::GlobalValue::InternalLinkage,
1290 Init,
1291 (std::string("\01L_OBJC_CLASSEXT_") +
1292 ID->getName()),
1293 &CGM.getModule());
1294 // No special section, but goes in llvm.used
1295 UsedGlobals.push_back(GV);
1296
1297 return GV;
1298}
1299
1300/*
1301 struct objc_ivar {
1302 char *ivar_name;
1303 char *ivar_type;
1304 int ivar_offset;
1305 };
1306
1307 struct objc_ivar_list {
1308 int ivar_count;
1309 struct objc_ivar list[count];
1310 };
1311 */
1312llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1313 bool ForClass,
1314 const llvm::Type *InterfaceTy) {
1315 std::vector<llvm::Constant*> Ivars, Ivar(3);
1316
1317 // When emitting the root class GCC emits ivar entries for the
1318 // actual class structure. It is not clear if we need to follow this
1319 // behavior; for now lets try and get away with not doing it. If so,
1320 // the cleanest solution would be to make up an ObjCInterfaceDecl
1321 // for the class.
1322 if (ForClass)
1323 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1324
1325 const llvm::StructLayout *Layout =
1326 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1327 for (ObjCInterfaceDecl::ivar_iterator
1328 i = ID->getClassInterface()->ivar_begin(),
1329 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1330 ObjCIvarDecl *V = *i;
1331 unsigned Offset =
1332 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1333 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001334 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001335 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001336 Ivar[1] = GetMethodVarType(TypeStr);
1337 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001338 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001339 }
1340
1341 // Return null for empty list.
1342 if (Ivars.empty())
1343 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1344
1345 std::vector<llvm::Constant*> Values(2);
1346 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1347 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1348 Ivars.size());
1349 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1350 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1351
1352 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1353 "\01L_OBJC_INSTANCE_VARIABLES_");
1354 llvm::GlobalVariable *GV =
1355 new llvm::GlobalVariable(Init->getType(), false,
1356 llvm::GlobalValue::InternalLinkage,
1357 Init,
1358 std::string(Prefix) + ID->getName(),
1359 &CGM.getModule());
1360 if (ForClass) {
1361 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1362 // FIXME: Why is this only here?
1363 GV->setAlignment(32);
1364 } else {
1365 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1366 }
1367 UsedGlobals.push_back(GV);
1368 return llvm::ConstantExpr::getBitCast(GV,
1369 ObjCTypes.IvarListPtrTy);
1370}
1371
1372/*
1373 struct objc_method {
1374 SEL method_name;
1375 char *method_types;
1376 void *method;
1377 };
1378
1379 struct objc_method_list {
1380 struct objc_method_list *obsolete;
1381 int count;
1382 struct objc_method methods_list[count];
1383 };
1384*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001385
1386/// GetMethodConstant - Return a struct objc_method constant for the
1387/// given method if it has been defined. The result is null if the
1388/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001389llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001390 // FIXME: Use DenseMap::lookup
1391 llvm::Function *Fn = MethodDefinitions[MD];
1392 if (!Fn)
1393 return 0;
1394
1395 std::vector<llvm::Constant*> Method(3);
1396 Method[0] =
1397 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1398 ObjCTypes.SelectorPtrTy);
1399 Method[1] = GetMethodVarType(MD);
1400 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1401 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1402}
1403
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001404llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1405 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001406 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001407 // Return null for empty list.
1408 if (Methods.empty())
1409 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1410
1411 std::vector<llvm::Constant*> Values(3);
1412 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1413 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1414 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1415 Methods.size());
1416 Values[2] = llvm::ConstantArray::get(AT, Methods);
1417 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1418
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001419 llvm::GlobalVariable *GV =
1420 new llvm::GlobalVariable(Init->getType(), false,
1421 llvm::GlobalValue::InternalLinkage,
1422 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001423 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001424 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001425 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001426 UsedGlobals.push_back(GV);
1427 return llvm::ConstantExpr::getBitCast(GV,
1428 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001429}
1430
1431llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001432 std::string Name;
1433 GetNameForMethod(OMD, Name);
1434
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001435 const llvm::FunctionType *MethodTy =
1436 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001437 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001438 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001439 llvm::GlobalValue::InternalLinkage,
1440 Name,
1441 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001442 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001443
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001444 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001445}
1446
1447llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001448 // Abuse this interface function as a place to finalize.
1449 FinishModule();
1450
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001451 return NULL;
1452}
1453
Daniel Dunbar49f66022008-09-24 03:38:44 +00001454llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1455 return ObjCTypes.GetPropertyFn;
1456}
1457
1458llvm::Function *CGObjCMac::GetPropertySetFunction() {
1459 return ObjCTypes.SetPropertyFn;
1460}
1461
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001462llvm::Function *CGObjCMac::EnumerationMutationFunction()
1463{
1464 return ObjCTypes.EnumerationMutationFn;
1465}
1466
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001467/*
1468
1469Objective-C setjmp-longjmp (sjlj) Exception Handling
1470--
1471
1472The basic framework for a @try-catch-finally is as follows:
1473{
1474 objc_exception_data d;
1475 id _rethrow = null;
1476
1477 objc_exception_try_enter(&d);
1478 if (!setjmp(d.jmp_buf)) {
1479 ... try body ...
1480 } else {
1481 // exception path
1482 id _caught = objc_exception_extract(&d);
1483
1484 // enter new try scope for handlers
1485 if (!setjmp(d.jmp_buf)) {
1486 ... match exception and execute catch blocks ...
1487
1488 // fell off end, rethrow.
1489 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001490 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001491 } else {
1492 // exception in catch block
1493 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001494 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001495 }
1496 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001497 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001498
1499finally:
1500 // match either the initial try_enter or the catch try_enter,
1501 // depending on the path followed.
1502 objc_exception_try_exit(&d);
1503finally_no_exit:
1504 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001505 ... dispatch to finally destination ...
1506
1507finally_rethrow:
1508 objc_exception_throw(_rethrow);
1509
1510finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001511}
1512
1513This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001514uses _rethrow to determine if objc_exception_try_exit should be called
1515and if the object should be rethrown. This breaks in the face of
1516throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001517
1518We specialize this framework for a few particular circumstances:
1519
1520 - If there are no catch blocks, then we avoid emitting the second
1521 exception handling context.
1522
1523 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1524 e)) we avoid emitting the code to rethrow an uncaught exception.
1525
1526 - FIXME: If there is no @finally block we can do a few more
1527 simplifications.
1528
1529Rethrows and Jumps-Through-Finally
1530--
1531
1532Support for implicit rethrows and jumping through the finally block is
1533handled by storing the current exception-handling context in
1534ObjCEHStack.
1535
Daniel Dunbar898d5082008-09-30 01:06:03 +00001536In order to implement proper @finally semantics, we support one basic
1537mechanism for jumping through the finally block to an arbitrary
1538destination. Constructs which generate exits from a @try or @catch
1539block use this mechanism to implement the proper semantics by chaining
1540jumps, as necessary.
1541
1542This mechanism works like the one used for indirect goto: we
1543arbitrarily assign an ID to each destination and store the ID for the
1544destination in a variable prior to entering the finally block. At the
1545end of the finally block we simply create a switch to the proper
1546destination.
1547
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001548*/
1549
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001550void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001551 const ObjCAtTryStmt &S) {
1552 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001553 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1554 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1555 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1556 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001557 llvm::Value *DestCode =
1558 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1559
1560 // Generate jump code. Done here so we can directly add things to
1561 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001562 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001563 llvm::SwitchInst *FinallySwitch =
1564 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1565 FinallyEnd, 10, FinallyJump);
1566
1567 // Push an EH context entry, used for handling rethrows and jumps
1568 // through finally.
1569 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1570 FinallySwitch, DestCode);
1571 CGF.ObjCEHStack.push_back(&EHEntry);
1572
1573 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001574 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1575 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001576 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1577 "_rethrow");
Anders Carlsson80f25672008-09-09 17:59:25 +00001578
1579 // Enter a new try block and call setjmp.
1580 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1581 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1582 "jmpbufarray");
1583 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1584 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1585 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001586
Daniel Dunbar55e87422008-11-11 02:29:29 +00001587 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1588 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001589 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001590 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001591
1592 // Emit the @try block.
1593 CGF.EmitBlock(TryBlock);
1594 CGF.EmitStmt(S.getTryBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001595 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001596
1597 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001598 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001599
1600 // Retrieve the exception object. We may emit multiple blocks but
1601 // nothing can cross this so the value is already in SSA form.
1602 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1603 ExceptionData,
1604 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001605 EHEntry.Exception = Caught;
Daniel Dunbar55e40722008-09-27 07:03:52 +00001606 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1607 // Enter a new exception try block (in case a @catch block throws
1608 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001609 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001610
Anders Carlsson80f25672008-09-09 17:59:25 +00001611 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1612 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001613 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001614
Daniel Dunbar55e87422008-11-11 02:29:29 +00001615 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1616 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001617 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001618
1619 CGF.EmitBlock(CatchBlock);
1620
Daniel Dunbar55e40722008-09-27 07:03:52 +00001621 // Handle catch list. As a special case we check if everything is
1622 // matched and avoid generating code for falling off the end if
1623 // so.
1624 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001625 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001626 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001627
Anders Carlssondde0a942008-09-11 09:15:33 +00001628 const DeclStmt *CatchParam =
1629 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001630 const VarDecl *VD = 0;
1631 const PointerType *PT = 0;
1632
Anders Carlsson80f25672008-09-09 17:59:25 +00001633 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001634 if (!CatchParam) {
1635 AllMatched = true;
1636 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001637 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001638 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001639
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001640 // catch(id e) always matches.
1641 // FIXME: For the time being we also match id<X>; this should
1642 // be rejected by Sema instead.
1643 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1644 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001645 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001646 }
1647
Daniel Dunbar55e40722008-09-27 07:03:52 +00001648 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001649 if (CatchParam) {
1650 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001651 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001652 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001653 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001654
Anders Carlssondde0a942008-09-11 09:15:33 +00001655 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001656 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001657 break;
1658 }
1659
Daniel Dunbar129271a2008-09-27 07:36:24 +00001660 assert(PT && "Unexpected non-pointer type in @catch");
1661 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001662 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001663 assert(ObjCType && "Catch parameter must have Objective-C type!");
1664
1665 // Check if the @catch block matches the exception object.
1666 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1667
Anders Carlsson80f25672008-09-09 17:59:25 +00001668 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1669 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001670
Daniel Dunbar55e87422008-11-11 02:29:29 +00001671 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001672
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001673 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001674 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001675
1676 // Emit the @catch block.
1677 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001678 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001679 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001680
1681 llvm::Value *Tmp =
1682 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1683 "tmp");
1684 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001685
1686 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001687 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001688
1689 CGF.EmitBlock(NextCatchBlock);
1690 }
1691
Daniel Dunbar55e40722008-09-27 07:03:52 +00001692 if (!AllMatched) {
1693 // None of the handlers caught the exception, so store it to be
1694 // rethrown at the end of the @finally block.
1695 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001696 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001697 }
1698
1699 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001700 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001701 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1702 ExceptionData),
1703 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001704 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001705 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001706 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001707 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001708 }
1709
Daniel Dunbar898d5082008-09-30 01:06:03 +00001710 // Pop the exception-handling stack entry. It is important to do
1711 // this now, because the code in the @finally block is not in this
1712 // context.
1713 CGF.ObjCEHStack.pop_back();
1714
Anders Carlsson80f25672008-09-09 17:59:25 +00001715 // Emit the @finally block.
1716 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001717 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001718
1719 CGF.EmitBlock(FinallyNoExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00001720 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1721 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1722
Daniel Dunbar898d5082008-09-30 01:06:03 +00001723 CGF.EmitBlock(FinallyJump);
1724
1725 CGF.EmitBlock(FinallyRethrow);
1726 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1727 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001728 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001729
1730 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001731}
1732
1733void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001734 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001735 llvm::Value *ExceptionAsObject;
1736
1737 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1738 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1739 ExceptionAsObject =
1740 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1741 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001742 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001743 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001744 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001745 }
1746
1747 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001748 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001749
1750 // Clear the insertion point to indicate we are in unreachable code.
1751 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001752}
1753
Daniel Dunbar898d5082008-09-30 01:06:03 +00001754void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1755 llvm::BasicBlock *Dst,
1756 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001757 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001758 return;
1759
1760 // Find the destination code for this block. We always use 0 for the
1761 // fallthrough block (default destination).
1762 llvm::SwitchInst *SI = E->FinallySwitch;
1763 llvm::ConstantInt *ID;
1764 if (Dst == SI->getDefaultDest()) {
1765 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1766 } else {
1767 ID = SI->findCaseDest(Dst);
1768 if (!ID) {
1769 // No code found, get a new unique one by just using the number
1770 // of switch successors.
1771 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1772 SI->addCase(ID, Dst);
1773 }
1774 }
1775
1776 // Set the destination code and branch.
1777 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001778 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001779}
1780
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001781/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001782/// object: objc_read_weak (id *src)
1783///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001784llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001785 llvm::Value *AddrWeakObj)
1786{
1787 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001788 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001789 return read_weak;
1790}
1791
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001792/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1793/// objc_assign_weak (id src, id *dst)
1794///
1795void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1796 llvm::Value *src, llvm::Value *dst)
1797{
1798 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1799 src, dst, "weakassign");
1800 return;
1801}
1802
Chris Lattner10cac6f2008-11-15 21:26:17 +00001803/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1804/// Effectively generating code for:
1805/// objc_sync_enter(expr);
1806/// @try stmt @finally { objc_sync_exit(expr); }
1807void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1808 const ObjCAtSynchronizedStmt &S) {
1809 // Create various blocks we refer to for handling @finally.
1810 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1811 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1812 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1813 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1814 llvm::Value *DestCode =
1815 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1816
1817 // Generate jump code. Done here so we can directly add things to
1818 // the switch instruction.
1819 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1820 llvm::SwitchInst *FinallySwitch =
1821 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1822 FinallyEnd, 10, FinallyJump);
1823
1824 // Push an EH context entry, used for handling rethrows and jumps
1825 // through finally.
1826 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1827 FinallySwitch, DestCode);
1828 CGF.ObjCEHStack.push_back(&EHEntry);
1829
1830 // Allocate memory for the exception data and rethrow pointer.
1831 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1832 "exceptiondata.ptr");
1833 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1834 "_rethrow");
1835 // Call objc_sync_enter(sync.expr)
1836 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1837 CGF.EmitScalarExpr(S.getSynchExpr()));
1838
1839 // Enter a new try block and call setjmp.
1840 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1841 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1842 "jmpbufarray");
1843 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1844 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1845 JmpBufPtr, "result");
1846
1847 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1848 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1849 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1850 TryHandler, TryBlock);
1851
1852 // Emit the @try block.
1853 CGF.EmitBlock(TryBlock);
1854 CGF.EmitStmt(S.getSynchBody());
1855 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1856
1857 // Emit the "exception in @try" block.
1858 CGF.EmitBlock(TryHandler);
1859
1860 // Retrieve the exception object. We may emit multiple blocks but
1861 // nothing can cross this so the value is already in SSA form.
1862 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1863 ExceptionData,
1864 "caught");
1865 EHEntry.Exception = Caught;
1866 CGF.Builder.CreateStore(Caught, RethrowPtr);
1867 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1868
1869 // Pop the exception-handling stack entry. It is important to do
1870 // this now, because the code in the @finally block is not in this
1871 // context.
1872 CGF.ObjCEHStack.pop_back();
1873
1874 // Emit the @finally block.
1875 CGF.EmitBlock(FinallyBlock);
1876 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1877
1878 CGF.EmitBlock(FinallyNoExit);
1879 // objc_sync_exit(expr); As finally's sole statement.
1880 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1881 CGF.EmitScalarExpr(S.getSynchExpr()));
1882
1883 CGF.EmitBlock(FinallyJump);
1884
1885 CGF.EmitBlock(FinallyRethrow);
1886 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1887 CGF.Builder.CreateLoad(RethrowPtr));
1888 CGF.Builder.CreateUnreachable();
1889
1890 CGF.EmitBlock(FinallyEnd);
1891}
1892
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001893/* *** Private Interface *** */
1894
1895/// EmitImageInfo - Emit the image info marker used to encode some module
1896/// level information.
1897///
1898/// See: <rdr://4810609&4810587&4810587>
1899/// struct IMAGE_INFO {
1900/// unsigned version;
1901/// unsigned flags;
1902/// };
1903enum ImageInfoFlags {
1904 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1905 eImageInfo_GarbageCollected = (1 << 1),
1906 eImageInfo_GCOnly = (1 << 2)
1907};
1908
1909void CGObjCMac::EmitImageInfo() {
1910 unsigned version = 0; // Version is unused?
1911 unsigned flags = 0;
1912
1913 // FIXME: Fix and continue?
1914 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1915 flags |= eImageInfo_GarbageCollected;
1916 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1917 flags |= eImageInfo_GCOnly;
1918
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001919 // Emitted as int[2];
1920 llvm::Constant *values[2] = {
1921 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1922 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1923 };
1924 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001925 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001926 new llvm::GlobalVariable(AT, true,
1927 llvm::GlobalValue::InternalLinkage,
1928 llvm::ConstantArray::get(AT, values, 2),
1929 "\01L_OBJC_IMAGE_INFO",
1930 &CGM.getModule());
1931
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001932 if (ObjCABI == 1) {
1933 GV->setSection("__OBJC, __image_info,regular");
1934 } else {
1935 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1936 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001937
1938 UsedGlobals.push_back(GV);
1939}
1940
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001941
1942// struct objc_module {
1943// unsigned long version;
1944// unsigned long size;
1945// const char *name;
1946// Symtab symtab;
1947// };
1948
1949// FIXME: Get from somewhere
1950static const int ModuleVersion = 7;
1951
1952void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001953 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1954
1955 std::vector<llvm::Constant*> Values(4);
1956 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1957 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001958 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001959 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001960 Values[3] = EmitModuleSymbols();
1961
1962 llvm::GlobalVariable *GV =
1963 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1964 llvm::GlobalValue::InternalLinkage,
1965 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1966 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001967 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001968 &CGM.getModule());
1969 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1970 UsedGlobals.push_back(GV);
1971}
1972
1973llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001974 unsigned NumClasses = DefinedClasses.size();
1975 unsigned NumCategories = DefinedCategories.size();
1976
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001977 // Return null if no symbols were defined.
1978 if (!NumClasses && !NumCategories)
1979 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1980
1981 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001982 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1983 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1984 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1985 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1986
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001987 // The runtime expects exactly the list of defined classes followed
1988 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001989 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001990 for (unsigned i=0; i<NumClasses; i++)
1991 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1992 ObjCTypes.Int8PtrTy);
1993 for (unsigned i=0; i<NumCategories; i++)
1994 Symbols[NumClasses + i] =
1995 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1996 ObjCTypes.Int8PtrTy);
1997
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001998 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001999 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000 NumClasses + NumCategories),
2001 Symbols);
2002
2003 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2004
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002005 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002006 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002007 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002009 "\01L_OBJC_SYMBOLS",
2010 &CGM.getModule());
2011 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2012 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002013 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2014}
2015
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002016llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002017 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002018 LazySymbols.insert(ID->getIdentifier());
2019
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002020 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2021
2022 if (!Entry) {
2023 llvm::Constant *Casted =
2024 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2025 ObjCTypes.ClassPtrTy);
2026 Entry =
2027 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2028 llvm::GlobalValue::InternalLinkage,
2029 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2030 &CGM.getModule());
2031 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2032 UsedGlobals.push_back(Entry);
2033 }
2034
2035 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002036}
2037
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002038llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002039 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2040
2041 if (!Entry) {
2042 llvm::Constant *Casted =
2043 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2044 ObjCTypes.SelectorPtrTy);
2045 Entry =
2046 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2047 llvm::GlobalValue::InternalLinkage,
2048 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2049 &CGM.getModule());
2050 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2051 UsedGlobals.push_back(Entry);
2052 }
2053
2054 return Builder.CreateLoad(Entry, false, "tmp");
2055}
2056
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002057llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2058 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002059
2060 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002061 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002062 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002063 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002064 llvm::GlobalValue::InternalLinkage,
2065 C, "\01L_OBJC_CLASS_NAME_",
2066 &CGM.getModule());
2067 Entry->setSection("__TEXT,__cstring,cstring_literals");
2068 UsedGlobals.push_back(Entry);
2069 }
2070
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002071 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002072}
2073
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002074llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2075 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2076
2077 if (!Entry) {
2078 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2079 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002080 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002081 llvm::GlobalValue::InternalLinkage,
2082 C, "\01L_OBJC_METH_VAR_NAME_",
2083 &CGM.getModule());
2084 Entry->setSection("__TEXT,__cstring,cstring_literals");
2085 UsedGlobals.push_back(Entry);
2086 }
2087
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002088 return getConstantGEP(Entry, 0, 0);
2089}
2090
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002091// FIXME: Merge into a single cstring creation function.
2092llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2093 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2094}
2095
2096// FIXME: Merge into a single cstring creation function.
2097llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2098 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2099}
2100
2101llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2102 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002103
2104 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002106 Entry =
2107 new llvm::GlobalVariable(C->getType(), false,
2108 llvm::GlobalValue::InternalLinkage,
2109 C, "\01L_OBJC_METH_VAR_TYPE_",
2110 &CGM.getModule());
2111 Entry->setSection("__TEXT,__cstring,cstring_literals");
2112 UsedGlobals.push_back(Entry);
2113 }
2114
2115 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002116}
2117
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002118// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002119llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002120 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002121 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2122 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002123 return GetMethodVarType(TypeStr);
2124}
2125
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002126// FIXME: Merge into a single cstring creation function.
2127llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2128 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2129
2130 if (!Entry) {
2131 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2132 Entry =
2133 new llvm::GlobalVariable(C->getType(), false,
2134 llvm::GlobalValue::InternalLinkage,
2135 C, "\01L_OBJC_PROP_NAME_ATTR_",
2136 &CGM.getModule());
2137 Entry->setSection("__TEXT,__cstring,cstring_literals");
2138 UsedGlobals.push_back(Entry);
2139 }
2140
2141 return getConstantGEP(Entry, 0, 0);
2142}
2143
2144// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002145// FIXME: This Decl should be more precise.
2146llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2147 const Decl *Container) {
2148 std::string TypeStr;
2149 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002150 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2151}
2152
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002153void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2154 std::string &NameOut) {
2155 // FIXME: Find the mangling GCC uses.
2156 std::stringstream s;
2157 s << (D->isInstance() ? "-" : "+");
2158 s << "[";
2159 s << D->getClassInterface()->getName();
2160 s << " ";
2161 s << D->getSelector().getName();
2162 s << "]";
2163 NameOut = s.str();
2164}
2165
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002166void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002167 EmitModuleInfo();
2168
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002169 // Emit the dummy bodies for any protocols which were referenced but
2170 // never defined.
2171 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2172 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2173 if (i->second->hasInitializer())
2174 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002175
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002176 std::vector<llvm::Constant*> Values(5);
2177 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2178 Values[1] = GetClassName(i->first);
2179 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2180 Values[3] = Values[4] =
2181 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2182 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2183 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2184 Values));
2185 }
2186
2187 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002188 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002189 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002190 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002191 }
2192
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002193 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002194 llvm::GlobalValue *GV =
2195 new llvm::GlobalVariable(AT, false,
2196 llvm::GlobalValue::AppendingLinkage,
2197 llvm::ConstantArray::get(AT, Used),
2198 "llvm.used",
2199 &CGM.getModule());
2200
2201 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002202
2203 // Add assembler directives to add lazy undefined symbol references
2204 // for classes which are referenced but not defined. This is
2205 // important for correct linker interaction.
2206
2207 // FIXME: Uh, this isn't particularly portable.
2208 std::stringstream s;
2209 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2210 e = LazySymbols.end(); i != e; ++i) {
2211 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2212 }
2213 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2214 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002215 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002216 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2217 }
2218 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002219}
2220
2221/* *** */
2222
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002223ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002224 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002225{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002226 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2227 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002228
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002229 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002230 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002231 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002232 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2233
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002234 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002235 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002236 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002237
2238 // FIXME: It would be nice to unify this with the opaque type, so
2239 // that the IR comes out a bit cleaner.
2240 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2241 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002242
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002243 MethodDescriptionTy =
2244 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002245 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002246 NULL);
2247 CGM.getModule().addTypeName("struct._objc_method_description",
2248 MethodDescriptionTy);
2249
2250 MethodDescriptionListTy =
2251 llvm::StructType::get(IntTy,
2252 llvm::ArrayType::get(MethodDescriptionTy, 0),
2253 NULL);
2254 CGM.getModule().addTypeName("struct._objc_method_description_list",
2255 MethodDescriptionListTy);
2256 MethodDescriptionListPtrTy =
2257 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2258
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002259 PropertyTy = llvm::StructType::get(Int8PtrTy,
2260 Int8PtrTy,
2261 NULL);
2262 CGM.getModule().addTypeName("struct._objc_property",
2263 PropertyTy);
2264
2265 PropertyListTy = llvm::StructType::get(IntTy,
2266 IntTy,
2267 llvm::ArrayType::get(PropertyTy, 0),
2268 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002269 CGM.getModule().addTypeName("struct._objc_property_list",
2270 PropertyListTy);
2271 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2272
2273 // Protocol description structures
2274
2275 ProtocolExtensionTy =
2276 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2277 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2278 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2279 PropertyListPtrTy,
2280 NULL);
2281 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2282 ProtocolExtensionTy);
2283 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2284
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002285 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002286
2287 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2288 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2289
2290 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2291 LongTy,
2292 llvm::ArrayType::get(ProtocolTyHolder, 0),
2293 NULL);
2294 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2295
2296 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002297 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002298 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2299 MethodDescriptionListPtrTy,
2300 MethodDescriptionListPtrTy,
2301 NULL);
2302 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2303
2304 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2305 CGM.getModule().addTypeName("struct._objc_protocol_list",
2306 ProtocolListTy);
2307 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2308
2309 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2310 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2311 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002312
2313 // Class description structures
2314
2315 IvarTy = llvm::StructType::get(Int8PtrTy,
2316 Int8PtrTy,
2317 IntTy,
2318 NULL);
2319 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2320
2321 IvarListTy = llvm::OpaqueType::get();
2322 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2323 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2324
2325 MethodTy = llvm::StructType::get(SelectorPtrTy,
2326 Int8PtrTy,
2327 Int8PtrTy,
2328 NULL);
2329 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2330
2331 MethodListTy = llvm::OpaqueType::get();
2332 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2333 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2334
2335 CacheTy = llvm::OpaqueType::get();
2336 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2337 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2338
2339 ClassExtensionTy =
2340 llvm::StructType::get(IntTy,
2341 Int8PtrTy,
2342 PropertyListPtrTy,
2343 NULL);
2344 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2345 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2346
2347 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2348
2349 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2350 llvm::PointerType::getUnqual(ClassTyHolder),
2351 Int8PtrTy,
2352 LongTy,
2353 LongTy,
2354 LongTy,
2355 IvarListPtrTy,
2356 MethodListPtrTy,
2357 CachePtrTy,
2358 ProtocolListPtrTy,
2359 Int8PtrTy,
2360 ClassExtensionPtrTy,
2361 NULL);
2362 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2363
2364 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2365 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2366 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2367
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002368 CategoryTy = llvm::StructType::get(Int8PtrTy,
2369 Int8PtrTy,
2370 MethodListPtrTy,
2371 MethodListPtrTy,
2372 ProtocolListPtrTy,
2373 IntTy,
2374 PropertyListPtrTy,
2375 NULL);
2376 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2377
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002378 // I'm not sure I like this. The implicit coordination is a bit
2379 // gross. We should solve this in a reasonable fashion because this
2380 // is a pretty common task (match some runtime data structure with
2381 // an LLVM data structure).
2382
2383 // FIXME: This is leaked.
2384 // FIXME: Merge with rewriter code?
2385 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2386 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002387 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002388 FieldDecl *FieldDecls[2];
2389 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2390 Ctx.getObjCIdType());
2391 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2392 Ctx.getObjCClassType());
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002393 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002394
2395 SuperCTy = Ctx.getTagDeclType(RD);
2396 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2397
2398 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002399 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002400
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002401 // Global metadata structures
2402
2403 SymtabTy = llvm::StructType::get(LongTy,
2404 SelectorPtrTy,
2405 ShortTy,
2406 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002407 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002408 NULL);
2409 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2410 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2411
2412 ModuleTy =
2413 llvm::StructType::get(LongTy,
2414 LongTy,
2415 Int8PtrTy,
2416 SymtabPtrTy,
2417 NULL);
2418 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002419
Daniel Dunbar49f66022008-09-24 03:38:44 +00002420 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002421
2422 std::vector<const llvm::Type*> Params;
2423 Params.push_back(ObjectPtrTy);
2424 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002425 MessageSendFn =
2426 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2427 Params,
2428 true),
2429 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002430
2431 Params.clear();
2432 Params.push_back(Int8PtrTy);
2433 Params.push_back(ObjectPtrTy);
2434 Params.push_back(SelectorPtrTy);
2435 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002436 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2437 Params,
2438 true),
2439 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002440
2441 Params.clear();
2442 Params.push_back(ObjectPtrTy);
2443 Params.push_back(SelectorPtrTy);
2444 // FIXME: This should be long double on x86_64?
2445 MessageSendFpretFn =
2446 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2447 Params,
2448 true),
2449 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002450
2451 Params.clear();
2452 Params.push_back(SuperPtrTy);
2453 Params.push_back(SelectorPtrTy);
2454 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002455 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2456 Params,
2457 true),
2458 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002459
2460 Params.clear();
2461 Params.push_back(Int8PtrTy);
2462 Params.push_back(SuperPtrTy);
2463 Params.push_back(SelectorPtrTy);
2464 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002465 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2466 Params,
2467 true),
2468 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002469
2470 // There is no objc_msgSendSuper_fpret? How can that work?
2471 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002472
Daniel Dunbar49f66022008-09-24 03:38:44 +00002473 // Property manipulation functions.
2474
2475 Params.clear();
2476 Params.push_back(ObjectPtrTy);
2477 Params.push_back(SelectorPtrTy);
2478 Params.push_back(LongTy);
2479 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2480 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002481 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2482 Params,
2483 false),
2484 "objc_getProperty");
2485
Daniel Dunbar49f66022008-09-24 03:38:44 +00002486 Params.clear();
2487 Params.push_back(ObjectPtrTy);
2488 Params.push_back(SelectorPtrTy);
2489 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002490 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002491 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2492 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2493 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002494 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2495 Params,
2496 false),
2497 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002498
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002499 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002500
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002501 Params.clear();
2502 Params.push_back(ObjectPtrTy);
2503 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002504 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2505 Params,
2506 false),
2507 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002508
2509 // FIXME: This is the size of the setjmp buffer and should be
2510 // target specific. 18 is what's used on 32-bit X86.
2511 uint64_t SetJmpBufferSize = 18;
2512
2513 // Exceptions
2514 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002515 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002516
2517 ExceptionDataTy =
2518 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2519 SetJmpBufferSize),
2520 StackPtrTy, NULL);
2521 CGM.getModule().addTypeName("struct._objc_exception_data",
2522 ExceptionDataTy);
2523
2524 Params.clear();
2525 Params.push_back(ObjectPtrTy);
2526 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002527 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2528 Params,
2529 false),
2530 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002531
2532 Params.clear();
2533 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2534 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002535 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2536 Params,
2537 false),
2538 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002539 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002540 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2541 Params,
2542 false),
2543 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002544 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002545 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2546 Params,
2547 false),
2548 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002549
2550 Params.clear();
2551 Params.push_back(ClassPtrTy);
2552 Params.push_back(ObjectPtrTy);
2553 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002554 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2555 Params,
2556 false),
2557 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002558
2559 // synchronized APIs
2560 // void objc_sync_enter (id)
2561 Params.clear();
2562 Params.push_back(ObjectPtrTy);
2563 SyncEnterFn =
2564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2565 Params,
2566 false),
2567 "objc_sync_enter");
2568 // void objc_sync_exit (id)
2569 SyncExitFn =
2570 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2571 Params,
2572 false),
2573 "objc_sync_exit");
2574
Anders Carlsson124526b2008-09-09 10:10:21 +00002575
2576 Params.clear();
2577 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2578 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002579 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2580 Params,
2581 false),
2582 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002583
2584 // gc's API
2585 // id objc_read_weak (id *)
2586 Params.clear();
2587 Params.push_back(PtrObjectPtrTy);
2588 GcReadWeakFn =
2589 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2590 Params,
2591 false),
2592 "objc_read_weak");
2593 // id objc_assign_weak (id, id *)
2594 Params.clear();
2595 Params.push_back(ObjectPtrTy);
2596 Params.push_back(PtrObjectPtrTy);
2597 GcAssignWeakFn =
2598 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2599 Params,
2600 false),
2601 "objc_assign_weak");
2602 GcAssignGlobalFn =
2603 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2604 Params,
2605 false),
2606 "objc_assign_global");
2607 GcAssignStrongCastFn =
2608 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2609 Params,
2610 false),
2611 "objc_assign_strongCast");
2612
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002613}
2614
2615ObjCTypesHelper::~ObjCTypesHelper() {
2616}
2617
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002618/* *** */
2619
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002620CodeGen::CGObjCRuntime *
2621CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002622 return new CGObjCMac(CGM);
2623}