blob: 44d56b5a6082cffd49a6c427f674c1700892c0c8 [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 Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy;
45 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Fariborz Jahaniandb286862009-01-22 00:37:21 +000087 llvm::Function *GetPropertyFn, *SetPropertyFn;
88
89 llvm::Function *EnumerationMutationFn;
90
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
92 llvm::Function *GcReadWeakFn;
93
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
95 llvm::Function *GcAssignWeakFn;
96
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
98 llvm::Function *GcAssignGlobalFn;
99
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
101 llvm::Function *GcAssignIvarFn;
102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
104 llvm::Function *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
107 llvm::Function *ExceptionThrowFn;
108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
110 llvm::Function *SyncEnterFn;
111
112 /// SyncExitFn - LLVM object_sync_exit function.
113 llvm::Function *SyncExitFn;
114
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000115 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
116 ~ObjCCommonTypesHelper(){}
117};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000118
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000119/// ObjCTypesHelper - Helper class that encapsulates lazy
120/// construction of varies types used during ObjC generation.
121class ObjCTypesHelper : public ObjCCommonTypesHelper {
122private:
123
124 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
125 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
126 *MessageSendSuperFpretFn;
127
128public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000129 /// SymtabTy - LLVM type for struct objc_symtab.
130 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000131 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
132 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000133 /// ModuleTy - LLVM type for struct objc_module.
134 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000135
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000136 /// ProtocolTy - LLVM type for struct objc_protocol.
137 const llvm::StructType *ProtocolTy;
138 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
139 const llvm::Type *ProtocolPtrTy;
140 /// ProtocolExtensionTy - LLVM type for struct
141 /// objc_protocol_extension.
142 const llvm::StructType *ProtocolExtensionTy;
143 /// ProtocolExtensionTy - LLVM type for struct
144 /// objc_protocol_extension *.
145 const llvm::Type *ProtocolExtensionPtrTy;
146 /// MethodDescriptionTy - LLVM type for struct
147 /// objc_method_description.
148 const llvm::StructType *MethodDescriptionTy;
149 /// MethodDescriptionListTy - LLVM type for struct
150 /// objc_method_description_list.
151 const llvm::StructType *MethodDescriptionListTy;
152 /// MethodDescriptionListPtrTy - LLVM type for struct
153 /// objc_method_description_list *.
154 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000155 /// ProtocolListTy - LLVM type for struct objc_property_list.
156 const llvm::Type *ProtocolListTy;
157 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
158 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000159 /// CategoryTy - LLVM type for struct objc_category.
160 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000161 /// ClassTy - LLVM type for struct objc_class.
162 const llvm::StructType *ClassTy;
163 /// ClassPtrTy - LLVM type for struct objc_class *.
164 const llvm::Type *ClassPtrTy;
165 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
166 const llvm::StructType *ClassExtensionTy;
167 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
168 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000169 // IvarTy - LLVM type for struct objc_ivar.
170 const llvm::StructType *IvarTy;
171 /// IvarListTy - LLVM type for struct objc_ivar_list.
172 const llvm::Type *IvarListTy;
173 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
174 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 /// MethodListTy - LLVM type for struct objc_method_list.
176 const llvm::Type *MethodListTy;
177 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
178 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000179
180 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
181 const llvm::Type *ExceptionDataTy;
182
Anders Carlsson124526b2008-09-09 10:10:21 +0000183 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
184 llvm::Function *ExceptionTryEnterFn;
185
186 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
187 llvm::Function *ExceptionTryExitFn;
188
189 /// ExceptionExtractFn - LLVM objc_exception_extract function.
190 llvm::Function *ExceptionExtractFn;
191
192 /// ExceptionMatchFn - LLVM objc_exception_match function.
193 llvm::Function *ExceptionMatchFn;
194
195 /// SetJmpFn - LLVM _setjmp function.
196 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000197
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000198public:
199 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000200 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000201
202
203 llvm::Function *getSendFn(bool IsSuper) {
204 return IsSuper ? MessageSendSuperFn : MessageSendFn;
205 }
206
207 llvm::Function *getSendStretFn(bool IsSuper) {
208 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
209 }
210
211 llvm::Function *getSendFpretFn(bool IsSuper) {
212 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
213 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000214};
215
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000216/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000217/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000218class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000219public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000220 llvm::Function *MessageSendFixupFn, *MessageSendFpretFixupFn,
221 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
222 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
223 *MessageSendSuper2StretFixupFn;
224
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000225 // MethodListnfABITy - LLVM for struct _method_list_t
226 const llvm::StructType *MethodListnfABITy;
227
228 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
229 const llvm::Type *MethodListnfABIPtrTy;
230
231 // ProtocolnfABITy = LLVM for struct _protocol_t
232 const llvm::StructType *ProtocolnfABITy;
233
Daniel Dunbar948e2582009-02-15 07:36:20 +0000234 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
235 const llvm::Type *ProtocolnfABIPtrTy;
236
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000237 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
238 const llvm::StructType *ProtocolListnfABITy;
239
240 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
241 const llvm::Type *ProtocolListnfABIPtrTy;
242
243 // ClassnfABITy - LLVM for struct _class_t
244 const llvm::StructType *ClassnfABITy;
245
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000246 // ClassnfABIPtrTy - LLVM for struct _class_t*
247 const llvm::Type *ClassnfABIPtrTy;
248
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000249 // IvarnfABITy - LLVM for struct _ivar_t
250 const llvm::StructType *IvarnfABITy;
251
252 // IvarListnfABITy - LLVM for struct _ivar_list_t
253 const llvm::StructType *IvarListnfABITy;
254
255 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
256 const llvm::Type *IvarListnfABIPtrTy;
257
258 // ClassRonfABITy - LLVM for struct _class_ro_t
259 const llvm::StructType *ClassRonfABITy;
260
261 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
262 const llvm::Type *ImpnfABITy;
263
264 // CategorynfABITy - LLVM for struct _category_t
265 const llvm::StructType *CategorynfABITy;
266
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000267 // New types for nonfragile abi messaging.
268
269 // MessageRefTy - LLVM for:
270 // struct _message_ref_t {
271 // IMP messenger;
272 // SEL name;
273 // };
274 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000275 // MessageRefCTy - clang type for struct _message_ref_t
276 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000277
278 // MessageRefPtrTy - LLVM for struct _message_ref_t*
279 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000280 // MessageRefCPtrTy - clang type for struct _message_ref_t*
281 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000282
Fariborz Jahanianef163782009-02-05 01:13:09 +0000283 // MessengerTy - Type of the messenger (shown as IMP above)
284 const llvm::FunctionType *MessengerTy;
285
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000286 // SuperMessageRefTy - LLVM for:
287 // struct _super_message_ref_t {
288 // SUPER_IMP messenger;
289 // SEL name;
290 // };
291 const llvm::StructType *SuperMessageRefTy;
292
293 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
294 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000295
296 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
297 /// exception personality function.
298 llvm::Value *EHPersonalityPtr;
299
Daniel Dunbare588b992009-03-01 04:46:24 +0000300 llvm::Function *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
301
302 const llvm::StructType *EHTypeTy;
303 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000304
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000305 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
306 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000307};
308
309class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
310protected:
311 CodeGen::CodeGenModule &CGM;
312 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000313 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000314
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000315 /// LazySymbols - Symbols to generate a lazy reference for. See
316 /// DefinedSymbols and FinishModule().
317 std::set<IdentifierInfo*> LazySymbols;
318
319 /// DefinedSymbols - External symbols which are defined by this
320 /// module. The symbols in this list and LazySymbols are used to add
321 /// special linker symbols which ensure that Objective-C modules are
322 /// linked properly.
323 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000324
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000325 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000326 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000328 /// MethodVarNames - uniqued method variable names.
329 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000330
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000331 /// MethodVarTypes - uniqued method type signatures. We have to use
332 /// a StringMap here because have no other unique reference.
333 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000334
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000335 /// MethodDefinitions - map of methods which have been defined in
336 /// this translation unit.
337 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000338
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000339 /// PropertyNames - uniqued method variable names.
340 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000341
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000342 /// ClassReferences - uniqued class references.
343 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000344
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000345 /// SelectorReferences - uniqued selector references.
346 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000347
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000348 /// Protocols - Protocols for which an objc_protocol structure has
349 /// been emitted. Forward declarations are handled by creating an
350 /// empty structure whose initializer is filled in when/if defined.
351 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000352
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000353 /// DefinedProtocols - Protocols which have actually been
354 /// defined. We should not need this, see FIXME in GenerateProtocol.
355 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000356
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000357 /// DefinedClasses - List of defined classes.
358 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000360 /// DefinedCategories - List of defined categories.
361 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000362
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000363 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000364 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000365 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000366
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000367 /// GetNameForMethod - Return a name for the given method.
368 /// \param[out] NameOut - The return value.
369 void GetNameForMethod(const ObjCMethodDecl *OMD,
370 const ObjCContainerDecl *CD,
371 std::string &NameOut);
372
373 /// GetMethodVarName - Return a unique constant for the given
374 /// selector's name. The return value has type char *.
375 llvm::Constant *GetMethodVarName(Selector Sel);
376 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
377 llvm::Constant *GetMethodVarName(const std::string &Name);
378
379 /// GetMethodVarType - Return a unique constant for the given
380 /// selector's name. The return value has type char *.
381
382 // FIXME: This is a horrible name.
383 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000384 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000385
386 /// GetPropertyName - Return a unique constant for the given
387 /// name. The return value has type char *.
388 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
389
390 // FIXME: This can be dropped once string functions are unified.
391 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
392 const Decl *Container);
393
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000394 /// GetClassName - Return a unique constant for the given selector's
395 /// name. The return value has type char *.
396 llvm::Constant *GetClassName(IdentifierInfo *Ident);
397
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000398 /// BuildIvarLayout - Builds ivar layout bitmap for the class
399 /// implementation for the __strong or __weak case.
400 ///
401 llvm::Constant *BuildIvarLayout(ObjCImplementationDecl *OI,
402 bool ForStrongLayout);
403
404 void BuildAggrIvarLayout(RecordDecl *RD,
405 const std::vector<FieldDecl*>& RecFields,
406 unsigned int BytePos, bool ForStrongLayout,
407 int &Index, int &SkIndex, bool &HasUnion);
408
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000409 /// GetIvarLayoutName - Returns a unique constant for the given
410 /// ivar layout bitmap.
411 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
412 const ObjCCommonTypesHelper &ObjCTypes);
413
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000414 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
415 RecordDecl::field_iterator &FIV,
416 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000417 /// EmitPropertyList - Emit the given property list. The return
418 /// value has type PropertyListPtrTy.
419 llvm::Constant *EmitPropertyList(const std::string &Name,
420 const Decl *Container,
421 const ObjCContainerDecl *OCD,
422 const ObjCCommonTypesHelper &ObjCTypes);
423
Fariborz Jahanianda320092009-01-29 19:24:30 +0000424 /// GetProtocolRef - Return a reference to the internal protocol
425 /// description, creating an empty one if it has not been
426 /// defined. The return value has type ProtocolPtrTy.
427 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000428
429 /// GetIvarBaseOffset - returns ivars byte offset.
430 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
431 FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000432
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000433public:
434 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
435 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000436
437 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000438
439 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
440 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000441
442 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
443
444 /// GetOrEmitProtocol - Get the protocol object for the given
445 /// declaration, emitting it if necessary. The return value has type
446 /// ProtocolPtrTy.
447 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
448
449 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
450 /// object for the given declaration, emitting it if needed. These
451 /// forward references will be filled in with empty bodies if no
452 /// definition is seen. The return value has type ProtocolPtrTy.
453 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000454};
455
456class CGObjCMac : public CGObjCCommonMac {
457private:
458 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000459 /// EmitImageInfo - Emit the image info marker used to encode some module
460 /// level information.
461 void EmitImageInfo();
462
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000463 /// EmitModuleInfo - Another marker encoding module level
464 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000465 void EmitModuleInfo();
466
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000467 /// EmitModuleSymols - Emit module symbols, the list of defined
468 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000469 llvm::Constant *EmitModuleSymbols();
470
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000471 /// FinishModule - Write out global data structures at the end of
472 /// processing a translation unit.
473 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000474
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000475 /// EmitClassExtension - Generate the class extension structure used
476 /// to store the weak ivar layout and properties. The return value
477 /// has type ClassExtensionPtrTy.
478 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
479
480 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
481 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000482 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000483 const ObjCInterfaceDecl *ID);
484
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000485 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000486 QualType ResultType,
487 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000488 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000489 QualType Arg0Ty,
490 bool IsSuper,
491 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000492
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000493 /// EmitIvarList - Emit the ivar list for the given
494 /// implementation. If ForClass is true the list of class ivars
495 /// (i.e. metaclass ivars) is emitted, otherwise the list of
496 /// interface ivars will be emitted. The return value has type
497 /// IvarListPtrTy.
498 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000499 bool ForClass);
500
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000501 /// EmitMetaClass - Emit a forward reference to the class structure
502 /// for the metaclass of the given interface. The return value has
503 /// type ClassPtrTy.
504 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
505
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000506 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000507 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000508 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
509 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000510 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000511 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000512
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000513 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000514
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000515 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000516
517 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000518 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000519 llvm::Constant *EmitMethodList(const std::string &Name,
520 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000521 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000522
523 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000524 /// method declarations.
525 /// - TypeName: The name for the type containing the methods.
526 /// - IsProtocol: True iff these methods are for a protocol.
527 /// - ClassMethds: True iff these are class methods.
528 /// - Required: When true, only "required" methods are
529 /// listed. Similarly, when false only "optional" methods are
530 /// listed. For classes this should always be true.
531 /// - begin, end: The method list to output.
532 ///
533 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000534 llvm::Constant *EmitMethodDescList(const std::string &Name,
535 const char *Section,
536 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000537
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000538 /// GetOrEmitProtocol - Get the protocol object for the given
539 /// declaration, emitting it if necessary. The return value has type
540 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000541 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000542
543 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
544 /// object for the given declaration, emitting it if needed. These
545 /// forward references will be filled in with empty bodies if no
546 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000547 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000548
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000549 /// EmitProtocolExtension - Generate the protocol extension
550 /// structure used to store optional instance and class methods, and
551 /// protocol properties. The return value has type
552 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000553 llvm::Constant *
554 EmitProtocolExtension(const ObjCProtocolDecl *PD,
555 const ConstantVector &OptInstanceMethods,
556 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000557
558 /// EmitProtocolList - Generate the list of referenced
559 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000560 llvm::Constant *EmitProtocolList(const std::string &Name,
561 ObjCProtocolDecl::protocol_iterator begin,
562 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000563
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000564 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
565 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000566 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000567
Fariborz Jahanianda320092009-01-29 19:24:30 +0000568 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000569 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000570
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000571 virtual llvm::Function *ModuleInitFunction();
572
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000573 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000574 QualType ResultType,
575 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000576 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000577 bool IsClassMessage,
578 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000579
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000580 virtual CodeGen::RValue
581 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000582 QualType ResultType,
583 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000584 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000585 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000586 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000587 bool IsClassMessage,
588 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000589
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000590 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000591 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000592
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000593 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000594
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000595 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000596
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000597 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000598
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000599 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000600 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000601
Daniel Dunbar49f66022008-09-24 03:38:44 +0000602 virtual llvm::Function *GetPropertyGetFunction();
603 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000604 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000605
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000606 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
607 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000608 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
609 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000610 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000611 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000612 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
613 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000614 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
615 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000616 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
617 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000618 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
619 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000620
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000621 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
622 QualType ObjectTy,
623 llvm::Value *BaseValue,
624 const ObjCIvarDecl *Ivar,
625 const FieldDecl *Field,
626 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000627 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
628 ObjCInterfaceDecl *Interface,
629 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000630};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000631
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000632class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000633private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000634 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000635 llvm::GlobalVariable* ObjCEmptyCacheVar;
636 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000637
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000638 /// MetaClassReferences - uniqued meta class references.
639 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000640
641 /// EHTypeReferences - uniqued class ehtype references.
642 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000643
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000644 /// FinishNonFragileABIModule - Write out global data structures at the end of
645 /// processing a translation unit.
646 void FinishNonFragileABIModule();
647
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000648 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
649 unsigned InstanceStart,
650 unsigned InstanceSize,
651 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000652 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
653 llvm::Constant *IsAGV,
654 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000655 llvm::Constant *ClassRoGV,
656 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000657
658 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
659
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000660 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
661
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000662 /// EmitMethodList - Emit the method list for the given
663 /// implementation. The return value has type MethodListnfABITy.
664 llvm::Constant *EmitMethodList(const std::string &Name,
665 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000666 const ConstantVector &Methods);
667 /// EmitIvarList - Emit the ivar list for the given
668 /// implementation. If ForClass is true the list of class ivars
669 /// (i.e. metaclass ivars) is emitted, otherwise the list of
670 /// interface ivars will be emitted. The return value has type
671 /// IvarListnfABIPtrTy.
672 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000673
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000674 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000675 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000676 unsigned long int offset);
677
Fariborz Jahanianda320092009-01-29 19:24:30 +0000678 /// GetOrEmitProtocol - Get the protocol object for the given
679 /// declaration, emitting it if necessary. The return value has type
680 /// ProtocolPtrTy.
681 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
682
683 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
684 /// object for the given declaration, emitting it if needed. These
685 /// forward references will be filled in with empty bodies if no
686 /// definition is seen. The return value has type ProtocolPtrTy.
687 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
688
689 /// EmitProtocolList - Generate the list of referenced
690 /// protocols. The return value has type ProtocolListPtrTy.
691 llvm::Constant *EmitProtocolList(const std::string &Name,
692 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000693 ObjCProtocolDecl::protocol_iterator end);
694
695 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
696 QualType ResultType,
697 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000698 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000699 QualType Arg0Ty,
700 bool IsSuper,
701 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000702
703 /// GetClassGlobal - Return the global variable for the Objective-C
704 /// class of the given name.
705 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000706
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000707 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
708 /// for the given class.
709 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000710 const ObjCInterfaceDecl *ID,
711 bool IsSuper = false);
712
713 /// EmitMetaClassRef - Return a Value * of the address of _class_t
714 /// meta-data
715 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
716 const ObjCInterfaceDecl *ID);
717
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000718 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
719 /// the given ivar.
720 ///
721 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000722 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000723 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000724
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000725 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
726 /// for the given selector.
727 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000728
729 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
730 /// interface. The return value has type EHTypePtrTy.
731 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000732
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000733public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000734 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000735 // FIXME. All stubs for now!
736 virtual llvm::Function *ModuleInitFunction();
737
738 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
739 QualType ResultType,
740 Selector Sel,
741 llvm::Value *Receiver,
742 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000743 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000744
745 virtual CodeGen::RValue
746 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
747 QualType ResultType,
748 Selector Sel,
749 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000750 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000751 llvm::Value *Receiver,
752 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000753 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000754
755 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000756 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000757
758 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000759 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000760
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000761 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000762
763 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000764 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000765 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000766
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000767 virtual llvm::Function *GetPropertyGetFunction(){
768 return ObjCTypes.GetPropertyFn;
769 }
770 virtual llvm::Function *GetPropertySetFunction(){
771 return ObjCTypes.SetPropertyFn;
772 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000773 virtual llvm::Function *EnumerationMutationFunction() {
774 return ObjCTypes.EnumerationMutationFn;
775 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000776
777 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000778 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000779 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000780 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000781 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000782 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000783 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000784 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000785 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000786 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000787 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000788 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000789 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000790 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000791 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
792 QualType ObjectTy,
793 llvm::Value *BaseValue,
794 const ObjCIvarDecl *Ivar,
795 const FieldDecl *Field,
796 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000797 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
798 ObjCInterfaceDecl *Interface,
799 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000800};
801
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000802} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000803
804/* *** Helper Functions *** */
805
806/// getConstantGEP() - Help routine to construct simple GEPs.
807static llvm::Constant *getConstantGEP(llvm::Constant *C,
808 unsigned idx0,
809 unsigned idx1) {
810 llvm::Value *Idxs[] = {
811 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
812 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
813 };
814 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
815}
816
817/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000818
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000819CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
820 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000821{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000822 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000823 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000824}
825
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000826/// GetClass - Return a reference to the class for the given interface
827/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000828llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000829 const ObjCInterfaceDecl *ID) {
830 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000831}
832
833/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000834llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000835 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000836}
837
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000838/// Generate a constant CFString object.
839/*
840 struct __builtin_CFString {
841 const int *isa; // point to __CFConstantStringClassReference
842 int flags;
843 const char *str;
844 long length;
845 };
846*/
847
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000848llvm::Constant *CGObjCCommonMac::GenerateConstantString(
849 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000850 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000851}
852
853/// Generates a message send where the super is the receiver. This is
854/// a message send to self with special delivery semantics indicating
855/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000856CodeGen::RValue
857CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000858 QualType ResultType,
859 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000860 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000861 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000862 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000863 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000864 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000865 // Create and init a super structure; this is a (receiver, class)
866 // pair we will pass to objc_msgSendSuper.
867 llvm::Value *ObjCSuper =
868 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
869 llvm::Value *ReceiverAsObject =
870 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
871 CGF.Builder.CreateStore(ReceiverAsObject,
872 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000873
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000874 // If this is a class message the metaclass is passed as the target.
875 llvm::Value *Target;
876 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000877 if (isCategoryImpl) {
878 // Message sent to 'super' in a class method defined in a category
879 // implementation requires an odd treatment.
880 // If we are in a class method, we must retrieve the
881 // _metaclass_ for the current class, pointed at by
882 // the class's "isa" pointer. The following assumes that
883 // isa" is the first ivar in a class (which it must be).
884 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
885 Target = CGF.Builder.CreateStructGEP(Target, 0);
886 Target = CGF.Builder.CreateLoad(Target);
887 }
888 else {
889 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
890 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
891 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
892 Target = Super;
893 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000894 } else {
895 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
896 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000897 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
898 // and ObjCTypes types.
899 const llvm::Type *ClassTy =
900 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000901 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000902 CGF.Builder.CreateStore(Target,
903 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
904
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000905 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000906 ObjCSuper, ObjCTypes.SuperPtrCTy,
907 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000908}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000909
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000910/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000911CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000912 QualType ResultType,
913 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000914 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000915 bool IsClassMessage,
916 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000917 llvm::Value *Arg0 =
918 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000919 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000920 Arg0, CGF.getContext().getObjCIdType(),
921 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000922}
923
924CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000925 QualType ResultType,
926 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000927 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000928 QualType Arg0Ty,
929 bool IsSuper,
930 const CallArgList &CallArgs) {
931 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000932 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
933 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
934 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000935 CGF.getContext().getObjCSelType()));
936 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000937
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000938 CodeGenTypes &Types = CGM.getTypes();
939 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
940 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000941
942 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000943 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000944 Fn = ObjCTypes.getSendStretFn(IsSuper);
945 } else if (ResultType->isFloatingType()) {
946 // FIXME: Sadly, this is wrong. This actually depends on the
947 // architecture. This happens to be right for x86-32 though.
948 Fn = ObjCTypes.getSendFpretFn(IsSuper);
949 } else {
950 Fn = ObjCTypes.getSendFn(IsSuper);
951 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000952 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000953 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000954}
955
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000956llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000957 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000958 // FIXME: I don't understand why gcc generates this, or where it is
959 // resolved. Investigate. Its also wasteful to look this up over and
960 // over.
961 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
962
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000963 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
964 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000965}
966
Fariborz Jahanianda320092009-01-29 19:24:30 +0000967void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000968 // FIXME: We shouldn't need this, the protocol decl should contain
969 // enough information to tell us whether this was a declaration or a
970 // definition.
971 DefinedProtocols.insert(PD->getIdentifier());
972
973 // If we have generated a forward reference to this protocol, emit
974 // it now. Otherwise do nothing, the protocol objects are lazily
975 // emitted.
976 if (Protocols.count(PD->getIdentifier()))
977 GetOrEmitProtocol(PD);
978}
979
Fariborz Jahanianda320092009-01-29 19:24:30 +0000980llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000981 if (DefinedProtocols.count(PD->getIdentifier()))
982 return GetOrEmitProtocol(PD);
983 return GetOrEmitProtocolRef(PD);
984}
985
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000986/*
987 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
988 struct _objc_protocol {
989 struct _objc_protocol_extension *isa;
990 char *protocol_name;
991 struct _objc_protocol_list *protocol_list;
992 struct _objc__method_prototype_list *instance_methods;
993 struct _objc__method_prototype_list *class_methods
994 };
995
996 See EmitProtocolExtension().
997*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000998llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
999 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1000
1001 // Early exit if a defining object has already been generated.
1002 if (Entry && Entry->hasInitializer())
1003 return Entry;
1004
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001005 // FIXME: I don't understand why gcc generates this, or where it is
1006 // resolved. Investigate. Its also wasteful to look this up over and
1007 // over.
1008 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1009
Chris Lattner8ec03f52008-11-24 03:54:41 +00001010 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001011
1012 // Construct method lists.
1013 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1014 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1015 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1016 e = PD->instmeth_end(); i != e; ++i) {
1017 ObjCMethodDecl *MD = *i;
1018 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1019 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1020 OptInstanceMethods.push_back(C);
1021 } else {
1022 InstanceMethods.push_back(C);
1023 }
1024 }
1025
1026 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1027 e = PD->classmeth_end(); i != e; ++i) {
1028 ObjCMethodDecl *MD = *i;
1029 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1030 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1031 OptClassMethods.push_back(C);
1032 } else {
1033 ClassMethods.push_back(C);
1034 }
1035 }
1036
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001037 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001038 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001039 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001040 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001041 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001042 PD->protocol_begin(),
1043 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001044 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001045 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1046 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001047 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1048 InstanceMethods);
1049 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001050 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1051 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001052 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1053 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001054 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1055 Values);
1056
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001057 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001058 // Already created, fix the linkage and update the initializer.
1059 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001060 Entry->setInitializer(Init);
1061 } else {
1062 Entry =
1063 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1064 llvm::GlobalValue::InternalLinkage,
1065 Init,
1066 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1067 &CGM.getModule());
1068 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1069 UsedGlobals.push_back(Entry);
1070 // FIXME: Is this necessary? Why only for protocol?
1071 Entry->setAlignment(4);
1072 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001073
1074 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001075}
1076
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001077llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001078 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1079
1080 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001081 // We use the initializer as a marker of whether this is a forward
1082 // reference or not. At module finalization we add the empty
1083 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001084 Entry =
1085 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001086 llvm::GlobalValue::ExternalLinkage,
1087 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001088 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001089 &CGM.getModule());
1090 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1091 UsedGlobals.push_back(Entry);
1092 // FIXME: Is this necessary? Why only for protocol?
1093 Entry->setAlignment(4);
1094 }
1095
1096 return Entry;
1097}
1098
1099/*
1100 struct _objc_protocol_extension {
1101 uint32_t size;
1102 struct objc_method_description_list *optional_instance_methods;
1103 struct objc_method_description_list *optional_class_methods;
1104 struct objc_property_list *instance_properties;
1105 };
1106*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001107llvm::Constant *
1108CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1109 const ConstantVector &OptInstanceMethods,
1110 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001111 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001112 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001113 std::vector<llvm::Constant*> Values(4);
1114 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001115 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001116 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1117 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001118 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1119 OptInstanceMethods);
1120 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001121 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1122 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001123 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1124 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001125 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1126 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001127 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001128
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001129 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001130 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1131 Values[3]->isNullValue())
1132 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1133
1134 llvm::Constant *Init =
1135 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1136 llvm::GlobalVariable *GV =
1137 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1138 llvm::GlobalValue::InternalLinkage,
1139 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001140 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001141 &CGM.getModule());
1142 // No special section, but goes in llvm.used
1143 UsedGlobals.push_back(GV);
1144
1145 return GV;
1146}
1147
1148/*
1149 struct objc_protocol_list {
1150 struct objc_protocol_list *next;
1151 long count;
1152 Protocol *list[];
1153 };
1154*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001155llvm::Constant *
1156CGObjCMac::EmitProtocolList(const std::string &Name,
1157 ObjCProtocolDecl::protocol_iterator begin,
1158 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001159 std::vector<llvm::Constant*> ProtocolRefs;
1160
Daniel Dunbardbc933702008-08-21 21:57:41 +00001161 for (; begin != end; ++begin)
1162 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163
1164 // Just return null for empty protocol lists
1165 if (ProtocolRefs.empty())
1166 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1167
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001168 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001169 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1170
1171 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001172 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001173 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1174 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1175 Values[2] =
1176 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1177 ProtocolRefs.size()),
1178 ProtocolRefs);
1179
1180 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1181 llvm::GlobalVariable *GV =
1182 new llvm::GlobalVariable(Init->getType(), false,
1183 llvm::GlobalValue::InternalLinkage,
1184 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001185 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001186 &CGM.getModule());
1187 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1188 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1189}
1190
1191/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001192 struct _objc_property {
1193 const char * const name;
1194 const char * const attributes;
1195 };
1196
1197 struct _objc_property_list {
1198 uint32_t entsize; // sizeof (struct _objc_property)
1199 uint32_t prop_count;
1200 struct _objc_property[prop_count];
1201 };
1202*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001203llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1204 const Decl *Container,
1205 const ObjCContainerDecl *OCD,
1206 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001207 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001208 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1209 E = OCD->prop_end(); I != E; ++I) {
1210 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001211 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001212 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001213 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1214 Prop));
1215 }
1216
1217 // Return null for empty list.
1218 if (Properties.empty())
1219 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1220
1221 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001222 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001223 std::vector<llvm::Constant*> Values(3);
1224 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1225 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1226 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1227 Properties.size());
1228 Values[2] = llvm::ConstantArray::get(AT, Properties);
1229 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1230
1231 llvm::GlobalVariable *GV =
1232 new llvm::GlobalVariable(Init->getType(), false,
1233 llvm::GlobalValue::InternalLinkage,
1234 Init,
1235 Name,
1236 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001237 if (ObjCABI == 2)
1238 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001239 // No special section on property lists?
1240 UsedGlobals.push_back(GV);
1241 return llvm::ConstantExpr::getBitCast(GV,
1242 ObjCTypes.PropertyListPtrTy);
1243
1244}
1245
1246/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001247 struct objc_method_description_list {
1248 int count;
1249 struct objc_method_description list[];
1250 };
1251*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001252llvm::Constant *
1253CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1254 std::vector<llvm::Constant*> Desc(2);
1255 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1256 ObjCTypes.SelectorPtrTy);
1257 Desc[1] = GetMethodVarType(MD);
1258 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1259 Desc);
1260}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001262llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1263 const char *Section,
1264 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001265 // Return null for empty list.
1266 if (Methods.empty())
1267 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1268
1269 std::vector<llvm::Constant*> Values(2);
1270 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1271 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1272 Methods.size());
1273 Values[1] = llvm::ConstantArray::get(AT, Methods);
1274 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1275
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001276 llvm::GlobalVariable *GV =
1277 new llvm::GlobalVariable(Init->getType(), false,
1278 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001279 Init, Name, &CGM.getModule());
1280 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001281 UsedGlobals.push_back(GV);
1282 return llvm::ConstantExpr::getBitCast(GV,
1283 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001284}
1285
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001286/*
1287 struct _objc_category {
1288 char *category_name;
1289 char *class_name;
1290 struct _objc_method_list *instance_methods;
1291 struct _objc_method_list *class_methods;
1292 struct _objc_protocol_list *protocols;
1293 uint32_t size; // <rdar://4585769>
1294 struct _objc_property_list *instance_properties;
1295 };
1296 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001297void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001298 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001299
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001300 // FIXME: This is poor design, the OCD should have a pointer to the
1301 // category decl. Additionally, note that Category can be null for
1302 // the @implementation w/o an @interface case. Sema should just
1303 // create one for us as it does for @implementation so everyone else
1304 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001305 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001306 const ObjCCategoryDecl *Category =
1307 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001308 std::string ExtName(Interface->getNameAsString() + "_" +
1309 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001310
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001311 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1312 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1313 e = OCD->instmeth_end(); i != e; ++i) {
1314 // Instance methods should always be defined.
1315 InstanceMethods.push_back(GetMethodConstant(*i));
1316 }
1317 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1318 e = OCD->classmeth_end(); i != e; ++i) {
1319 // Class methods should always be defined.
1320 ClassMethods.push_back(GetMethodConstant(*i));
1321 }
1322
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001323 std::vector<llvm::Constant*> Values(7);
1324 Values[0] = GetClassName(OCD->getIdentifier());
1325 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001326 Values[2] =
1327 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1328 ExtName,
1329 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001330 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001331 Values[3] =
1332 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1333 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001334 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001335 if (Category) {
1336 Values[4] =
1337 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1338 Category->protocol_begin(),
1339 Category->protocol_end());
1340 } else {
1341 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1342 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001343 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001344
1345 // If there is no category @interface then there can be no properties.
1346 if (Category) {
1347 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001348 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001349 } else {
1350 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1351 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001352
1353 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1354 Values);
1355
1356 llvm::GlobalVariable *GV =
1357 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1358 llvm::GlobalValue::InternalLinkage,
1359 Init,
1360 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1361 &CGM.getModule());
1362 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1363 UsedGlobals.push_back(GV);
1364 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001365}
1366
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001367// FIXME: Get from somewhere?
1368enum ClassFlags {
1369 eClassFlags_Factory = 0x00001,
1370 eClassFlags_Meta = 0x00002,
1371 // <rdr://5142207>
1372 eClassFlags_HasCXXStructors = 0x02000,
1373 eClassFlags_Hidden = 0x20000,
1374 eClassFlags_ABI2_Hidden = 0x00010,
1375 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1376};
1377
1378// <rdr://5142207&4705298&4843145>
1379static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1380 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1381 // FIXME: Support -fvisibility
1382 switch (attr->getVisibility()) {
1383 default:
1384 assert(0 && "Unknown visibility");
1385 return false;
1386 case VisibilityAttr::DefaultVisibility:
1387 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1388 return false;
1389 case VisibilityAttr::HiddenVisibility:
1390 return true;
1391 }
1392 } else {
1393 return false; // FIXME: Support -fvisibility
1394 }
1395}
1396
1397/*
1398 struct _objc_class {
1399 Class isa;
1400 Class super_class;
1401 const char *name;
1402 long version;
1403 long info;
1404 long instance_size;
1405 struct _objc_ivar_list *ivars;
1406 struct _objc_method_list *methods;
1407 struct _objc_cache *cache;
1408 struct _objc_protocol_list *protocols;
1409 // Objective-C 1.0 extensions (<rdr://4585769>)
1410 const char *ivar_layout;
1411 struct _objc_class_ext *ext;
1412 };
1413
1414 See EmitClassExtension();
1415 */
1416void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001417 DefinedSymbols.insert(ID->getIdentifier());
1418
Chris Lattner8ec03f52008-11-24 03:54:41 +00001419 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001420 // FIXME: Gross
1421 ObjCInterfaceDecl *Interface =
1422 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001423 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001424 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001425 Interface->protocol_begin(),
1426 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001428 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001429 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001430 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001431
1432 // FIXME: Set CXX-structors flag.
1433 if (IsClassHidden(ID->getClassInterface()))
1434 Flags |= eClassFlags_Hidden;
1435
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001436 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1437 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1438 e = ID->instmeth_end(); i != e; ++i) {
1439 // Instance methods should always be defined.
1440 InstanceMethods.push_back(GetMethodConstant(*i));
1441 }
1442 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1443 e = ID->classmeth_end(); i != e; ++i) {
1444 // Class methods should always be defined.
1445 ClassMethods.push_back(GetMethodConstant(*i));
1446 }
1447
1448 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1449 e = ID->propimpl_end(); i != e; ++i) {
1450 ObjCPropertyImplDecl *PID = *i;
1451
1452 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1453 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1454
1455 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1456 if (llvm::Constant *C = GetMethodConstant(MD))
1457 InstanceMethods.push_back(C);
1458 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1459 if (llvm::Constant *C = GetMethodConstant(MD))
1460 InstanceMethods.push_back(C);
1461 }
1462 }
1463
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001464 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001465 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001467 // Record a reference to the super class.
1468 LazySymbols.insert(Super->getIdentifier());
1469
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001470 Values[ 1] =
1471 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1472 ObjCTypes.ClassPtrTy);
1473 } else {
1474 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1475 }
1476 Values[ 2] = GetClassName(ID->getIdentifier());
1477 // Version is always 0.
1478 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1479 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1480 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001481 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001482 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001483 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001484 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001485 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001486 // cache is always NULL.
1487 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1488 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001489 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001490 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001491 Values[11] = EmitClassExtension(ID);
1492 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1493 Values);
1494
1495 llvm::GlobalVariable *GV =
1496 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1497 llvm::GlobalValue::InternalLinkage,
1498 Init,
1499 std::string("\01L_OBJC_CLASS_")+ClassName,
1500 &CGM.getModule());
1501 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1502 UsedGlobals.push_back(GV);
1503 // FIXME: Why?
1504 GV->setAlignment(32);
1505 DefinedClasses.push_back(GV);
1506}
1507
1508llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1509 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001510 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001511 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001512 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001513 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001514
1515 if (IsClassHidden(ID->getClassInterface()))
1516 Flags |= eClassFlags_Hidden;
1517
1518 std::vector<llvm::Constant*> Values(12);
1519 // The isa for the metaclass is the root of the hierarchy.
1520 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1521 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1522 Root = Super;
1523 Values[ 0] =
1524 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1525 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001526 // The super class for the metaclass is emitted as the name of the
1527 // super class. The runtime fixes this up to point to the
1528 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001529 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1530 Values[ 1] =
1531 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1532 ObjCTypes.ClassPtrTy);
1533 } else {
1534 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1535 }
1536 Values[ 2] = GetClassName(ID->getIdentifier());
1537 // Version is always 0.
1538 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1539 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1540 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001541 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001542 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001543 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001544 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001545 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001546 // cache is always NULL.
1547 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1548 Values[ 9] = Protocols;
1549 // ivar_layout for metaclass is always NULL.
1550 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1551 // The class extension is always unused for metaclasses.
1552 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1553 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1554 Values);
1555
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001556 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001557 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001558
1559 // Check for a forward reference.
1560 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1561 if (GV) {
1562 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1563 "Forward metaclass reference has incorrect type.");
1564 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1565 GV->setInitializer(Init);
1566 } else {
1567 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1568 llvm::GlobalValue::InternalLinkage,
1569 Init, Name,
1570 &CGM.getModule());
1571 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001572 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1573 UsedGlobals.push_back(GV);
1574 // FIXME: Why?
1575 GV->setAlignment(32);
1576
1577 return GV;
1578}
1579
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001580llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001581 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001582
1583 // FIXME: Should we look these up somewhere other than the
1584 // module. Its a bit silly since we only generate these while
1585 // processing an implementation, so exactly one pointer would work
1586 // if know when we entered/exitted an implementation block.
1587
1588 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001589 // Previously, metaclass with internal linkage may have been defined.
1590 // pass 'true' as 2nd argument so it is returned.
1591 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001592 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1593 "Forward metaclass reference has incorrect type.");
1594 return GV;
1595 } else {
1596 // Generate as an external reference to keep a consistent
1597 // module. This will be patched up when we emit the metaclass.
1598 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1599 llvm::GlobalValue::ExternalLinkage,
1600 0,
1601 Name,
1602 &CGM.getModule());
1603 }
1604}
1605
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001606/*
1607 struct objc_class_ext {
1608 uint32_t size;
1609 const char *weak_ivar_layout;
1610 struct _objc_property_list *properties;
1611 };
1612*/
1613llvm::Constant *
1614CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1615 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001616 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001617
1618 std::vector<llvm::Constant*> Values(3);
1619 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001620 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001621 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001622 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001623 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001624
1625 // Return null if no extension bits are used.
1626 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1627 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1628
1629 llvm::Constant *Init =
1630 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1631 llvm::GlobalVariable *GV =
1632 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1633 llvm::GlobalValue::InternalLinkage,
1634 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001635 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001636 &CGM.getModule());
1637 // No special section, but goes in llvm.used
1638 UsedGlobals.push_back(GV);
1639
1640 return GV;
1641}
1642
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001643/// countInheritedIvars - count number of ivars in class and its super class(s)
1644///
1645static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1646 int count = 0;
1647 if (!OI)
1648 return 0;
1649 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1650 if (SuperClass)
1651 count += countInheritedIvars(SuperClass);
1652 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1653 E = OI->ivar_end(); I != E; ++I)
1654 ++count;
1655 return count;
1656}
1657
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001658/// getInterfaceDeclForIvar - Get the interface declaration node where
1659/// this ivar is declared in.
1660/// FIXME. Ideally, this info should be in the ivar node. But currently
1661/// it is not and prevailing wisdom is that ASTs should not have more
1662/// info than is absolutely needed, even though this info reflects the
1663/// source language.
1664///
1665static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1666 const ObjCInterfaceDecl *OI,
1667 const ObjCIvarDecl *IVD) {
1668 if (!OI)
1669 return 0;
1670 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1671 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1672 E = OI->ivar_end(); I != E; ++I)
1673 if ((*I)->getIdentifier() == IVD->getIdentifier())
1674 return OI;
1675 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1676}
1677
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001678/*
1679 struct objc_ivar {
1680 char *ivar_name;
1681 char *ivar_type;
1682 int ivar_offset;
1683 };
1684
1685 struct objc_ivar_list {
1686 int ivar_count;
1687 struct objc_ivar list[count];
1688 };
1689 */
1690llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001691 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001692 std::vector<llvm::Constant*> Ivars, Ivar(3);
1693
1694 // When emitting the root class GCC emits ivar entries for the
1695 // actual class structure. It is not clear if we need to follow this
1696 // behavior; for now lets try and get away with not doing it. If so,
1697 // the cleanest solution would be to make up an ObjCInterfaceDecl
1698 // for the class.
1699 if (ForClass)
1700 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001701
1702 ObjCInterfaceDecl *OID =
1703 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1704 const llvm::Type *InterfaceTy =
1705 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001706 const llvm::StructLayout *Layout =
1707 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001708
1709 RecordDecl::field_iterator ifield, pfield;
1710 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001711 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1712 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001713 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001714 if (Field->getIdentifier())
1715 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1716 else
1717 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001718 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001719 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001720 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001721 }
1722
1723 // Return null for empty list.
1724 if (Ivars.empty())
1725 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1726
1727 std::vector<llvm::Constant*> Values(2);
1728 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1729 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1730 Ivars.size());
1731 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1732 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1733
1734 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1735 "\01L_OBJC_INSTANCE_VARIABLES_");
1736 llvm::GlobalVariable *GV =
1737 new llvm::GlobalVariable(Init->getType(), false,
1738 llvm::GlobalValue::InternalLinkage,
1739 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001740 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001741 &CGM.getModule());
1742 if (ForClass) {
1743 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1744 // FIXME: Why is this only here?
1745 GV->setAlignment(32);
1746 } else {
1747 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1748 }
1749 UsedGlobals.push_back(GV);
1750 return llvm::ConstantExpr::getBitCast(GV,
1751 ObjCTypes.IvarListPtrTy);
1752}
1753
1754/*
1755 struct objc_method {
1756 SEL method_name;
1757 char *method_types;
1758 void *method;
1759 };
1760
1761 struct objc_method_list {
1762 struct objc_method_list *obsolete;
1763 int count;
1764 struct objc_method methods_list[count];
1765 };
1766*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001767
1768/// GetMethodConstant - Return a struct objc_method constant for the
1769/// given method if it has been defined. The result is null if the
1770/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001771llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001772 // FIXME: Use DenseMap::lookup
1773 llvm::Function *Fn = MethodDefinitions[MD];
1774 if (!Fn)
1775 return 0;
1776
1777 std::vector<llvm::Constant*> Method(3);
1778 Method[0] =
1779 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1780 ObjCTypes.SelectorPtrTy);
1781 Method[1] = GetMethodVarType(MD);
1782 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1783 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1784}
1785
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001786llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1787 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001788 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789 // Return null for empty list.
1790 if (Methods.empty())
1791 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1792
1793 std::vector<llvm::Constant*> Values(3);
1794 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1795 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1796 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1797 Methods.size());
1798 Values[2] = llvm::ConstantArray::get(AT, Methods);
1799 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1800
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001801 llvm::GlobalVariable *GV =
1802 new llvm::GlobalVariable(Init->getType(), false,
1803 llvm::GlobalValue::InternalLinkage,
1804 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001805 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001806 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001807 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001808 UsedGlobals.push_back(GV);
1809 return llvm::ConstantExpr::getBitCast(GV,
1810 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001811}
1812
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001813llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001814 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001815 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001816 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001817
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001818 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001819 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001820 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001821 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001822 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001823 llvm::GlobalValue::InternalLinkage,
1824 Name,
1825 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001826 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001827
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001828 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001829}
1830
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001831uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
1832 FieldDecl *Field) {
1833 return Field->isBitField()
1834 ? CGM.getTypes().getLLVMFieldNo(Field)
1835 : Layout->getElementOffset(
1836 CGM.getTypes().getLLVMFieldNo(Field));
1837}
1838
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001839llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001840 // Abuse this interface function as a place to finalize.
1841 FinishModule();
1842
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001843 return NULL;
1844}
1845
Daniel Dunbar49f66022008-09-24 03:38:44 +00001846llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1847 return ObjCTypes.GetPropertyFn;
1848}
1849
1850llvm::Function *CGObjCMac::GetPropertySetFunction() {
1851 return ObjCTypes.SetPropertyFn;
1852}
1853
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001854llvm::Function *CGObjCMac::EnumerationMutationFunction()
1855{
1856 return ObjCTypes.EnumerationMutationFn;
1857}
1858
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001859/*
1860
1861Objective-C setjmp-longjmp (sjlj) Exception Handling
1862--
1863
1864The basic framework for a @try-catch-finally is as follows:
1865{
1866 objc_exception_data d;
1867 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001868 bool _call_try_exit = true;
1869
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001870 objc_exception_try_enter(&d);
1871 if (!setjmp(d.jmp_buf)) {
1872 ... try body ...
1873 } else {
1874 // exception path
1875 id _caught = objc_exception_extract(&d);
1876
1877 // enter new try scope for handlers
1878 if (!setjmp(d.jmp_buf)) {
1879 ... match exception and execute catch blocks ...
1880
1881 // fell off end, rethrow.
1882 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001883 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001884 } else {
1885 // exception in catch block
1886 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001887 _call_try_exit = false;
1888 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001889 }
1890 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001891 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001892
1893finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001894 if (_call_try_exit)
1895 objc_exception_try_exit(&d);
1896
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001897 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001898 ... dispatch to finally destination ...
1899
1900finally_rethrow:
1901 objc_exception_throw(_rethrow);
1902
1903finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001904}
1905
1906This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001907uses _rethrow to determine if objc_exception_try_exit should be called
1908and if the object should be rethrown. This breaks in the face of
1909throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001910
1911We specialize this framework for a few particular circumstances:
1912
1913 - If there are no catch blocks, then we avoid emitting the second
1914 exception handling context.
1915
1916 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1917 e)) we avoid emitting the code to rethrow an uncaught exception.
1918
1919 - FIXME: If there is no @finally block we can do a few more
1920 simplifications.
1921
1922Rethrows and Jumps-Through-Finally
1923--
1924
1925Support for implicit rethrows and jumping through the finally block is
1926handled by storing the current exception-handling context in
1927ObjCEHStack.
1928
Daniel Dunbar898d5082008-09-30 01:06:03 +00001929In order to implement proper @finally semantics, we support one basic
1930mechanism for jumping through the finally block to an arbitrary
1931destination. Constructs which generate exits from a @try or @catch
1932block use this mechanism to implement the proper semantics by chaining
1933jumps, as necessary.
1934
1935This mechanism works like the one used for indirect goto: we
1936arbitrarily assign an ID to each destination and store the ID for the
1937destination in a variable prior to entering the finally block. At the
1938end of the finally block we simply create a switch to the proper
1939destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001940
1941Code gen for @synchronized(expr) stmt;
1942Effectively generating code for:
1943objc_sync_enter(expr);
1944@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001945*/
1946
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001947void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1948 const Stmt &S) {
1949 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001950 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001951 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001952 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001953 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1954 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1955 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001956
1957 // For @synchronized, call objc_sync_enter(sync.expr). The
1958 // evaluation of the expression must occur before we enter the
1959 // @synchronized. We can safely avoid a temp here because jumps into
1960 // @synchronized are illegal & this will dominate uses.
1961 llvm::Value *SyncArg = 0;
1962 if (!isTry) {
1963 SyncArg =
1964 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1965 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1966 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1967 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001968
1969 // Push an EH context entry, used for handling rethrows and jumps
1970 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001971 CGF.PushCleanupBlock(FinallyBlock);
1972
Anders Carlsson273558f2009-02-07 21:37:21 +00001973 CGF.ObjCEHValueStack.push_back(0);
1974
Daniel Dunbar898d5082008-09-30 01:06:03 +00001975 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001976 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1977 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001978 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1979 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001980 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1981 "_call_try_exit");
1982 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1983
Anders Carlsson80f25672008-09-09 17:59:25 +00001984 // Enter a new try block and call setjmp.
1985 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1986 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1987 "jmpbufarray");
1988 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1989 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1990 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001991
Daniel Dunbar55e87422008-11-11 02:29:29 +00001992 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1993 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001994 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001995 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001996
1997 // Emit the @try block.
1998 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001999 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2000 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002001 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002002
2003 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002004 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002005
2006 // Retrieve the exception object. We may emit multiple blocks but
2007 // nothing can cross this so the value is already in SSA form.
2008 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2009 ExceptionData,
2010 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002011 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002012 if (!isTry)
2013 {
2014 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002015 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002016 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002017 }
2018 else if (const ObjCAtCatchStmt* CatchStmt =
2019 cast<ObjCAtTryStmt>(S).getCatchStmts())
2020 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002021 // Enter a new exception try block (in case a @catch block throws
2022 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002023 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002024
Anders Carlsson80f25672008-09-09 17:59:25 +00002025 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2026 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002027 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002028
Daniel Dunbar55e87422008-11-11 02:29:29 +00002029 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2030 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002031 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002032
2033 CGF.EmitBlock(CatchBlock);
2034
Daniel Dunbar55e40722008-09-27 07:03:52 +00002035 // Handle catch list. As a special case we check if everything is
2036 // matched and avoid generating code for falling off the end if
2037 // so.
2038 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002039 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002040 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002041
Steve Naroff7ba138a2009-03-03 19:52:17 +00002042 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002043 const PointerType *PT = 0;
2044
Anders Carlsson80f25672008-09-09 17:59:25 +00002045 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002046 if (!CatchParam) {
2047 AllMatched = true;
2048 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002049 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002050
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002051 // catch(id e) always matches.
2052 // FIXME: For the time being we also match id<X>; this should
2053 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002054 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002055 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002056 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002057 }
2058
Daniel Dunbar55e40722008-09-27 07:03:52 +00002059 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002060 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002061 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002062 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002063 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002064 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002065
Anders Carlssondde0a942008-09-11 09:15:33 +00002066 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002067 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002068 break;
2069 }
2070
Daniel Dunbar129271a2008-09-27 07:36:24 +00002071 assert(PT && "Unexpected non-pointer type in @catch");
2072 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002073 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002074 assert(ObjCType && "Catch parameter must have Objective-C type!");
2075
2076 // Check if the @catch block matches the exception object.
2077 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2078
Anders Carlsson80f25672008-09-09 17:59:25 +00002079 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2080 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002081
Daniel Dunbar55e87422008-11-11 02:29:29 +00002082 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002083
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002084 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002085 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002086
2087 // Emit the @catch block.
2088 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002089 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002090 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002091
2092 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002093 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002094 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002095 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002096
2097 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002098 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002099
2100 CGF.EmitBlock(NextCatchBlock);
2101 }
2102
Daniel Dunbar55e40722008-09-27 07:03:52 +00002103 if (!AllMatched) {
2104 // None of the handlers caught the exception, so store it to be
2105 // rethrown at the end of the @finally block.
2106 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002107 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002108 }
2109
2110 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002111 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002112 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2113 ExceptionData),
2114 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002115 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002116 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002117 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002118 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002119 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002120 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002121 }
2122
Daniel Dunbar898d5082008-09-30 01:06:03 +00002123 // Pop the exception-handling stack entry. It is important to do
2124 // this now, because the code in the @finally block is not in this
2125 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002126 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2127
Anders Carlsson273558f2009-02-07 21:37:21 +00002128 CGF.ObjCEHValueStack.pop_back();
2129
Anders Carlsson80f25672008-09-09 17:59:25 +00002130 // Emit the @finally block.
2131 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002132 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2133
2134 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2135
2136 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002137 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002138
2139 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002140 if (isTry) {
2141 if (const ObjCAtFinallyStmt* FinallyStmt =
2142 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2143 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002144 } else {
2145 // Emit objc_sync_exit(expr); as finally's sole statement for
2146 // @synchronized.
2147 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002148 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002149
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002150 // Emit the switch block
2151 if (Info.SwitchBlock)
2152 CGF.EmitBlock(Info.SwitchBlock);
2153 if (Info.EndBlock)
2154 CGF.EmitBlock(Info.EndBlock);
2155
Daniel Dunbar898d5082008-09-30 01:06:03 +00002156 CGF.EmitBlock(FinallyRethrow);
2157 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2158 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002159 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002160
2161 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002162}
2163
2164void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002165 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002166 llvm::Value *ExceptionAsObject;
2167
2168 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2169 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2170 ExceptionAsObject =
2171 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2172 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002173 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002174 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002175 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002176 }
2177
2178 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002179 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002180
2181 // Clear the insertion point to indicate we are in unreachable code.
2182 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002183}
2184
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002185/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002186/// object: objc_read_weak (id *src)
2187///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002188llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002189 llvm::Value *AddrWeakObj)
2190{
Eli Friedman8339b352009-03-07 03:57:15 +00002191 const llvm::Type* DestTy =
2192 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002193 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002194 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002195 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002196 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002197 return read_weak;
2198}
2199
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002200/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2201/// objc_assign_weak (id src, id *dst)
2202///
2203void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2204 llvm::Value *src, llvm::Value *dst)
2205{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002206 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2207 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002208 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2209 src, dst, "weakassign");
2210 return;
2211}
2212
Fariborz Jahanian58626502008-11-19 00:59:10 +00002213/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2214/// objc_assign_global (id src, id *dst)
2215///
2216void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2217 llvm::Value *src, llvm::Value *dst)
2218{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002219 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2220 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002221 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2222 src, dst, "globalassign");
2223 return;
2224}
2225
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002226/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2227/// objc_assign_ivar (id src, id *dst)
2228///
2229void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2230 llvm::Value *src, llvm::Value *dst)
2231{
2232 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2233 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2234 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2235 src, dst, "assignivar");
2236 return;
2237}
2238
Fariborz Jahanian58626502008-11-19 00:59:10 +00002239/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2240/// objc_assign_strongCast (id src, id *dst)
2241///
2242void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2243 llvm::Value *src, llvm::Value *dst)
2244{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002245 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2246 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002247 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2248 src, dst, "weakassign");
2249 return;
2250}
2251
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002252/// EmitObjCValueForIvar - Code Gen for ivar reference.
2253///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002254LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2255 QualType ObjectTy,
2256 llvm::Value *BaseValue,
2257 const ObjCIvarDecl *Ivar,
2258 const FieldDecl *Field,
2259 unsigned CVRQualifiers) {
2260 if (Ivar->isBitField())
2261 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2262 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002263 // TODO: Add a special case for isa (index 0)
2264 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2265 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002266 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002267 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2268 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002269 LValue::SetObjCIvar(LV, true);
2270 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002271}
2272
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002273llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2274 ObjCInterfaceDecl *Interface,
2275 const ObjCIvarDecl *Ivar) {
2276 const llvm::Type *InterfaceLTy =
2277 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2278 const llvm::StructLayout *Layout =
2279 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2280 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002281 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002282 return llvm::ConstantInt::get(
2283 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2284 Offset);
2285}
2286
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002287/* *** Private Interface *** */
2288
2289/// EmitImageInfo - Emit the image info marker used to encode some module
2290/// level information.
2291///
2292/// See: <rdr://4810609&4810587&4810587>
2293/// struct IMAGE_INFO {
2294/// unsigned version;
2295/// unsigned flags;
2296/// };
2297enum ImageInfoFlags {
2298 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2299 eImageInfo_GarbageCollected = (1 << 1),
2300 eImageInfo_GCOnly = (1 << 2)
2301};
2302
2303void CGObjCMac::EmitImageInfo() {
2304 unsigned version = 0; // Version is unused?
2305 unsigned flags = 0;
2306
2307 // FIXME: Fix and continue?
2308 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2309 flags |= eImageInfo_GarbageCollected;
2310 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2311 flags |= eImageInfo_GCOnly;
2312
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002313 // Emitted as int[2];
2314 llvm::Constant *values[2] = {
2315 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2316 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2317 };
2318 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002319 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002320 new llvm::GlobalVariable(AT, true,
2321 llvm::GlobalValue::InternalLinkage,
2322 llvm::ConstantArray::get(AT, values, 2),
2323 "\01L_OBJC_IMAGE_INFO",
2324 &CGM.getModule());
2325
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002326 if (ObjCABI == 1) {
2327 GV->setSection("__OBJC, __image_info,regular");
2328 } else {
2329 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2330 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002331
2332 UsedGlobals.push_back(GV);
2333}
2334
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002335
2336// struct objc_module {
2337// unsigned long version;
2338// unsigned long size;
2339// const char *name;
2340// Symtab symtab;
2341// };
2342
2343// FIXME: Get from somewhere
2344static const int ModuleVersion = 7;
2345
2346void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002347 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002348
2349 std::vector<llvm::Constant*> Values(4);
2350 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2351 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002352 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002353 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002354 Values[3] = EmitModuleSymbols();
2355
2356 llvm::GlobalVariable *GV =
2357 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2358 llvm::GlobalValue::InternalLinkage,
2359 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2360 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002361 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002362 &CGM.getModule());
2363 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2364 UsedGlobals.push_back(GV);
2365}
2366
2367llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002368 unsigned NumClasses = DefinedClasses.size();
2369 unsigned NumCategories = DefinedCategories.size();
2370
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002371 // Return null if no symbols were defined.
2372 if (!NumClasses && !NumCategories)
2373 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2374
2375 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002376 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2377 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2378 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2379 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2380
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002381 // The runtime expects exactly the list of defined classes followed
2382 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002383 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002384 for (unsigned i=0; i<NumClasses; i++)
2385 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2386 ObjCTypes.Int8PtrTy);
2387 for (unsigned i=0; i<NumCategories; i++)
2388 Symbols[NumClasses + i] =
2389 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2390 ObjCTypes.Int8PtrTy);
2391
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002392 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002393 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002394 NumClasses + NumCategories),
2395 Symbols);
2396
2397 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2398
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002399 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002400 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002401 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002402 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002403 "\01L_OBJC_SYMBOLS",
2404 &CGM.getModule());
2405 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2406 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002407 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2408}
2409
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002410llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002411 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002412 LazySymbols.insert(ID->getIdentifier());
2413
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002414 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2415
2416 if (!Entry) {
2417 llvm::Constant *Casted =
2418 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2419 ObjCTypes.ClassPtrTy);
2420 Entry =
2421 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2422 llvm::GlobalValue::InternalLinkage,
2423 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2424 &CGM.getModule());
2425 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2426 UsedGlobals.push_back(Entry);
2427 }
2428
2429 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430}
2431
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002432llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002433 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2434
2435 if (!Entry) {
2436 llvm::Constant *Casted =
2437 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2438 ObjCTypes.SelectorPtrTy);
2439 Entry =
2440 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2441 llvm::GlobalValue::InternalLinkage,
2442 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2443 &CGM.getModule());
2444 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2445 UsedGlobals.push_back(Entry);
2446 }
2447
2448 return Builder.CreateLoad(Entry, false, "tmp");
2449}
2450
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002451llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002452 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002453
2454 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002455 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002456 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002457 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002458 llvm::GlobalValue::InternalLinkage,
2459 C, "\01L_OBJC_CLASS_NAME_",
2460 &CGM.getModule());
2461 Entry->setSection("__TEXT,__cstring,cstring_literals");
2462 UsedGlobals.push_back(Entry);
2463 }
2464
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002465 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002466}
2467
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002468/// GetIvarLayoutName - Returns a unique constant for the given
2469/// ivar layout bitmap.
2470llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2471 const ObjCCommonTypesHelper &ObjCTypes) {
2472 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2473}
2474
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002475void CGObjCCommonMac::BuildAggrIvarLayout(RecordDecl *RD,
2476 const std::vector<FieldDecl*>& RecFields,
2477 unsigned int BytePos, bool ForStrongLayout,
2478 int &Index, int &SkIndex, bool &HasUnion) {
2479 return;
2480}
2481
2482/// BuildIvarLayout - Builds ivar layout bitmap for the class
2483/// implementation for the __strong or __weak case.
2484/// The layout map displays which words in ivar list must be skipped
2485/// and which must be scanned by GC (see below). String is built of bytes.
2486/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2487/// of words to skip and right nibble is count of words to scan. So, each
2488/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2489/// represented by a 0x00 byte which also ends the string.
2490/// 1. when ForStrongLayout is true, following ivars are scanned:
2491/// - id, Class
2492/// - object *
2493/// - __strong anything
2494///
2495/// 2. When ForStrongLayout is false, following ivars are scanned:
2496/// - __weak anything
2497///
2498llvm::Constant *CGObjCCommonMac::BuildIvarLayout(ObjCImplementationDecl *OMD,
2499 bool ForStrongLayout) {
2500 int iIndex = -1;
2501 int iSkIndex = -1;
2502 bool hasUnion = false;
2503
2504 std::vector<FieldDecl*> RecFields;
2505 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2506 CGM.getContext().CollectObjCIvars(OI, RecFields);
2507 if (RecFields.empty())
2508 return 0;
2509 BuildAggrIvarLayout (0, RecFields, 0, ForStrongLayout,
2510 iIndex, iSkIndex, hasUnion);
2511 return 0;
2512}
2513
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002514llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002515 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2516
2517 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002518 // FIXME: Avoid std::string copying.
2519 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002520 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002521 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002522 llvm::GlobalValue::InternalLinkage,
2523 C, "\01L_OBJC_METH_VAR_NAME_",
2524 &CGM.getModule());
2525 Entry->setSection("__TEXT,__cstring,cstring_literals");
2526 UsedGlobals.push_back(Entry);
2527 }
2528
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002529 return getConstantGEP(Entry, 0, 0);
2530}
2531
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002532// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002533llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002534 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2535}
2536
2537// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002538llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002539 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2540}
2541
Devang Patel7794bb82009-03-04 18:21:39 +00002542llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2543 std::string TypeStr;
2544 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2545
2546 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002547
2548 if (!Entry) {
Devang Patel7794bb82009-03-04 18:21:39 +00002549 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002550 Entry =
2551 new llvm::GlobalVariable(C->getType(), false,
2552 llvm::GlobalValue::InternalLinkage,
2553 C, "\01L_OBJC_METH_VAR_TYPE_",
2554 &CGM.getModule());
2555 Entry->setSection("__TEXT,__cstring,cstring_literals");
2556 UsedGlobals.push_back(Entry);
2557 }
2558
2559 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002560}
2561
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002562llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002563 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002564 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2565 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002566
2567 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2568
2569 if (!Entry) {
2570 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2571 Entry =
2572 new llvm::GlobalVariable(C->getType(), false,
2573 llvm::GlobalValue::InternalLinkage,
2574 C, "\01L_OBJC_METH_VAR_TYPE_",
2575 &CGM.getModule());
2576 Entry->setSection("__TEXT,__cstring,cstring_literals");
2577 UsedGlobals.push_back(Entry);
2578 }
2579
2580 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002581}
2582
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002583// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002584llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002585 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2586
2587 if (!Entry) {
2588 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2589 Entry =
2590 new llvm::GlobalVariable(C->getType(), false,
2591 llvm::GlobalValue::InternalLinkage,
2592 C, "\01L_OBJC_PROP_NAME_ATTR_",
2593 &CGM.getModule());
2594 Entry->setSection("__TEXT,__cstring,cstring_literals");
2595 UsedGlobals.push_back(Entry);
2596 }
2597
2598 return getConstantGEP(Entry, 0, 0);
2599}
2600
2601// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002602// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002603llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002604 const Decl *Container) {
2605 std::string TypeStr;
2606 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002607 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2608}
2609
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002610void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2611 const ObjCContainerDecl *CD,
2612 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002613 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002614 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002615 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002616 assert (CD && "Missing container decl in GetNameForMethod");
2617 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002618 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2619 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002620 NameOut += ' ';
2621 NameOut += D->getSelector().getAsString();
2622 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002623}
2624
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002625/// GetFirstIvarInRecord - This routine returns the record for the
2626/// implementation of the fiven class OID. It also returns field
2627/// corresponding to the first ivar in the class in FIV. It also
2628/// returns the one before the first ivar.
2629///
2630const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2631 const ObjCInterfaceDecl *OID,
2632 RecordDecl::field_iterator &FIV,
2633 RecordDecl::field_iterator &PIV) {
2634 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2635 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2636 RecordDecl::field_iterator ifield = RD->field_begin();
2637 RecordDecl::field_iterator pfield = RD->field_end();
2638 while (countSuperClassIvars-- > 0) {
2639 pfield = ifield;
2640 ++ifield;
2641 }
2642 FIV = ifield;
2643 PIV = pfield;
2644 return RD;
2645}
2646
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002647void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002648 EmitModuleInfo();
2649
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002650 // Emit the dummy bodies for any protocols which were referenced but
2651 // never defined.
2652 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2653 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2654 if (i->second->hasInitializer())
2655 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002656
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002657 std::vector<llvm::Constant*> Values(5);
2658 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2659 Values[1] = GetClassName(i->first);
2660 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2661 Values[3] = Values[4] =
2662 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2663 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2664 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2665 Values));
2666 }
2667
2668 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002669 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002670 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002671 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002672 }
2673
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002674 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002675 llvm::GlobalValue *GV =
2676 new llvm::GlobalVariable(AT, false,
2677 llvm::GlobalValue::AppendingLinkage,
2678 llvm::ConstantArray::get(AT, Used),
2679 "llvm.used",
2680 &CGM.getModule());
2681
2682 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002683
2684 // Add assembler directives to add lazy undefined symbol references
2685 // for classes which are referenced but not defined. This is
2686 // important for correct linker interaction.
2687
2688 // FIXME: Uh, this isn't particularly portable.
2689 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002690
2691 if (!CGM.getModule().getModuleInlineAsm().empty())
2692 s << "\n";
2693
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002694 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2695 e = LazySymbols.end(); i != e; ++i) {
2696 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2697 }
2698 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2699 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002700 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002701 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2702 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002703
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002704 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002705}
2706
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002707CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002708 : CGObjCCommonMac(cgm),
2709 ObjCTypes(cgm)
2710{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002711 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002712 ObjCABI = 2;
2713}
2714
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002715/* *** */
2716
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002717ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2718: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002719{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002720 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2721 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002722
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002723 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002724 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002725 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002726 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2727
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002728 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002729 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002730 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002731
2732 // FIXME: It would be nice to unify this with the opaque type, so
2733 // that the IR comes out a bit cleaner.
2734 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2735 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002736
2737 // I'm not sure I like this. The implicit coordination is a bit
2738 // gross. We should solve this in a reasonable fashion because this
2739 // is a pretty common task (match some runtime data structure with
2740 // an LLVM data structure).
2741
2742 // FIXME: This is leaked.
2743 // FIXME: Merge with rewriter code?
2744
2745 // struct _objc_super {
2746 // id self;
2747 // Class cls;
2748 // }
2749 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2750 SourceLocation(),
2751 &Ctx.Idents.get("_objc_super"));
2752 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2753 Ctx.getObjCIdType(), 0, false));
2754 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2755 Ctx.getObjCClassType(), 0, false));
2756 RD->completeDefinition(Ctx);
2757
2758 SuperCTy = Ctx.getTagDeclType(RD);
2759 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2760
2761 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002762 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2763
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002764 // struct _prop_t {
2765 // char *name;
2766 // char *attributes;
2767 // }
2768 PropertyTy = llvm::StructType::get(Int8PtrTy,
2769 Int8PtrTy,
2770 NULL);
2771 CGM.getModule().addTypeName("struct._prop_t",
2772 PropertyTy);
2773
2774 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002775 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002776 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002777 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002778 // }
2779 PropertyListTy = llvm::StructType::get(IntTy,
2780 IntTy,
2781 llvm::ArrayType::get(PropertyTy, 0),
2782 NULL);
2783 CGM.getModule().addTypeName("struct._prop_list_t",
2784 PropertyListTy);
2785 // struct _prop_list_t *
2786 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2787
2788 // struct _objc_method {
2789 // SEL _cmd;
2790 // char *method_type;
2791 // char *_imp;
2792 // }
2793 MethodTy = llvm::StructType::get(SelectorPtrTy,
2794 Int8PtrTy,
2795 Int8PtrTy,
2796 NULL);
2797 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002798
2799 // struct _objc_cache *
2800 CacheTy = llvm::OpaqueType::get();
2801 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2802 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002803
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002804 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002805
2806 QualType IdType = Ctx.getObjCIdType();
2807 QualType SelType = Ctx.getObjCSelType();
2808 llvm::SmallVector<QualType,16> Params;
2809 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002810
2811 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002812 Params.push_back(IdType);
2813 Params.push_back(SelType);
2814 Params.push_back(Ctx.LongTy);
2815 Params.push_back(Ctx.BoolTy);
2816 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2817 false);
2818 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002819
2820 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2821 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002822 Params.push_back(IdType);
2823 Params.push_back(SelType);
2824 Params.push_back(Ctx.LongTy);
2825 Params.push_back(IdType);
2826 Params.push_back(Ctx.BoolTy);
2827 Params.push_back(Ctx.BoolTy);
2828 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2829 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2830
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002831 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002832
2833 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002834 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002835 Params.push_back(IdType);
2836 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2837 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2838 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002839
2840 // gc's API
2841 // id objc_read_weak (id *)
2842 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002843 Params.push_back(Ctx.getPointerType(IdType));
2844 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2845 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2846
2847 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002848 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002849 Params.push_back(IdType);
2850 Params.push_back(Ctx.getPointerType(IdType));
2851
2852 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2853 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2854 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2855 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2856 GcAssignStrongCastFn =
2857 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002858
2859 // void objc_exception_throw(id)
2860 Params.clear();
2861 Params.push_back(IdType);
2862
2863 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002864 ExceptionThrowFn =
2865 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002866
2867 // synchronized APIs
2868 // void objc_sync_enter (id)
2869 // void objc_sync_exit (id)
2870 Params.clear();
2871 Params.push_back(IdType);
2872
2873 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2874 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2875 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002876}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002877
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002878ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2879 : ObjCCommonTypesHelper(cgm)
2880{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002881 // struct _objc_method_description {
2882 // SEL name;
2883 // char *types;
2884 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002885 MethodDescriptionTy =
2886 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002887 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002888 NULL);
2889 CGM.getModule().addTypeName("struct._objc_method_description",
2890 MethodDescriptionTy);
2891
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002892 // struct _objc_method_description_list {
2893 // int count;
2894 // struct _objc_method_description[1];
2895 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002896 MethodDescriptionListTy =
2897 llvm::StructType::get(IntTy,
2898 llvm::ArrayType::get(MethodDescriptionTy, 0),
2899 NULL);
2900 CGM.getModule().addTypeName("struct._objc_method_description_list",
2901 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002902
2903 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002904 MethodDescriptionListPtrTy =
2905 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2906
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002907 // Protocol description structures
2908
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002909 // struct _objc_protocol_extension {
2910 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2911 // struct _objc_method_description_list *optional_instance_methods;
2912 // struct _objc_method_description_list *optional_class_methods;
2913 // struct _objc_property_list *instance_properties;
2914 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002915 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002916 llvm::StructType::get(IntTy,
2917 MethodDescriptionListPtrTy,
2918 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002919 PropertyListPtrTy,
2920 NULL);
2921 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2922 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002923
2924 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002925 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2926
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002927 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002928
2929 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2930 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2931
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002932 const llvm::Type *T =
2933 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2934 LongTy,
2935 llvm::ArrayType::get(ProtocolTyHolder, 0),
2936 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002937 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2938
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002939 // struct _objc_protocol {
2940 // struct _objc_protocol_extension *isa;
2941 // char *protocol_name;
2942 // struct _objc_protocol **_objc_protocol_list;
2943 // struct _objc_method_description_list *instance_methods;
2944 // struct _objc_method_description_list *class_methods;
2945 // }
2946 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002947 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002948 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2949 MethodDescriptionListPtrTy,
2950 MethodDescriptionListPtrTy,
2951 NULL);
2952 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2953
2954 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2955 CGM.getModule().addTypeName("struct._objc_protocol_list",
2956 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002957 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002958 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2959
2960 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002961 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002962 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002963
2964 // Class description structures
2965
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002966 // struct _objc_ivar {
2967 // char *ivar_name;
2968 // char *ivar_type;
2969 // int ivar_offset;
2970 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002971 IvarTy = llvm::StructType::get(Int8PtrTy,
2972 Int8PtrTy,
2973 IntTy,
2974 NULL);
2975 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2976
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002977 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002978 IvarListTy = llvm::OpaqueType::get();
2979 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2980 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2981
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002982 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002983 MethodListTy = llvm::OpaqueType::get();
2984 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2985 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2986
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002987 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002988 ClassExtensionTy =
2989 llvm::StructType::get(IntTy,
2990 Int8PtrTy,
2991 PropertyListPtrTy,
2992 NULL);
2993 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2994 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2995
2996 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2997
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002998 // struct _objc_class {
2999 // Class isa;
3000 // Class super_class;
3001 // char *name;
3002 // long version;
3003 // long info;
3004 // long instance_size;
3005 // struct _objc_ivar_list *ivars;
3006 // struct _objc_method_list *methods;
3007 // struct _objc_cache *cache;
3008 // struct _objc_protocol_list *protocols;
3009 // char *ivar_layout;
3010 // struct _objc_class_ext *ext;
3011 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003012 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3013 llvm::PointerType::getUnqual(ClassTyHolder),
3014 Int8PtrTy,
3015 LongTy,
3016 LongTy,
3017 LongTy,
3018 IvarListPtrTy,
3019 MethodListPtrTy,
3020 CachePtrTy,
3021 ProtocolListPtrTy,
3022 Int8PtrTy,
3023 ClassExtensionPtrTy,
3024 NULL);
3025 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3026
3027 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3028 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3029 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3030
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003031 // struct _objc_category {
3032 // char *category_name;
3033 // char *class_name;
3034 // struct _objc_method_list *instance_method;
3035 // struct _objc_method_list *class_method;
3036 // uint32_t size; // sizeof(struct _objc_category)
3037 // struct _objc_property_list *instance_properties;// category's @property
3038 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003039 CategoryTy = llvm::StructType::get(Int8PtrTy,
3040 Int8PtrTy,
3041 MethodListPtrTy,
3042 MethodListPtrTy,
3043 ProtocolListPtrTy,
3044 IntTy,
3045 PropertyListPtrTy,
3046 NULL);
3047 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3048
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003049 // Global metadata structures
3050
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003051 // struct _objc_symtab {
3052 // long sel_ref_cnt;
3053 // SEL *refs;
3054 // short cls_def_cnt;
3055 // short cat_def_cnt;
3056 // char *defs[cls_def_cnt + cat_def_cnt];
3057 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003058 SymtabTy = llvm::StructType::get(LongTy,
3059 SelectorPtrTy,
3060 ShortTy,
3061 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003062 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003063 NULL);
3064 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3065 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3066
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003067 // struct _objc_module {
3068 // long version;
3069 // long size; // sizeof(struct _objc_module)
3070 // char *name;
3071 // struct _objc_symtab* symtab;
3072 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003073 ModuleTy =
3074 llvm::StructType::get(LongTy,
3075 LongTy,
3076 Int8PtrTy,
3077 SymtabPtrTy,
3078 NULL);
3079 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003080
Daniel Dunbar49f66022008-09-24 03:38:44 +00003081 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003082
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003083 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003084 std::vector<const llvm::Type*> Params;
3085 Params.push_back(ObjectPtrTy);
3086 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003087 MessageSendFn =
3088 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3089 Params,
3090 true),
3091 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003092
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003093 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003094 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003095 Params.push_back(ObjectPtrTy);
3096 Params.push_back(SelectorPtrTy);
3097 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003098 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3099 Params,
3100 true),
3101 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003102
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003103 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003104 Params.clear();
3105 Params.push_back(ObjectPtrTy);
3106 Params.push_back(SelectorPtrTy);
3107 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003108 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003109 MessageSendFpretFn =
3110 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3111 Params,
3112 true),
3113 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003114
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003115 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003116 Params.clear();
3117 Params.push_back(SuperPtrTy);
3118 Params.push_back(SelectorPtrTy);
3119 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003120 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3121 Params,
3122 true),
3123 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003124
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003125 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3126 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003127 Params.clear();
3128 Params.push_back(Int8PtrTy);
3129 Params.push_back(SuperPtrTy);
3130 Params.push_back(SelectorPtrTy);
3131 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003132 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3133 Params,
3134 true),
3135 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003136
3137 // There is no objc_msgSendSuper_fpret? How can that work?
3138 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003139
Anders Carlsson124526b2008-09-09 10:10:21 +00003140 // FIXME: This is the size of the setjmp buffer and should be
3141 // target specific. 18 is what's used on 32-bit X86.
3142 uint64_t SetJmpBufferSize = 18;
3143
3144 // Exceptions
3145 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003146 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003147
3148 ExceptionDataTy =
3149 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3150 SetJmpBufferSize),
3151 StackPtrTy, NULL);
3152 CGM.getModule().addTypeName("struct._objc_exception_data",
3153 ExceptionDataTy);
3154
3155 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003156 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3157 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003158 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3159 Params,
3160 false),
3161 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003162 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003163 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3164 Params,
3165 false),
3166 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003167 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003168 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3169 Params,
3170 false),
3171 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003172
3173 Params.clear();
3174 Params.push_back(ClassPtrTy);
3175 Params.push_back(ObjectPtrTy);
3176 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003177 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3178 Params,
3179 false),
3180 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003181
Anders Carlsson124526b2008-09-09 10:10:21 +00003182 Params.clear();
3183 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3184 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003185 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3186 Params,
3187 false),
3188 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003189
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003190}
3191
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003192ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003193: ObjCCommonTypesHelper(cgm)
3194{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003195 // struct _method_list_t {
3196 // uint32_t entsize; // sizeof(struct _objc_method)
3197 // uint32_t method_count;
3198 // struct _objc_method method_list[method_count];
3199 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003200 MethodListnfABITy = llvm::StructType::get(IntTy,
3201 IntTy,
3202 llvm::ArrayType::get(MethodTy, 0),
3203 NULL);
3204 CGM.getModule().addTypeName("struct.__method_list_t",
3205 MethodListnfABITy);
3206 // struct method_list_t *
3207 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003208
3209 // struct _protocol_t {
3210 // id isa; // NULL
3211 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003212 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003213 // const struct method_list_t * const instance_methods;
3214 // const struct method_list_t * const class_methods;
3215 // const struct method_list_t *optionalInstanceMethods;
3216 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003217 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003218 // const uint32_t size; // sizeof(struct _protocol_t)
3219 // const uint32_t flags; // = 0
3220 // }
3221
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003222 // Holder for struct _protocol_list_t *
3223 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3224
3225 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3226 Int8PtrTy,
3227 llvm::PointerType::getUnqual(
3228 ProtocolListTyHolder),
3229 MethodListnfABIPtrTy,
3230 MethodListnfABIPtrTy,
3231 MethodListnfABIPtrTy,
3232 MethodListnfABIPtrTy,
3233 PropertyListPtrTy,
3234 IntTy,
3235 IntTy,
3236 NULL);
3237 CGM.getModule().addTypeName("struct._protocol_t",
3238 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003239
3240 // struct _protocol_t*
3241 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003242
Fariborz Jahanianda320092009-01-29 19:24:30 +00003243 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003244 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003245 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003246 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003247 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3248 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003249 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003250 NULL);
3251 CGM.getModule().addTypeName("struct._objc_protocol_list",
3252 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003253 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3254 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003255
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003256 // struct _objc_protocol_list*
3257 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003258
3259 // struct _ivar_t {
3260 // unsigned long int *offset; // pointer to ivar offset location
3261 // char *name;
3262 // char *type;
3263 // uint32_t alignment;
3264 // uint32_t size;
3265 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003266 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3267 Int8PtrTy,
3268 Int8PtrTy,
3269 IntTy,
3270 IntTy,
3271 NULL);
3272 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3273
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003274 // struct _ivar_list_t {
3275 // uint32 entsize; // sizeof(struct _ivar_t)
3276 // uint32 count;
3277 // struct _iver_t list[count];
3278 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003279 IvarListnfABITy = llvm::StructType::get(IntTy,
3280 IntTy,
3281 llvm::ArrayType::get(
3282 IvarnfABITy, 0),
3283 NULL);
3284 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3285
3286 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003287
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003288 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003289 // uint32_t const flags;
3290 // uint32_t const instanceStart;
3291 // uint32_t const instanceSize;
3292 // uint32_t const reserved; // only when building for 64bit targets
3293 // const uint8_t * const ivarLayout;
3294 // const char *const name;
3295 // const struct _method_list_t * const baseMethods;
3296 // const struct _objc_protocol_list *const baseProtocols;
3297 // const struct _ivar_list_t *const ivars;
3298 // const uint8_t * const weakIvarLayout;
3299 // const struct _prop_list_t * const properties;
3300 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003301
3302 // FIXME. Add 'reserved' field in 64bit abi mode!
3303 ClassRonfABITy = llvm::StructType::get(IntTy,
3304 IntTy,
3305 IntTy,
3306 Int8PtrTy,
3307 Int8PtrTy,
3308 MethodListnfABIPtrTy,
3309 ProtocolListnfABIPtrTy,
3310 IvarListnfABIPtrTy,
3311 Int8PtrTy,
3312 PropertyListPtrTy,
3313 NULL);
3314 CGM.getModule().addTypeName("struct._class_ro_t",
3315 ClassRonfABITy);
3316
3317 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3318 std::vector<const llvm::Type*> Params;
3319 Params.push_back(ObjectPtrTy);
3320 Params.push_back(SelectorPtrTy);
3321 ImpnfABITy = llvm::PointerType::getUnqual(
3322 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3323
3324 // struct _class_t {
3325 // struct _class_t *isa;
3326 // struct _class_t * const superclass;
3327 // void *cache;
3328 // IMP *vtable;
3329 // struct class_ro_t *ro;
3330 // }
3331
3332 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3333 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3334 llvm::PointerType::getUnqual(ClassTyHolder),
3335 CachePtrTy,
3336 llvm::PointerType::getUnqual(ImpnfABITy),
3337 llvm::PointerType::getUnqual(
3338 ClassRonfABITy),
3339 NULL);
3340 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3341
3342 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3343 ClassnfABITy);
3344
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003345 // LLVM for struct _class_t *
3346 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3347
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003348 // struct _category_t {
3349 // const char * const name;
3350 // struct _class_t *const cls;
3351 // const struct _method_list_t * const instance_methods;
3352 // const struct _method_list_t * const class_methods;
3353 // const struct _protocol_list_t * const protocols;
3354 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003355 // }
3356 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003357 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003358 MethodListnfABIPtrTy,
3359 MethodListnfABIPtrTy,
3360 ProtocolListnfABIPtrTy,
3361 PropertyListPtrTy,
3362 NULL);
3363 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003364
3365 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003366 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3367 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003368
3369 // MessageRefTy - LLVM for:
3370 // struct _message_ref_t {
3371 // IMP messenger;
3372 // SEL name;
3373 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003374
3375 // First the clang type for struct _message_ref_t
3376 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3377 SourceLocation(),
3378 &Ctx.Idents.get("_message_ref_t"));
3379 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3380 Ctx.VoidPtrTy, 0, false));
3381 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3382 Ctx.getObjCSelType(), 0, false));
3383 RD->completeDefinition(Ctx);
3384
3385 MessageRefCTy = Ctx.getTagDeclType(RD);
3386 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3387 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003388
3389 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3390 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3391
3392 // SuperMessageRefTy - LLVM for:
3393 // struct _super_message_ref_t {
3394 // SUPER_IMP messenger;
3395 // SEL name;
3396 // };
3397 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3398 SelectorPtrTy,
3399 NULL);
3400 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3401
3402 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3403 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3404
3405 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3406 Params.clear();
3407 Params.push_back(ObjectPtrTy);
3408 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003409 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3410 Params,
3411 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003412 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003413 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003414 "objc_msgSend_fixup");
3415
3416 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3417 MessageSendFpretFixupFn =
3418 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3419 Params,
3420 true),
3421 "objc_msgSend_fpret_fixup");
3422
3423 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3424 MessageSendStretFixupFn =
3425 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3426 Params,
3427 true),
3428 "objc_msgSend_stret_fixup");
3429
3430 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3431 MessageSendIdFixupFn =
3432 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3433 Params,
3434 true),
3435 "objc_msgSendId_fixup");
3436
3437
3438 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3439 MessageSendIdStretFixupFn =
3440 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3441 Params,
3442 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003443 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003444
3445 // id objc_msgSendSuper2_fixup (struct objc_super *,
3446 // struct _super_message_ref_t*, ...)
3447 Params.clear();
3448 Params.push_back(SuperPtrTy);
3449 Params.push_back(SuperMessageRefPtrTy);
3450 MessageSendSuper2FixupFn =
3451 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3452 Params,
3453 true),
3454 "objc_msgSendSuper2_fixup");
3455
3456
3457 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3458 // struct _super_message_ref_t*, ...)
3459 MessageSendSuper2StretFixupFn =
3460 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3461 Params,
3462 true),
3463 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003464
3465 Params.clear();
3466 llvm::Constant *Personality =
3467 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3468 Params,
3469 true),
3470 "__objc_personality_v0");
3471 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3472
3473 Params.clear();
3474 Params.push_back(Int8PtrTy);
3475 UnwindResumeOrRethrowFn =
3476 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3477 Params,
3478 false),
3479 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003480 ObjCBeginCatchFn =
3481 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3482 Params,
3483 false),
3484 "objc_begin_catch");
3485
3486 Params.clear();
3487 ObjCEndCatchFn =
3488 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3489 Params,
3490 false),
3491 "objc_end_catch");
3492
3493 // struct objc_typeinfo {
3494 // const void** vtable; // objc_ehtype_vtable + 2
3495 // const char* name; // c++ typeinfo string
3496 // Class cls;
3497 // };
3498 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3499 Int8PtrTy,
3500 ClassnfABIPtrTy,
3501 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003502 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003503 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003504}
3505
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003506llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3507 FinishNonFragileABIModule();
3508
3509 return NULL;
3510}
3511
3512void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3513 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003514
3515 // Build list of all implemented classe addresses in array
3516 // L_OBJC_LABEL_CLASS_$.
3517 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3518 // list of 'nonlazy' implementations (defined as those with a +load{}
3519 // method!!).
3520 unsigned NumClasses = DefinedClasses.size();
3521 if (NumClasses) {
3522 std::vector<llvm::Constant*> Symbols(NumClasses);
3523 for (unsigned i=0; i<NumClasses; i++)
3524 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3525 ObjCTypes.Int8PtrTy);
3526 llvm::Constant* Init =
3527 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3528 NumClasses),
3529 Symbols);
3530
3531 llvm::GlobalVariable *GV =
3532 new llvm::GlobalVariable(Init->getType(), false,
3533 llvm::GlobalValue::InternalLinkage,
3534 Init,
3535 "\01L_OBJC_LABEL_CLASS_$",
3536 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003537 GV->setAlignment(
3538 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003539 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3540 UsedGlobals.push_back(GV);
3541 }
3542
3543 // Build list of all implemented category addresses in array
3544 // L_OBJC_LABEL_CATEGORY_$.
3545 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3546 // list of 'nonlazy' category implementations (defined as those with a +load{}
3547 // method!!).
3548 unsigned NumCategory = DefinedCategories.size();
3549 if (NumCategory) {
3550 std::vector<llvm::Constant*> Symbols(NumCategory);
3551 for (unsigned i=0; i<NumCategory; i++)
3552 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3553 ObjCTypes.Int8PtrTy);
3554 llvm::Constant* Init =
3555 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3556 NumCategory),
3557 Symbols);
3558
3559 llvm::GlobalVariable *GV =
3560 new llvm::GlobalVariable(Init->getType(), false,
3561 llvm::GlobalValue::InternalLinkage,
3562 Init,
3563 "\01L_OBJC_LABEL_CATEGORY_$",
3564 &CGM.getModule());
3565 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3566 UsedGlobals.push_back(GV);
3567 }
3568
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003569 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3570 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3571 std::vector<llvm::Constant*> Values(2);
3572 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003573 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003574 // FIXME: Fix and continue?
3575 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3576 flags |= eImageInfo_GarbageCollected;
3577 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3578 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003579 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003580 llvm::Constant* Init = llvm::ConstantArray::get(
3581 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3582 Values);
3583 llvm::GlobalVariable *IMGV =
3584 new llvm::GlobalVariable(Init->getType(), false,
3585 llvm::GlobalValue::InternalLinkage,
3586 Init,
3587 "\01L_OBJC_IMAGE_INFO",
3588 &CGM.getModule());
3589 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3590 UsedGlobals.push_back(IMGV);
3591
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003592 std::vector<llvm::Constant*> Used;
3593 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3594 e = UsedGlobals.end(); i != e; ++i) {
3595 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3596 }
3597
3598 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3599 llvm::GlobalValue *GV =
3600 new llvm::GlobalVariable(AT, false,
3601 llvm::GlobalValue::AppendingLinkage,
3602 llvm::ConstantArray::get(AT, Used),
3603 "llvm.used",
3604 &CGM.getModule());
3605
3606 GV->setSection("llvm.metadata");
3607
3608}
3609
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003610// Metadata flags
3611enum MetaDataDlags {
3612 CLS = 0x0,
3613 CLS_META = 0x1,
3614 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003615 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003616 CLS_EXCEPTION = 0x20
3617};
3618/// BuildClassRoTInitializer - generate meta-data for:
3619/// struct _class_ro_t {
3620/// uint32_t const flags;
3621/// uint32_t const instanceStart;
3622/// uint32_t const instanceSize;
3623/// uint32_t const reserved; // only when building for 64bit targets
3624/// const uint8_t * const ivarLayout;
3625/// const char *const name;
3626/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003627/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003628/// const struct _ivar_list_t *const ivars;
3629/// const uint8_t * const weakIvarLayout;
3630/// const struct _prop_list_t * const properties;
3631/// }
3632///
3633llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3634 unsigned flags,
3635 unsigned InstanceStart,
3636 unsigned InstanceSize,
3637 const ObjCImplementationDecl *ID) {
3638 std::string ClassName = ID->getNameAsString();
3639 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3640 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3641 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3642 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3643 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003644 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003645 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003646 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003647 // const struct _method_list_t * const baseMethods;
3648 std::vector<llvm::Constant*> Methods;
3649 std::string MethodListName("\01l_OBJC_$_");
3650 if (flags & CLS_META) {
3651 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3652 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3653 e = ID->classmeth_end(); i != e; ++i) {
3654 // Class methods should always be defined.
3655 Methods.push_back(GetMethodConstant(*i));
3656 }
3657 } else {
3658 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3659 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3660 e = ID->instmeth_end(); i != e; ++i) {
3661 // Instance methods should always be defined.
3662 Methods.push_back(GetMethodConstant(*i));
3663 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003664 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3665 e = ID->propimpl_end(); i != e; ++i) {
3666 ObjCPropertyImplDecl *PID = *i;
3667
3668 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3669 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3670
3671 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3672 if (llvm::Constant *C = GetMethodConstant(MD))
3673 Methods.push_back(C);
3674 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3675 if (llvm::Constant *C = GetMethodConstant(MD))
3676 Methods.push_back(C);
3677 }
3678 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003679 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003680 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003681 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003682
3683 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3684 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3685 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3686 + OID->getNameAsString(),
3687 OID->protocol_begin(),
3688 OID->protocol_end());
3689
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003690 if (flags & CLS_META)
3691 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3692 else
3693 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003694 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003695 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003696 if (flags & CLS_META)
3697 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3698 else
3699 Values[ 9] =
3700 EmitPropertyList(
3701 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3702 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003703 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3704 Values);
3705 llvm::GlobalVariable *CLASS_RO_GV =
3706 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3707 llvm::GlobalValue::InternalLinkage,
3708 Init,
3709 (flags & CLS_META) ?
3710 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3711 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3712 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003713 CLASS_RO_GV->setAlignment(
3714 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003715 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003716 UsedGlobals.push_back(CLASS_RO_GV);
3717 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003718
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003719}
3720
3721/// BuildClassMetaData - This routine defines that to-level meta-data
3722/// for the given ClassName for:
3723/// struct _class_t {
3724/// struct _class_t *isa;
3725/// struct _class_t * const superclass;
3726/// void *cache;
3727/// IMP *vtable;
3728/// struct class_ro_t *ro;
3729/// }
3730///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003731llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3732 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003733 llvm::Constant *IsAGV,
3734 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003735 llvm::Constant *ClassRoGV,
3736 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003737 std::vector<llvm::Constant*> Values(5);
3738 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003739 Values[1] = SuperClassGV
3740 ? SuperClassGV
3741 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003742 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3743 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3744 Values[4] = ClassRoGV; // &CLASS_RO_GV
3745 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3746 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003747 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3748 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003749 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003750 GV->setAlignment(
3751 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003752 if (HiddenVisibility)
3753 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003754 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003755 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003756}
3757
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003758void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3759 std::string ClassName = ID->getNameAsString();
3760 if (!ObjCEmptyCacheVar) {
3761 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003762 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003763 false,
3764 llvm::GlobalValue::ExternalLinkage,
3765 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003766 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003767 &CGM.getModule());
3768 UsedGlobals.push_back(ObjCEmptyCacheVar);
3769
3770 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003771 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003772 false,
3773 llvm::GlobalValue::ExternalLinkage,
3774 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003775 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003776 &CGM.getModule());
3777 UsedGlobals.push_back(ObjCEmptyVtableVar);
3778 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003779 assert(ID->getClassInterface() &&
3780 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003781 uint32_t InstanceStart =
3782 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3783 uint32_t InstanceSize = InstanceStart;
3784 uint32_t flags = CLS_META;
3785 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3786 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003787
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003788 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003789
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003790 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3791 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003792 flags |= OBJC2_CLS_HIDDEN;
3793 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003794 // class is root
3795 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003796 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3797 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003798 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003799 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003800 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3801 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3802 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003803 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003804 // work on super class metadata symbol.
3805 std::string SuperClassName =
3806 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003807 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003808 }
3809 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3810 InstanceStart,
3811 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003812 std::string TClassName = ObjCMetaClassName + ClassName;
3813 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003814 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3815 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003816
3817 // Metadata for the class
3818 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003819 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003820 flags |= OBJC2_CLS_HIDDEN;
3821 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003822 flags |= CLS_ROOT;
3823 SuperClassGV = 0;
3824 }
3825 else {
3826 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003827 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003828 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003829 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003830 }
3831
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003832 InstanceStart = InstanceSize = 0;
3833 if (ObjCInterfaceDecl *OID =
3834 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3835 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003836 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003837 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003838 const llvm::StructLayout *Layout =
3839 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003840
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003841 RecordDecl::field_iterator firstField, lastField;
3842 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003843
3844 for (RecordDecl::field_iterator e = RD->field_end(),
3845 ifield = firstField; ifield != e; ++ifield)
3846 lastField = ifield;
3847
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003848 if (lastField != RD->field_end()) {
3849 FieldDecl *Field = *lastField;
3850 const llvm::Type *FieldTy =
3851 CGM.getTypes().ConvertTypeForMem(Field->getType());
3852 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003853 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003854 if (firstField == RD->field_end())
3855 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003856 else {
3857 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003858 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003859 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003860 }
3861 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003862 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003863 InstanceStart,
3864 InstanceSize,
3865 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003866
3867 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003868 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003869 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3870 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003871 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003872}
3873
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003874/// GenerateProtocolRef - This routine is called to generate code for
3875/// a protocol reference expression; as in:
3876/// @code
3877/// @protocol(Proto1);
3878/// @endcode
3879/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3880/// which will hold address of the protocol meta-data.
3881///
3882llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3883 const ObjCProtocolDecl *PD) {
3884
3885 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3886 ObjCTypes.ExternalProtocolPtrTy);
3887
3888 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3889 ProtocolName += PD->getNameAsCString();
3890
3891 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3892 if (PTGV)
3893 return Builder.CreateLoad(PTGV, false, "tmp");
3894 PTGV = new llvm::GlobalVariable(
3895 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00003896 // FIXME: review, was WeakLinkage,
3897 // also review all other WeakLinkage changes
3898 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003899 Init,
3900 ProtocolName,
3901 &CGM.getModule());
3902 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3903 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3904 UsedGlobals.push_back(PTGV);
3905 return Builder.CreateLoad(PTGV, false, "tmp");
3906}
3907
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003908/// GenerateCategory - Build metadata for a category implementation.
3909/// struct _category_t {
3910/// const char * const name;
3911/// struct _class_t *const cls;
3912/// const struct _method_list_t * const instance_methods;
3913/// const struct _method_list_t * const class_methods;
3914/// const struct _protocol_list_t * const protocols;
3915/// const struct _prop_list_t * const properties;
3916/// }
3917///
3918void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3919{
3920 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003921 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3922 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003923 "_$_" + OCD->getNameAsString());
3924 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3925
3926 std::vector<llvm::Constant*> Values(6);
3927 Values[0] = GetClassName(OCD->getIdentifier());
3928 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003929 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003930 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003931 std::vector<llvm::Constant*> Methods;
3932 std::string MethodListName(Prefix);
3933 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3934 "_$_" + OCD->getNameAsString();
3935
3936 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3937 e = OCD->instmeth_end(); i != e; ++i) {
3938 // Instance methods should always be defined.
3939 Methods.push_back(GetMethodConstant(*i));
3940 }
3941
3942 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003943 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003944 Methods);
3945
3946 MethodListName = Prefix;
3947 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3948 OCD->getNameAsString();
3949 Methods.clear();
3950 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3951 e = OCD->classmeth_end(); i != e; ++i) {
3952 // Class methods should always be defined.
3953 Methods.push_back(GetMethodConstant(*i));
3954 }
3955
3956 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003957 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003958 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003959 const ObjCCategoryDecl *Category =
3960 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003961 if (Category) {
3962 std::string ExtName(Interface->getNameAsString() + "_$_" +
3963 OCD->getNameAsString());
3964 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3965 + Interface->getNameAsString() + "_$_"
3966 + Category->getNameAsString(),
3967 Category->protocol_begin(),
3968 Category->protocol_end());
3969 Values[5] =
3970 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3971 OCD, Category, ObjCTypes);
3972 }
3973 else {
3974 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3975 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3976 }
3977
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003978 llvm::Constant *Init =
3979 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3980 Values);
3981 llvm::GlobalVariable *GCATV
3982 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3983 false,
3984 llvm::GlobalValue::InternalLinkage,
3985 Init,
3986 ExtCatName,
3987 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003988 GCATV->setAlignment(
3989 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003990 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003991 UsedGlobals.push_back(GCATV);
3992 DefinedCategories.push_back(GCATV);
3993}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003994
3995/// GetMethodConstant - Return a struct objc_method constant for the
3996/// given method if it has been defined. The result is null if the
3997/// method has not been defined. The return value has type MethodPtrTy.
3998llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3999 const ObjCMethodDecl *MD) {
4000 // FIXME: Use DenseMap::lookup
4001 llvm::Function *Fn = MethodDefinitions[MD];
4002 if (!Fn)
4003 return 0;
4004
4005 std::vector<llvm::Constant*> Method(3);
4006 Method[0] =
4007 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4008 ObjCTypes.SelectorPtrTy);
4009 Method[1] = GetMethodVarType(MD);
4010 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4011 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4012}
4013
4014/// EmitMethodList - Build meta-data for method declarations
4015/// struct _method_list_t {
4016/// uint32_t entsize; // sizeof(struct _objc_method)
4017/// uint32_t method_count;
4018/// struct _objc_method method_list[method_count];
4019/// }
4020///
4021llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4022 const std::string &Name,
4023 const char *Section,
4024 const ConstantVector &Methods) {
4025 // Return null for empty list.
4026 if (Methods.empty())
4027 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4028
4029 std::vector<llvm::Constant*> Values(3);
4030 // sizeof(struct _objc_method)
4031 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4032 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4033 // method_count
4034 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4035 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4036 Methods.size());
4037 Values[2] = llvm::ConstantArray::get(AT, Methods);
4038 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4039
4040 llvm::GlobalVariable *GV =
4041 new llvm::GlobalVariable(Init->getType(), false,
4042 llvm::GlobalValue::InternalLinkage,
4043 Init,
4044 Name,
4045 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004046 GV->setAlignment(
4047 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004048 GV->setSection(Section);
4049 UsedGlobals.push_back(GV);
4050 return llvm::ConstantExpr::getBitCast(GV,
4051 ObjCTypes.MethodListnfABIPtrTy);
4052}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004053
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004054/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4055/// the given ivar.
4056///
4057llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4058 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004059 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004060 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004061 Name += "\01_OBJC_IVAR_$_" +
4062 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004063 + Ivar->getNameAsString();
4064 llvm::GlobalVariable *IvarOffsetGV =
4065 CGM.getModule().getGlobalVariable(Name);
4066 if (!IvarOffsetGV)
4067 IvarOffsetGV =
4068 new llvm::GlobalVariable(ObjCTypes.LongTy,
4069 false,
4070 llvm::GlobalValue::ExternalLinkage,
4071 0,
4072 Name,
4073 &CGM.getModule());
4074 return IvarOffsetGV;
4075}
4076
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004077llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004078 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004079 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004080 unsigned long int Offset) {
4081
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004082 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004083 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004084 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004085 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004086
4087 llvm::GlobalVariable *IvarOffsetGV =
4088 CGM.getModule().getGlobalVariable(ExternalName);
4089 if (IvarOffsetGV) {
4090 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004091 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004092 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004093 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004094 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004095 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004096 return IvarOffsetGV;
4097 }
4098
4099 IvarOffsetGV =
4100 new llvm::GlobalVariable(Init->getType(),
4101 false,
4102 llvm::GlobalValue::ExternalLinkage,
4103 Init,
4104 ExternalName,
4105 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004106 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004107 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004108 // @private and @package have hidden visibility.
4109 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4110 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4111 if (!globalVisibility)
4112 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004113 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004114 if (IsClassHidden(ID))
4115 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004116
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004117 IvarOffsetGV->setSection("__DATA, __objc_const");
4118 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004119 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004120}
4121
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004122/// EmitIvarList - Emit the ivar list for the given
4123/// implementation. If ForClass is true the list of class ivars
4124/// (i.e. metaclass ivars) is emitted, otherwise the list of
4125/// interface ivars will be emitted. The return value has type
4126/// IvarListnfABIPtrTy.
4127/// struct _ivar_t {
4128/// unsigned long int *offset; // pointer to ivar offset location
4129/// char *name;
4130/// char *type;
4131/// uint32_t alignment;
4132/// uint32_t size;
4133/// }
4134/// struct _ivar_list_t {
4135/// uint32 entsize; // sizeof(struct _ivar_t)
4136/// uint32 count;
4137/// struct _iver_t list[count];
4138/// }
4139///
4140llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4141 const ObjCImplementationDecl *ID) {
4142
4143 std::vector<llvm::Constant*> Ivars, Ivar(5);
4144
4145 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4146 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4147
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004148 // FIXME. Consolidate this with similar code in GenerateClass.
4149 const llvm::Type *InterfaceTy =
4150 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4151 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004152 const llvm::StructLayout *Layout =
4153 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004154
4155 RecordDecl::field_iterator i,p;
4156 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004157 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4158
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004159 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004160 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004161 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004162 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004163 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004164 if (Field->getIdentifier())
4165 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4166 else
4167 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004168 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004169 const llvm::Type *FieldTy =
4170 CGM.getTypes().ConvertTypeForMem(Field->getType());
4171 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4172 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4173 Field->getType().getTypePtr()) >> 3;
4174 Align = llvm::Log2_32(Align);
4175 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004176 // NOTE. Size of a bitfield does not match gcc's, because of the way
4177 // bitfields are treated special in each. But I am told that 'size'
4178 // for bitfield ivars is ignored by the runtime so it does not matter.
4179 // (even if it matters, some day, there is enough info. to get the bitfield
4180 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004181 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4182 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4183 }
4184 // Return null for empty list.
4185 if (Ivars.empty())
4186 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4187 std::vector<llvm::Constant*> Values(3);
4188 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4189 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4190 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4191 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4192 Ivars.size());
4193 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4194 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4195 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4196 llvm::GlobalVariable *GV =
4197 new llvm::GlobalVariable(Init->getType(), false,
4198 llvm::GlobalValue::InternalLinkage,
4199 Init,
4200 Prefix + OID->getNameAsString(),
4201 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004202 GV->setAlignment(
4203 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004204 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004205
4206 UsedGlobals.push_back(GV);
4207 return llvm::ConstantExpr::getBitCast(GV,
4208 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004209}
4210
4211llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4212 const ObjCProtocolDecl *PD) {
4213 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4214
4215 if (!Entry) {
4216 // We use the initializer as a marker of whether this is a forward
4217 // reference or not. At module finalization we add the empty
4218 // contents for protocols which were referenced but never defined.
4219 Entry =
4220 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4221 llvm::GlobalValue::ExternalLinkage,
4222 0,
4223 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4224 &CGM.getModule());
4225 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4226 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004227 }
4228
4229 return Entry;
4230}
4231
4232/// GetOrEmitProtocol - Generate the protocol meta-data:
4233/// @code
4234/// struct _protocol_t {
4235/// id isa; // NULL
4236/// const char * const protocol_name;
4237/// const struct _protocol_list_t * protocol_list; // super protocols
4238/// const struct method_list_t * const instance_methods;
4239/// const struct method_list_t * const class_methods;
4240/// const struct method_list_t *optionalInstanceMethods;
4241/// const struct method_list_t *optionalClassMethods;
4242/// const struct _prop_list_t * properties;
4243/// const uint32_t size; // sizeof(struct _protocol_t)
4244/// const uint32_t flags; // = 0
4245/// }
4246/// @endcode
4247///
4248
4249llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4250 const ObjCProtocolDecl *PD) {
4251 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4252
4253 // Early exit if a defining object has already been generated.
4254 if (Entry && Entry->hasInitializer())
4255 return Entry;
4256
4257 const char *ProtocolName = PD->getNameAsCString();
4258
4259 // Construct method lists.
4260 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4261 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4262 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4263 e = PD->instmeth_end(); i != e; ++i) {
4264 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004265 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004266 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4267 OptInstanceMethods.push_back(C);
4268 } else {
4269 InstanceMethods.push_back(C);
4270 }
4271 }
4272
4273 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4274 e = PD->classmeth_end(); i != e; ++i) {
4275 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004276 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004277 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4278 OptClassMethods.push_back(C);
4279 } else {
4280 ClassMethods.push_back(C);
4281 }
4282 }
4283
4284 std::vector<llvm::Constant*> Values(10);
4285 // isa is NULL
4286 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4287 Values[1] = GetClassName(PD->getIdentifier());
4288 Values[2] = EmitProtocolList(
4289 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4290 PD->protocol_begin(),
4291 PD->protocol_end());
4292
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004293 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004294 + PD->getNameAsString(),
4295 "__DATA, __objc_const",
4296 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004297 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004298 + PD->getNameAsString(),
4299 "__DATA, __objc_const",
4300 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004301 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004302 + PD->getNameAsString(),
4303 "__DATA, __objc_const",
4304 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004305 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004306 + PD->getNameAsString(),
4307 "__DATA, __objc_const",
4308 OptClassMethods);
4309 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4310 0, PD, ObjCTypes);
4311 uint32_t Size =
4312 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4313 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4314 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4315 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4316 Values);
4317
4318 if (Entry) {
4319 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004320 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004321 Entry->setInitializer(Init);
4322 } else {
4323 Entry =
4324 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004325 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004326 Init,
4327 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4328 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004329 Entry->setAlignment(
4330 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004331 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004332 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004333 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4334
4335 // Use this protocol meta-data to build protocol list table in section
4336 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004337 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004338 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004339 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004340 Entry,
4341 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4342 +ProtocolName,
4343 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004344 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004345 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004346 PTGV->setSection("__DATA, __objc_protolist");
4347 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4348 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004349 return Entry;
4350}
4351
4352/// EmitProtocolList - Generate protocol list meta-data:
4353/// @code
4354/// struct _protocol_list_t {
4355/// long protocol_count; // Note, this is 32/64 bit
4356/// struct _protocol_t[protocol_count];
4357/// }
4358/// @endcode
4359///
4360llvm::Constant *
4361CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4362 ObjCProtocolDecl::protocol_iterator begin,
4363 ObjCProtocolDecl::protocol_iterator end) {
4364 std::vector<llvm::Constant*> ProtocolRefs;
4365
Fariborz Jahanianda320092009-01-29 19:24:30 +00004366 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004367 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004368 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4369
Daniel Dunbar948e2582009-02-15 07:36:20 +00004370 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004371 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4372 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004373 return llvm::ConstantExpr::getBitCast(GV,
4374 ObjCTypes.ProtocolListnfABIPtrTy);
4375
4376 for (; begin != end; ++begin)
4377 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4378
Fariborz Jahanianda320092009-01-29 19:24:30 +00004379 // This list is null terminated.
4380 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004381 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004382
4383 std::vector<llvm::Constant*> Values(2);
4384 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4385 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004386 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004387 ProtocolRefs.size()),
4388 ProtocolRefs);
4389
4390 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4391 GV = new llvm::GlobalVariable(Init->getType(), false,
4392 llvm::GlobalValue::InternalLinkage,
4393 Init,
4394 Name,
4395 &CGM.getModule());
4396 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004397 GV->setAlignment(
4398 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004399 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004400 return llvm::ConstantExpr::getBitCast(GV,
4401 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004402}
4403
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004404/// GetMethodDescriptionConstant - This routine build following meta-data:
4405/// struct _objc_method {
4406/// SEL _cmd;
4407/// char *method_type;
4408/// char *_imp;
4409/// }
4410
4411llvm::Constant *
4412CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4413 std::vector<llvm::Constant*> Desc(3);
4414 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4415 ObjCTypes.SelectorPtrTy);
4416 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004417 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004418 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4419 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4420}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004421
4422/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4423/// This code gen. amounts to generating code for:
4424/// @code
4425/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4426/// @encode
4427///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004428LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004429 CodeGen::CodeGenFunction &CGF,
4430 QualType ObjectTy,
4431 llvm::Value *BaseValue,
4432 const ObjCIvarDecl *Ivar,
4433 const FieldDecl *Field,
4434 unsigned CVRQualifiers) {
4435 assert(ObjectTy->isObjCInterfaceType() &&
4436 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004437 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004438 std::string ExternalName;
4439 llvm::GlobalVariable *IvarOffsetGV =
4440 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004441
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004442 // (char *) BaseValue
4443 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4444 ObjCTypes.Int8PtrTy);
4445 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4446 // (char*)BaseValue + Offset_symbol
4447 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4448 // (type *)((char*)BaseValue + Offset_symbol)
4449 const llvm::Type *IvarTy =
4450 CGM.getTypes().ConvertType(Ivar->getType());
4451 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4452 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004453
4454 if (Ivar->isBitField())
4455 return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4456 CVRQualifiers);
4457
4458 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004459 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4460 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004461 LValue::SetObjCIvar(LV, true);
4462 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004463}
4464
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004465llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4466 CodeGen::CodeGenFunction &CGF,
4467 ObjCInterfaceDecl *Interface,
4468 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004469 std::string ExternalName;
4470 llvm::GlobalVariable *IvarOffsetGV =
4471 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4472
4473 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004474}
4475
Fariborz Jahanian46551122009-02-04 00:22:57 +00004476CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4477 CodeGen::CodeGenFunction &CGF,
4478 QualType ResultType,
4479 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004480 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004481 QualType Arg0Ty,
4482 bool IsSuper,
4483 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004484 // FIXME. Even though IsSuper is passes. This function doese not
4485 // handle calls to 'super' receivers.
4486 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004487 llvm::Value *Arg0 = Receiver;
4488 if (!IsSuper)
4489 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004490
4491 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004492 // FIXME. This is too much work to get the ABI-specific result type
4493 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004494 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4495 llvm::SmallVector<QualType, 16>());
4496 llvm::Constant *Fn;
4497 std::string Name("\01l_");
4498 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004499#if 0
4500 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004501 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4502 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4503 // FIXME. Is there a better way of getting these names.
4504 // They are available in RuntimeFunctions vector pair.
4505 Name += "objc_msgSendId_stret_fixup";
4506 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004507 else
4508#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004509 if (IsSuper) {
4510 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4511 Name += "objc_msgSendSuper2_stret_fixup";
4512 }
4513 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004514 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004515 Fn = ObjCTypes.MessageSendStretFixupFn;
4516 Name += "objc_msgSend_stret_fixup";
4517 }
4518 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004519 else if (ResultType->isFloatingType() &&
4520 // Selection of frret API only happens in 32bit nonfragile ABI.
4521 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004522 Fn = ObjCTypes.MessageSendFpretFixupFn;
4523 Name += "objc_msgSend_fpret_fixup";
4524 }
4525 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004526#if 0
4527// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004528 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4529 Fn = ObjCTypes.MessageSendIdFixupFn;
4530 Name += "objc_msgSendId_fixup";
4531 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004532 else
4533#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004534 if (IsSuper) {
4535 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4536 Name += "objc_msgSendSuper2_fixup";
4537 }
4538 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004539 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004540 Fn = ObjCTypes.MessageSendFixupFn;
4541 Name += "objc_msgSend_fixup";
4542 }
4543 }
4544 Name += '_';
4545 std::string SelName(Sel.getAsString());
4546 // Replace all ':' in selector name with '_' ouch!
4547 for(unsigned i = 0; i < SelName.size(); i++)
4548 if (SelName[i] == ':')
4549 SelName[i] = '_';
4550 Name += SelName;
4551 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4552 if (!GV) {
4553 // Build messafe ref table entry.
4554 std::vector<llvm::Constant*> Values(2);
4555 Values[0] = Fn;
4556 Values[1] = GetMethodVarName(Sel);
4557 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4558 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004559 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004560 Init,
4561 Name,
4562 &CGM.getModule());
4563 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4564 GV->setAlignment(
4565 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4566 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4567 UsedGlobals.push_back(GV);
4568 }
4569 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004570
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004571 CallArgList ActualArgs;
4572 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4573 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4574 ObjCTypes.MessageRefCPtrTy));
4575 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004576 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4577 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4578 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004579 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004580 Callee = CGF.Builder.CreateBitCast(Callee,
4581 llvm::PointerType::getUnqual(FTy));
4582 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004583}
4584
4585/// Generate code for a message send expression in the nonfragile abi.
4586CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4587 CodeGen::CodeGenFunction &CGF,
4588 QualType ResultType,
4589 Selector Sel,
4590 llvm::Value *Receiver,
4591 bool IsClassMessage,
4592 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004593 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004594 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004595 false, CallArgs);
4596}
4597
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004598llvm::GlobalVariable *
4599CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4600 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4601
Daniel Dunbardfff2302009-03-02 05:18:14 +00004602 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004603 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4604 llvm::GlobalValue::ExternalLinkage,
4605 0, Name, &CGM.getModule());
4606 UsedGlobals.push_back(GV);
4607 }
4608
4609 return GV;
4610}
4611
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004612llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004613 const ObjCInterfaceDecl *ID,
4614 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004615
4616 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4617
4618 if (!Entry) {
4619 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004620 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004621 Entry =
4622 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4623 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004624 ClassGV,
4625 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4626 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004627 &CGM.getModule());
4628 Entry->setAlignment(
4629 CGM.getTargetData().getPrefTypeAlignment(
4630 ObjCTypes.ClassnfABIPtrTy));
4631
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004632 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004633 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004634 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004635 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004636 UsedGlobals.push_back(Entry);
4637 }
4638
4639 return Builder.CreateLoad(Entry, false, "tmp");
4640}
4641
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004642/// EmitMetaClassRef - Return a Value * of the address of _class_t
4643/// meta-data
4644///
4645llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4646 const ObjCInterfaceDecl *ID) {
4647 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4648 if (Entry)
4649 return Builder.CreateLoad(Entry, false, "tmp");
4650
4651 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004652 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004653 Entry =
4654 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4655 llvm::GlobalValue::InternalLinkage,
4656 MetaClassGV,
4657 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4658 &CGM.getModule());
4659 Entry->setAlignment(
4660 CGM.getTargetData().getPrefTypeAlignment(
4661 ObjCTypes.ClassnfABIPtrTy));
4662
4663 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4664 UsedGlobals.push_back(Entry);
4665
4666 return Builder.CreateLoad(Entry, false, "tmp");
4667}
4668
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004669/// GetClass - Return a reference to the class for the given interface
4670/// decl.
4671llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4672 const ObjCInterfaceDecl *ID) {
4673 return EmitClassRef(Builder, ID);
4674}
4675
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004676/// Generates a message send where the super is the receiver. This is
4677/// a message send to self with special delivery semantics indicating
4678/// which class's method should be called.
4679CodeGen::RValue
4680CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4681 QualType ResultType,
4682 Selector Sel,
4683 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004684 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004685 llvm::Value *Receiver,
4686 bool IsClassMessage,
4687 const CodeGen::CallArgList &CallArgs) {
4688 // ...
4689 // Create and init a super structure; this is a (receiver, class)
4690 // pair we will pass to objc_msgSendSuper.
4691 llvm::Value *ObjCSuper =
4692 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4693
4694 llvm::Value *ReceiverAsObject =
4695 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4696 CGF.Builder.CreateStore(ReceiverAsObject,
4697 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4698
4699 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004700 llvm::Value *Target;
4701 if (IsClassMessage) {
4702 if (isCategoryImpl) {
4703 // Message sent to "super' in a class method defined in
4704 // a category implementation.
4705 Target = EmitClassRef(CGF.Builder, Class, false);
4706 Target = CGF.Builder.CreateStructGEP(Target, 0);
4707 Target = CGF.Builder.CreateLoad(Target);
4708 }
4709 else
4710 Target = EmitMetaClassRef(CGF.Builder, Class);
4711 }
4712 else
4713 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004714
4715 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4716 // and ObjCTypes types.
4717 const llvm::Type *ClassTy =
4718 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4719 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4720 CGF.Builder.CreateStore(Target,
4721 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4722
4723 return EmitMessageSend(CGF, ResultType, Sel,
4724 ObjCSuper, ObjCTypes.SuperPtrCTy,
4725 true, CallArgs);
4726}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004727
4728llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4729 Selector Sel) {
4730 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4731
4732 if (!Entry) {
4733 llvm::Constant *Casted =
4734 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4735 ObjCTypes.SelectorPtrTy);
4736 Entry =
4737 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4738 llvm::GlobalValue::InternalLinkage,
4739 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4740 &CGM.getModule());
4741 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4742 UsedGlobals.push_back(Entry);
4743 }
4744
4745 return Builder.CreateLoad(Entry, false, "tmp");
4746}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004747/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4748/// objc_assign_ivar (id src, id *dst)
4749///
4750void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4751 llvm::Value *src, llvm::Value *dst)
4752{
4753 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4754 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4755 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4756 src, dst, "assignivar");
4757 return;
4758}
4759
4760/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4761/// objc_assign_strongCast (id src, id *dst)
4762///
4763void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4764 CodeGen::CodeGenFunction &CGF,
4765 llvm::Value *src, llvm::Value *dst)
4766{
4767 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4768 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4769 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4770 src, dst, "weakassign");
4771 return;
4772}
4773
4774/// EmitObjCWeakRead - Code gen for loading value of a __weak
4775/// object: objc_read_weak (id *src)
4776///
4777llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4778 CodeGen::CodeGenFunction &CGF,
4779 llvm::Value *AddrWeakObj)
4780{
Eli Friedman8339b352009-03-07 03:57:15 +00004781 const llvm::Type* DestTy =
4782 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004783 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4784 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4785 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00004786 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004787 return read_weak;
4788}
4789
4790/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4791/// objc_assign_weak (id src, id *dst)
4792///
4793void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4794 llvm::Value *src, llvm::Value *dst)
4795{
4796 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4797 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4798 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4799 src, dst, "weakassign");
4800 return;
4801}
4802
4803/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4804/// objc_assign_global (id src, id *dst)
4805///
4806void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4807 llvm::Value *src, llvm::Value *dst)
4808{
4809 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4810 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4811 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4812 src, dst, "globalassign");
4813 return;
4814}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004815
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004816void
4817CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4818 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004819 bool isTry = isa<ObjCAtTryStmt>(S);
4820 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4821 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004822 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004823 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004824 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004825 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4826
4827 // For @synchronized, call objc_sync_enter(sync.expr). The
4828 // evaluation of the expression must occur before we enter the
4829 // @synchronized. We can safely avoid a temp here because jumps into
4830 // @synchronized are illegal & this will dominate uses.
4831 llvm::Value *SyncArg = 0;
4832 if (!isTry) {
4833 SyncArg =
4834 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4835 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4836 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4837 }
4838
4839 // Push an EH context entry, used for handling rethrows and jumps
4840 // through finally.
4841 CGF.PushCleanupBlock(FinallyBlock);
4842
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004843 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004844
4845 CGF.EmitBlock(TryBlock);
4846 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4847 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4848 CGF.EmitBranchThroughCleanup(FinallyEnd);
4849
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004850 // Emit the exception handler.
4851
4852 CGF.EmitBlock(TryHandler);
4853
4854 llvm::Value *llvm_eh_exception =
4855 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4856 llvm::Value *llvm_eh_selector_i64 =
4857 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4858 llvm::Value *llvm_eh_typeid_for_i64 =
4859 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4860 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4861 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4862
4863 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4864 SelectorArgs.push_back(Exc);
4865 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4866
4867 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004868 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004869 bool HasCatchAll = false;
4870 if (isTry) {
4871 if (const ObjCAtCatchStmt* CatchStmt =
4872 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4873 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004874 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00004875 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004876
4877 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004878 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004879 // Use i8* null here to signal this is a catch all, not a cleanup.
4880 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4881 SelectorArgs.push_back(Null);
4882 HasCatchAll = true;
4883 break;
4884 }
4885
Daniel Dunbarede8de92009-03-06 00:01:21 +00004886 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
4887 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004888 llvm::Value *IDEHType =
4889 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4890 if (!IDEHType)
4891 IDEHType =
4892 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4893 llvm::GlobalValue::ExternalLinkage,
4894 0, "OBJC_EHTYPE_id", &CGM.getModule());
4895 SelectorArgs.push_back(IDEHType);
4896 HasCatchAll = true;
4897 break;
4898 }
4899
4900 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004901 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004902 assert(PT && "Invalid @catch type.");
4903 const ObjCInterfaceType *IT =
4904 PT->getPointeeType()->getAsObjCInterfaceType();
4905 assert(IT && "Invalid @catch type.");
4906 llvm::Value *EHType = GetInterfaceEHType(IT);
4907 SelectorArgs.push_back(EHType);
4908 }
4909 }
4910 }
4911
4912 // We use a cleanup unless there was already a catch all.
4913 if (!HasCatchAll) {
4914 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00004915 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004916 }
4917
4918 llvm::Value *Selector =
4919 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4920 SelectorArgs.begin(), SelectorArgs.end(),
4921 "selector");
4922 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004923 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004924 const Stmt *CatchBody = Handlers[i].second;
4925
4926 llvm::BasicBlock *Next = 0;
4927
4928 // The last handler always matches.
4929 if (i + 1 != e) {
4930 assert(CatchParam && "Only last handler can be a catch all.");
4931
4932 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4933 Next = CGF.createBasicBlock("catch.next");
4934 llvm::Value *Id =
4935 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4936 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4937 ObjCTypes.Int8PtrTy));
4938 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4939 Match, Next);
4940
4941 CGF.EmitBlock(Match);
4942 }
4943
4944 if (CatchBody) {
4945 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4946 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4947
4948 // Cleanups must call objc_end_catch.
4949 //
4950 // FIXME: It seems incorrect for objc_begin_catch to be inside
4951 // this context, but this matches gcc.
4952 CGF.PushCleanupBlock(MatchEnd);
4953 CGF.setInvokeDest(MatchHandler);
4954
4955 llvm::Value *ExcObject =
4956 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4957
4958 // Bind the catch parameter if it exists.
4959 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004960 ExcObject =
4961 CGF.Builder.CreateBitCast(ExcObject,
4962 CGF.ConvertType(CatchParam->getType()));
4963 // CatchParam is a ParmVarDecl because of the grammar
4964 // construction used to handle this, but for codegen purposes
4965 // we treat this as a local decl.
4966 CGF.EmitLocalBlockVarDecl(*CatchParam);
4967 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004968 }
4969
4970 CGF.ObjCEHValueStack.push_back(ExcObject);
4971 CGF.EmitStmt(CatchBody);
4972 CGF.ObjCEHValueStack.pop_back();
4973
4974 CGF.EmitBranchThroughCleanup(FinallyEnd);
4975
4976 CGF.EmitBlock(MatchHandler);
4977
4978 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4979 // We are required to emit this call to satisfy LLVM, even
4980 // though we don't use the result.
4981 llvm::SmallVector<llvm::Value*, 8> Args;
4982 Args.push_back(Exc);
4983 Args.push_back(ObjCTypes.EHPersonalityPtr);
4984 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4985 0));
4986 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4987 CGF.Builder.CreateStore(Exc, RethrowPtr);
4988 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4989
4990 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4991
4992 CGF.EmitBlock(MatchEnd);
4993
4994 // Unfortunately, we also have to generate another EH frame here
4995 // in case this throws.
4996 llvm::BasicBlock *MatchEndHandler =
4997 CGF.createBasicBlock("match.end.handler");
4998 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4999 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5000 Cont, MatchEndHandler,
5001 Args.begin(), Args.begin());
5002
5003 CGF.EmitBlock(Cont);
5004 if (Info.SwitchBlock)
5005 CGF.EmitBlock(Info.SwitchBlock);
5006 if (Info.EndBlock)
5007 CGF.EmitBlock(Info.EndBlock);
5008
5009 CGF.EmitBlock(MatchEndHandler);
5010 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5011 // We are required to emit this call to satisfy LLVM, even
5012 // though we don't use the result.
5013 Args.clear();
5014 Args.push_back(Exc);
5015 Args.push_back(ObjCTypes.EHPersonalityPtr);
5016 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5017 0));
5018 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5019 CGF.Builder.CreateStore(Exc, RethrowPtr);
5020 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5021
5022 if (Next)
5023 CGF.EmitBlock(Next);
5024 } else {
5025 assert(!Next && "catchup should be last handler.");
5026
5027 CGF.Builder.CreateStore(Exc, RethrowPtr);
5028 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5029 }
5030 }
5031
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005032 // Pop the cleanup entry, the @finally is outside this cleanup
5033 // scope.
5034 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5035 CGF.setInvokeDest(PrevLandingPad);
5036
5037 CGF.EmitBlock(FinallyBlock);
5038
5039 if (isTry) {
5040 if (const ObjCAtFinallyStmt* FinallyStmt =
5041 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5042 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5043 } else {
5044 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5045 // @synchronized.
5046 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005047 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005048
5049 if (Info.SwitchBlock)
5050 CGF.EmitBlock(Info.SwitchBlock);
5051 if (Info.EndBlock)
5052 CGF.EmitBlock(Info.EndBlock);
5053
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005054 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005055 CGF.EmitBranch(FinallyEnd);
5056
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005057 CGF.EmitBlock(FinallyRethrow);
5058 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5059 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005060 CGF.Builder.CreateUnreachable();
5061
5062 CGF.EmitBlock(FinallyEnd);
5063}
5064
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005065/// EmitThrowStmt - Generate code for a throw statement.
5066void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5067 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005068 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005069 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005070 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005071 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005072 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5073 "Unexpected rethrow outside @catch block.");
5074 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005075 }
5076
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005077 llvm::Value *ExceptionAsObject =
5078 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5079 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5080 if (InvokeDest) {
5081 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5082 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5083 Cont, InvokeDest,
5084 &ExceptionAsObject, &ExceptionAsObject + 1);
5085 CGF.EmitBlock(Cont);
5086 } else
5087 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5088 CGF.Builder.CreateUnreachable();
5089
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005090 // Clear the insertion point to indicate we are in unreachable code.
5091 CGF.Builder.ClearInsertionPoint();
5092}
Daniel Dunbare588b992009-03-01 04:46:24 +00005093
5094llvm::Value *
5095CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5096 const ObjCInterfaceDecl *ID = IT->getDecl();
5097 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5098 if (Entry)
5099 return Entry;
5100
5101 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5102 std::string VTableName = "objc_ehtype_vtable";
5103 llvm::GlobalVariable *VTableGV =
5104 CGM.getModule().getGlobalVariable(VTableName);
5105 if (!VTableGV)
5106 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5107 llvm::GlobalValue::ExternalLinkage,
5108 0, VTableName, &CGM.getModule());
5109
5110 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5111
5112 std::vector<llvm::Constant*> Values(3);
5113 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5114 Values[1] = GetClassName(ID->getIdentifier());
5115 Values[2] = GetClassGlobal(ClassName);
5116 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5117
5118 Entry =
5119 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005120 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005121 Init,
5122 (std::string("OBJC_EHTYPE_$_") +
5123 ID->getIdentifier()->getName()),
5124 &CGM.getModule());
5125
5126 return Entry;
5127}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005128
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005129/* *** */
5130
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005131CodeGen::CGObjCRuntime *
5132CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005133 return new CGObjCMac(CGM);
5134}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005135
5136CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005137CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005138 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005139}