blob: d33005ef0c8a118b61a3699954ffeea773af956a [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
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000433 /// CreateMetadataVar - Create a global variable with internal
434 /// linkage for use by the Objective-C runtime.
435 ///
436 /// This is a convenience wrapper which not only creates the
437 /// variable, but also sets the section and alignment and adds the
438 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000439 ///
440 /// \param Name - The variable name.
441 /// \param Init - The variable initializer; this is also used to
442 /// define the type of the variable.
443 /// \param Section - The section the variable should go into, or 0.
444 /// \param Align - The alignment for the variable, or 0.
445 /// \param AddToUsed - Whether the variable should be added to
446 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000447 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
448 llvm::Constant *Init,
449 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000450 unsigned Align,
451 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000452
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000453public:
454 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
455 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000456
457 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000458
459 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
460 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000461
462 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
463
464 /// GetOrEmitProtocol - Get the protocol object for the given
465 /// declaration, emitting it if necessary. The return value has type
466 /// ProtocolPtrTy.
467 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
468
469 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
470 /// object for the given declaration, emitting it if needed. These
471 /// forward references will be filled in with empty bodies if no
472 /// definition is seen. The return value has type ProtocolPtrTy.
473 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000474};
475
476class CGObjCMac : public CGObjCCommonMac {
477private:
478 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000479 /// EmitImageInfo - Emit the image info marker used to encode some module
480 /// level information.
481 void EmitImageInfo();
482
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000483 /// EmitModuleInfo - Another marker encoding module level
484 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000485 void EmitModuleInfo();
486
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000487 /// EmitModuleSymols - Emit module symbols, the list of defined
488 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000489 llvm::Constant *EmitModuleSymbols();
490
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000491 /// FinishModule - Write out global data structures at the end of
492 /// processing a translation unit.
493 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000494
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000495 /// EmitClassExtension - Generate the class extension structure used
496 /// to store the weak ivar layout and properties. The return value
497 /// has type ClassExtensionPtrTy.
498 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
499
500 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
501 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000502 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000503 const ObjCInterfaceDecl *ID);
504
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000505 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000506 QualType ResultType,
507 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000508 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000509 QualType Arg0Ty,
510 bool IsSuper,
511 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000512
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000513 /// EmitIvarList - Emit the ivar list for the given
514 /// implementation. If ForClass is true the list of class ivars
515 /// (i.e. metaclass ivars) is emitted, otherwise the list of
516 /// interface ivars will be emitted. The return value has type
517 /// IvarListPtrTy.
518 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000519 bool ForClass);
520
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000521 /// EmitMetaClass - Emit a forward reference to the class structure
522 /// for the metaclass of the given interface. The return value has
523 /// type ClassPtrTy.
524 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
525
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000526 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000527 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000528 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
529 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000530 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000531 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000532
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000533 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000534
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000535 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000536
537 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000538 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000539 llvm::Constant *EmitMethodList(const std::string &Name,
540 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000541 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000542
543 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000544 /// method declarations.
545 /// - TypeName: The name for the type containing the methods.
546 /// - IsProtocol: True iff these methods are for a protocol.
547 /// - ClassMethds: True iff these are class methods.
548 /// - Required: When true, only "required" methods are
549 /// listed. Similarly, when false only "optional" methods are
550 /// listed. For classes this should always be true.
551 /// - begin, end: The method list to output.
552 ///
553 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000554 llvm::Constant *EmitMethodDescList(const std::string &Name,
555 const char *Section,
556 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000557
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000558 /// GetOrEmitProtocol - Get the protocol object for the given
559 /// declaration, emitting it if necessary. The return value has type
560 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000561 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000562
563 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
564 /// object for the given declaration, emitting it if needed. These
565 /// forward references will be filled in with empty bodies if no
566 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000567 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000568
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000569 /// EmitProtocolExtension - Generate the protocol extension
570 /// structure used to store optional instance and class methods, and
571 /// protocol properties. The return value has type
572 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000573 llvm::Constant *
574 EmitProtocolExtension(const ObjCProtocolDecl *PD,
575 const ConstantVector &OptInstanceMethods,
576 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000577
578 /// EmitProtocolList - Generate the list of referenced
579 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000580 llvm::Constant *EmitProtocolList(const std::string &Name,
581 ObjCProtocolDecl::protocol_iterator begin,
582 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000583
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000584 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
585 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000586 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000587
Fariborz Jahanianda320092009-01-29 19:24:30 +0000588 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000589 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000590
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000591 virtual llvm::Function *ModuleInitFunction();
592
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000593 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000594 QualType ResultType,
595 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000596 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000597 bool IsClassMessage,
598 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000599
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000600 virtual CodeGen::RValue
601 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000602 QualType ResultType,
603 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000604 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000605 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000606 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000607 bool IsClassMessage,
608 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000609
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000610 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000611 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000612
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000613 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000614
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000615 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000616
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000617 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000618
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000619 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000620 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000621
Daniel Dunbar49f66022008-09-24 03:38:44 +0000622 virtual llvm::Function *GetPropertyGetFunction();
623 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000624 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000625
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000626 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
627 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000628 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
629 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000630 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000631 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000632 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
633 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000634 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
635 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000636 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
637 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000638 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
639 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000640
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000641 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
642 QualType ObjectTy,
643 llvm::Value *BaseValue,
644 const ObjCIvarDecl *Ivar,
645 const FieldDecl *Field,
646 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000647 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
648 ObjCInterfaceDecl *Interface,
649 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000650};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000651
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000652class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000653private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000654 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000655 llvm::GlobalVariable* ObjCEmptyCacheVar;
656 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000657
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000658 /// MetaClassReferences - uniqued meta class references.
659 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000660
661 /// EHTypeReferences - uniqued class ehtype references.
662 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000663
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000664 /// FinishNonFragileABIModule - Write out global data structures at the end of
665 /// processing a translation unit.
666 void FinishNonFragileABIModule();
667
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000668 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
669 unsigned InstanceStart,
670 unsigned InstanceSize,
671 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000672 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
673 llvm::Constant *IsAGV,
674 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000675 llvm::Constant *ClassRoGV,
676 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000677
678 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
679
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000680 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
681
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000682 /// EmitMethodList - Emit the method list for the given
683 /// implementation. The return value has type MethodListnfABITy.
684 llvm::Constant *EmitMethodList(const std::string &Name,
685 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000686 const ConstantVector &Methods);
687 /// EmitIvarList - Emit the ivar list for the given
688 /// implementation. If ForClass is true the list of class ivars
689 /// (i.e. metaclass ivars) is emitted, otherwise the list of
690 /// interface ivars will be emitted. The return value has type
691 /// IvarListnfABIPtrTy.
692 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000693
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000694 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000695 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000696 unsigned long int offset);
697
Fariborz Jahanianda320092009-01-29 19:24:30 +0000698 /// GetOrEmitProtocol - Get the protocol object for the given
699 /// declaration, emitting it if necessary. The return value has type
700 /// ProtocolPtrTy.
701 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
702
703 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
704 /// object for the given declaration, emitting it if needed. These
705 /// forward references will be filled in with empty bodies if no
706 /// definition is seen. The return value has type ProtocolPtrTy.
707 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
708
709 /// EmitProtocolList - Generate the list of referenced
710 /// protocols. The return value has type ProtocolListPtrTy.
711 llvm::Constant *EmitProtocolList(const std::string &Name,
712 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000713 ObjCProtocolDecl::protocol_iterator end);
714
715 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
716 QualType ResultType,
717 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000718 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000719 QualType Arg0Ty,
720 bool IsSuper,
721 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000722
723 /// GetClassGlobal - Return the global variable for the Objective-C
724 /// class of the given name.
725 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000726
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000727 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
728 /// for the given class.
729 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000730 const ObjCInterfaceDecl *ID,
731 bool IsSuper = false);
732
733 /// EmitMetaClassRef - Return a Value * of the address of _class_t
734 /// meta-data
735 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
736 const ObjCInterfaceDecl *ID);
737
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000738 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
739 /// the given ivar.
740 ///
741 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000742 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000743 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000744
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000745 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
746 /// for the given selector.
747 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000748
749 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
750 /// interface. The return value has type EHTypePtrTy.
751 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000752
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000753public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000754 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000755 // FIXME. All stubs for now!
756 virtual llvm::Function *ModuleInitFunction();
757
758 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
759 QualType ResultType,
760 Selector Sel,
761 llvm::Value *Receiver,
762 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000763 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000764
765 virtual CodeGen::RValue
766 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
767 QualType ResultType,
768 Selector Sel,
769 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000770 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000771 llvm::Value *Receiver,
772 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000773 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000774
775 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000776 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000777
778 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000779 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000780
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000781 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000782
783 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000784 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000785 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000786
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000787 virtual llvm::Function *GetPropertyGetFunction(){
788 return ObjCTypes.GetPropertyFn;
789 }
790 virtual llvm::Function *GetPropertySetFunction(){
791 return ObjCTypes.SetPropertyFn;
792 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000793 virtual llvm::Function *EnumerationMutationFunction() {
794 return ObjCTypes.EnumerationMutationFn;
795 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000796
797 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000798 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000799 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000800 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000801 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000802 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000803 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000804 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000805 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000806 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000807 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000808 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000809 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000810 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000811 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
812 QualType ObjectTy,
813 llvm::Value *BaseValue,
814 const ObjCIvarDecl *Ivar,
815 const FieldDecl *Field,
816 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000817 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
818 ObjCInterfaceDecl *Interface,
819 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000820};
821
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000822} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000823
824/* *** Helper Functions *** */
825
826/// getConstantGEP() - Help routine to construct simple GEPs.
827static llvm::Constant *getConstantGEP(llvm::Constant *C,
828 unsigned idx0,
829 unsigned idx1) {
830 llvm::Value *Idxs[] = {
831 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
832 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
833 };
834 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
835}
836
837/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000838
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000839CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
840 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000841{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000842 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000843 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000844}
845
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000846/// GetClass - Return a reference to the class for the given interface
847/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000848llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000849 const ObjCInterfaceDecl *ID) {
850 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000851}
852
853/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000854llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000855 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000856}
857
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000858/// Generate a constant CFString object.
859/*
860 struct __builtin_CFString {
861 const int *isa; // point to __CFConstantStringClassReference
862 int flags;
863 const char *str;
864 long length;
865 };
866*/
867
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000868llvm::Constant *CGObjCCommonMac::GenerateConstantString(
869 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000870 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000871}
872
873/// Generates a message send where the super is the receiver. This is
874/// a message send to self with special delivery semantics indicating
875/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000876CodeGen::RValue
877CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000878 QualType ResultType,
879 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000880 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000881 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000882 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000883 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000884 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000885 // Create and init a super structure; this is a (receiver, class)
886 // pair we will pass to objc_msgSendSuper.
887 llvm::Value *ObjCSuper =
888 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
889 llvm::Value *ReceiverAsObject =
890 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
891 CGF.Builder.CreateStore(ReceiverAsObject,
892 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000893
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000894 // If this is a class message the metaclass is passed as the target.
895 llvm::Value *Target;
896 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000897 if (isCategoryImpl) {
898 // Message sent to 'super' in a class method defined in a category
899 // implementation requires an odd treatment.
900 // If we are in a class method, we must retrieve the
901 // _metaclass_ for the current class, pointed at by
902 // the class's "isa" pointer. The following assumes that
903 // isa" is the first ivar in a class (which it must be).
904 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
905 Target = CGF.Builder.CreateStructGEP(Target, 0);
906 Target = CGF.Builder.CreateLoad(Target);
907 }
908 else {
909 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
910 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
911 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
912 Target = Super;
913 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000914 } else {
915 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
916 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000917 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
918 // and ObjCTypes types.
919 const llvm::Type *ClassTy =
920 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000921 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000922 CGF.Builder.CreateStore(Target,
923 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
924
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000925 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000926 ObjCSuper, ObjCTypes.SuperPtrCTy,
927 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000928}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000929
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000930/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000931CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000932 QualType ResultType,
933 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000934 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000935 bool IsClassMessage,
936 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000937 llvm::Value *Arg0 =
938 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000939 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000940 Arg0, CGF.getContext().getObjCIdType(),
941 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000942}
943
944CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000945 QualType ResultType,
946 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000947 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000948 QualType Arg0Ty,
949 bool IsSuper,
950 const CallArgList &CallArgs) {
951 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000952 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
953 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
954 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000955 CGF.getContext().getObjCSelType()));
956 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000957
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000958 CodeGenTypes &Types = CGM.getTypes();
959 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
960 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000961
962 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000963 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000964 Fn = ObjCTypes.getSendStretFn(IsSuper);
965 } else if (ResultType->isFloatingType()) {
966 // FIXME: Sadly, this is wrong. This actually depends on the
967 // architecture. This happens to be right for x86-32 though.
968 Fn = ObjCTypes.getSendFpretFn(IsSuper);
969 } else {
970 Fn = ObjCTypes.getSendFn(IsSuper);
971 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000972 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000973 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000974}
975
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000976llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000977 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000978 // FIXME: I don't understand why gcc generates this, or where it is
979 // resolved. Investigate. Its also wasteful to look this up over and
980 // over.
981 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
982
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000983 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
984 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000985}
986
Fariborz Jahanianda320092009-01-29 19:24:30 +0000987void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000988 // FIXME: We shouldn't need this, the protocol decl should contain
989 // enough information to tell us whether this was a declaration or a
990 // definition.
991 DefinedProtocols.insert(PD->getIdentifier());
992
993 // If we have generated a forward reference to this protocol, emit
994 // it now. Otherwise do nothing, the protocol objects are lazily
995 // emitted.
996 if (Protocols.count(PD->getIdentifier()))
997 GetOrEmitProtocol(PD);
998}
999
Fariborz Jahanianda320092009-01-29 19:24:30 +00001000llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001001 if (DefinedProtocols.count(PD->getIdentifier()))
1002 return GetOrEmitProtocol(PD);
1003 return GetOrEmitProtocolRef(PD);
1004}
1005
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001006/*
1007 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1008 struct _objc_protocol {
1009 struct _objc_protocol_extension *isa;
1010 char *protocol_name;
1011 struct _objc_protocol_list *protocol_list;
1012 struct _objc__method_prototype_list *instance_methods;
1013 struct _objc__method_prototype_list *class_methods
1014 };
1015
1016 See EmitProtocolExtension().
1017*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001018llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1019 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1020
1021 // Early exit if a defining object has already been generated.
1022 if (Entry && Entry->hasInitializer())
1023 return Entry;
1024
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001025 // FIXME: I don't understand why gcc generates this, or where it is
1026 // resolved. Investigate. Its also wasteful to look this up over and
1027 // over.
1028 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1029
Chris Lattner8ec03f52008-11-24 03:54:41 +00001030 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001031
1032 // Construct method lists.
1033 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1034 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1035 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1036 e = PD->instmeth_end(); i != e; ++i) {
1037 ObjCMethodDecl *MD = *i;
1038 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1039 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1040 OptInstanceMethods.push_back(C);
1041 } else {
1042 InstanceMethods.push_back(C);
1043 }
1044 }
1045
1046 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1047 e = PD->classmeth_end(); i != e; ++i) {
1048 ObjCMethodDecl *MD = *i;
1049 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1050 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1051 OptClassMethods.push_back(C);
1052 } else {
1053 ClassMethods.push_back(C);
1054 }
1055 }
1056
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001057 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001058 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001059 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001060 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001061 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001062 PD->protocol_begin(),
1063 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001064 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001065 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1066 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001067 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1068 InstanceMethods);
1069 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001070 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1071 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001072 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1073 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1075 Values);
1076
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001077 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001078 // Already created, fix the linkage and update the initializer.
1079 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001080 Entry->setInitializer(Init);
1081 } else {
1082 Entry =
1083 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1084 llvm::GlobalValue::InternalLinkage,
1085 Init,
1086 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1087 &CGM.getModule());
1088 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001089 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001090 UsedGlobals.push_back(Entry);
1091 // FIXME: Is this necessary? Why only for protocol?
1092 Entry->setAlignment(4);
1093 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001094
1095 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001096}
1097
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001098llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001099 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1100
1101 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001102 // We use the initializer as a marker of whether this is a forward
1103 // reference or not. At module finalization we add the empty
1104 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001105 Entry =
1106 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001107 llvm::GlobalValue::ExternalLinkage,
1108 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001110 &CGM.getModule());
1111 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001112 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001113 UsedGlobals.push_back(Entry);
1114 // FIXME: Is this necessary? Why only for protocol?
1115 Entry->setAlignment(4);
1116 }
1117
1118 return Entry;
1119}
1120
1121/*
1122 struct _objc_protocol_extension {
1123 uint32_t size;
1124 struct objc_method_description_list *optional_instance_methods;
1125 struct objc_method_description_list *optional_class_methods;
1126 struct objc_property_list *instance_properties;
1127 };
1128*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001129llvm::Constant *
1130CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1131 const ConstantVector &OptInstanceMethods,
1132 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001133 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001134 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001135 std::vector<llvm::Constant*> Values(4);
1136 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001137 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001138 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1139 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001140 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1141 OptInstanceMethods);
1142 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001143 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1144 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001145 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1146 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001147 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1148 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001149 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001150
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001151 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001152 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1153 Values[3]->isNullValue())
1154 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1155
1156 llvm::Constant *Init =
1157 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001158
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001159 // No special section, but goes in llvm.used
1160 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1161 Init,
1162 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163}
1164
1165/*
1166 struct objc_protocol_list {
1167 struct objc_protocol_list *next;
1168 long count;
1169 Protocol *list[];
1170 };
1171*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001172llvm::Constant *
1173CGObjCMac::EmitProtocolList(const std::string &Name,
1174 ObjCProtocolDecl::protocol_iterator begin,
1175 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001176 std::vector<llvm::Constant*> ProtocolRefs;
1177
Daniel Dunbardbc933702008-08-21 21:57:41 +00001178 for (; begin != end; ++begin)
1179 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001180
1181 // Just return null for empty protocol lists
1182 if (ProtocolRefs.empty())
1183 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1184
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001185 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001186 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1187
1188 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001189 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1191 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1192 Values[2] =
1193 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1194 ProtocolRefs.size()),
1195 ProtocolRefs);
1196
1197 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1198 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001199 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001200 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001201 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1202}
1203
1204/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001205 struct _objc_property {
1206 const char * const name;
1207 const char * const attributes;
1208 };
1209
1210 struct _objc_property_list {
1211 uint32_t entsize; // sizeof (struct _objc_property)
1212 uint32_t prop_count;
1213 struct _objc_property[prop_count];
1214 };
1215*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001216llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1217 const Decl *Container,
1218 const ObjCContainerDecl *OCD,
1219 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001220 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001221 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1222 E = OCD->prop_end(); I != E; ++I) {
1223 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001224 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001225 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001226 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1227 Prop));
1228 }
1229
1230 // Return null for empty list.
1231 if (Properties.empty())
1232 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1233
1234 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001235 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001236 std::vector<llvm::Constant*> Values(3);
1237 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1238 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1239 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1240 Properties.size());
1241 Values[2] = llvm::ConstantArray::get(AT, Properties);
1242 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1243
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001244 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001245 llvm::GlobalVariable *GV =
1246 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1247 0, true);
1248 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001249}
1250
1251/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001252 struct objc_method_description_list {
1253 int count;
1254 struct objc_method_description list[];
1255 };
1256*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001257llvm::Constant *
1258CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1259 std::vector<llvm::Constant*> Desc(2);
1260 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1261 ObjCTypes.SelectorPtrTy);
1262 Desc[1] = GetMethodVarType(MD);
1263 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1264 Desc);
1265}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001266
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001267llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1268 const char *Section,
1269 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001270 // Return null for empty list.
1271 if (Methods.empty())
1272 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1273
1274 std::vector<llvm::Constant*> Values(2);
1275 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1276 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1277 Methods.size());
1278 Values[1] = llvm::ConstantArray::get(AT, Methods);
1279 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1280
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001281 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001282 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 =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001357 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1358 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001359 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001360 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001361}
1362
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001363// FIXME: Get from somewhere?
1364enum ClassFlags {
1365 eClassFlags_Factory = 0x00001,
1366 eClassFlags_Meta = 0x00002,
1367 // <rdr://5142207>
1368 eClassFlags_HasCXXStructors = 0x02000,
1369 eClassFlags_Hidden = 0x20000,
1370 eClassFlags_ABI2_Hidden = 0x00010,
1371 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1372};
1373
1374// <rdr://5142207&4705298&4843145>
1375static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1376 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1377 // FIXME: Support -fvisibility
1378 switch (attr->getVisibility()) {
1379 default:
1380 assert(0 && "Unknown visibility");
1381 return false;
1382 case VisibilityAttr::DefaultVisibility:
1383 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1384 return false;
1385 case VisibilityAttr::HiddenVisibility:
1386 return true;
1387 }
1388 } else {
1389 return false; // FIXME: Support -fvisibility
1390 }
1391}
1392
1393/*
1394 struct _objc_class {
1395 Class isa;
1396 Class super_class;
1397 const char *name;
1398 long version;
1399 long info;
1400 long instance_size;
1401 struct _objc_ivar_list *ivars;
1402 struct _objc_method_list *methods;
1403 struct _objc_cache *cache;
1404 struct _objc_protocol_list *protocols;
1405 // Objective-C 1.0 extensions (<rdr://4585769>)
1406 const char *ivar_layout;
1407 struct _objc_class_ext *ext;
1408 };
1409
1410 See EmitClassExtension();
1411 */
1412void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001413 DefinedSymbols.insert(ID->getIdentifier());
1414
Chris Lattner8ec03f52008-11-24 03:54:41 +00001415 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001416 // FIXME: Gross
1417 ObjCInterfaceDecl *Interface =
1418 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001419 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001420 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001421 Interface->protocol_begin(),
1422 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001423 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001424 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001425 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001426 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427
1428 // FIXME: Set CXX-structors flag.
1429 if (IsClassHidden(ID->getClassInterface()))
1430 Flags |= eClassFlags_Hidden;
1431
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001432 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1433 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1434 e = ID->instmeth_end(); i != e; ++i) {
1435 // Instance methods should always be defined.
1436 InstanceMethods.push_back(GetMethodConstant(*i));
1437 }
1438 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1439 e = ID->classmeth_end(); i != e; ++i) {
1440 // Class methods should always be defined.
1441 ClassMethods.push_back(GetMethodConstant(*i));
1442 }
1443
1444 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1445 e = ID->propimpl_end(); i != e; ++i) {
1446 ObjCPropertyImplDecl *PID = *i;
1447
1448 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1449 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1450
1451 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1452 if (llvm::Constant *C = GetMethodConstant(MD))
1453 InstanceMethods.push_back(C);
1454 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1455 if (llvm::Constant *C = GetMethodConstant(MD))
1456 InstanceMethods.push_back(C);
1457 }
1458 }
1459
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001460 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001461 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001462 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001463 // Record a reference to the super class.
1464 LazySymbols.insert(Super->getIdentifier());
1465
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 Values[ 1] =
1467 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1468 ObjCTypes.ClassPtrTy);
1469 } else {
1470 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1471 }
1472 Values[ 2] = GetClassName(ID->getIdentifier());
1473 // Version is always 0.
1474 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1475 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1476 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001477 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001478 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001479 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001480 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001481 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001482 // cache is always NULL.
1483 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1484 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001485 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001486 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001487 Values[11] = EmitClassExtension(ID);
1488 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1489 Values);
1490
1491 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001492 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1493 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001494 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001495 DefinedClasses.push_back(GV);
1496}
1497
1498llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1499 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001500 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001501 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001502 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001503 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001504
1505 if (IsClassHidden(ID->getClassInterface()))
1506 Flags |= eClassFlags_Hidden;
1507
1508 std::vector<llvm::Constant*> Values(12);
1509 // The isa for the metaclass is the root of the hierarchy.
1510 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1511 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1512 Root = Super;
1513 Values[ 0] =
1514 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1515 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001516 // The super class for the metaclass is emitted as the name of the
1517 // super class. The runtime fixes this up to point to the
1518 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001519 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1520 Values[ 1] =
1521 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1522 ObjCTypes.ClassPtrTy);
1523 } else {
1524 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1525 }
1526 Values[ 2] = GetClassName(ID->getIdentifier());
1527 // Version is always 0.
1528 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1529 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1530 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001531 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001532 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001533 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001534 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001535 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001536 // cache is always NULL.
1537 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1538 Values[ 9] = Protocols;
1539 // ivar_layout for metaclass is always NULL.
1540 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1541 // The class extension is always unused for metaclasses.
1542 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1543 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1544 Values);
1545
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001546 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001547 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001548
1549 // Check for a forward reference.
1550 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1551 if (GV) {
1552 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1553 "Forward metaclass reference has incorrect type.");
1554 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1555 GV->setInitializer(Init);
1556 } else {
1557 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1558 llvm::GlobalValue::InternalLinkage,
1559 Init, Name,
1560 &CGM.getModule());
1561 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001562 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001563 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001564 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001565
1566 return GV;
1567}
1568
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001569llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001570 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001571
1572 // FIXME: Should we look these up somewhere other than the
1573 // module. Its a bit silly since we only generate these while
1574 // processing an implementation, so exactly one pointer would work
1575 // if know when we entered/exitted an implementation block.
1576
1577 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001578 // Previously, metaclass with internal linkage may have been defined.
1579 // pass 'true' as 2nd argument so it is returned.
1580 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001581 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1582 "Forward metaclass reference has incorrect type.");
1583 return GV;
1584 } else {
1585 // Generate as an external reference to keep a consistent
1586 // module. This will be patched up when we emit the metaclass.
1587 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1588 llvm::GlobalValue::ExternalLinkage,
1589 0,
1590 Name,
1591 &CGM.getModule());
1592 }
1593}
1594
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001595/*
1596 struct objc_class_ext {
1597 uint32_t size;
1598 const char *weak_ivar_layout;
1599 struct _objc_property_list *properties;
1600 };
1601*/
1602llvm::Constant *
1603CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1604 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001605 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001606
1607 std::vector<llvm::Constant*> Values(3);
1608 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001609 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001610 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001611 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001612 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613
1614 // Return null if no extension bits are used.
1615 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1616 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1617
1618 llvm::Constant *Init =
1619 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001620 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1621 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001622}
1623
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001624/// countInheritedIvars - count number of ivars in class and its super class(s)
1625///
1626static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1627 int count = 0;
1628 if (!OI)
1629 return 0;
1630 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1631 if (SuperClass)
1632 count += countInheritedIvars(SuperClass);
1633 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1634 E = OI->ivar_end(); I != E; ++I)
1635 ++count;
1636 return count;
1637}
1638
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001639/// getInterfaceDeclForIvar - Get the interface declaration node where
1640/// this ivar is declared in.
1641/// FIXME. Ideally, this info should be in the ivar node. But currently
1642/// it is not and prevailing wisdom is that ASTs should not have more
1643/// info than is absolutely needed, even though this info reflects the
1644/// source language.
1645///
1646static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1647 const ObjCInterfaceDecl *OI,
1648 const ObjCIvarDecl *IVD) {
1649 if (!OI)
1650 return 0;
1651 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1652 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1653 E = OI->ivar_end(); I != E; ++I)
1654 if ((*I)->getIdentifier() == IVD->getIdentifier())
1655 return OI;
1656 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1657}
1658
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001659/*
1660 struct objc_ivar {
1661 char *ivar_name;
1662 char *ivar_type;
1663 int ivar_offset;
1664 };
1665
1666 struct objc_ivar_list {
1667 int ivar_count;
1668 struct objc_ivar list[count];
1669 };
1670 */
1671llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001672 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001673 std::vector<llvm::Constant*> Ivars, Ivar(3);
1674
1675 // When emitting the root class GCC emits ivar entries for the
1676 // actual class structure. It is not clear if we need to follow this
1677 // behavior; for now lets try and get away with not doing it. If so,
1678 // the cleanest solution would be to make up an ObjCInterfaceDecl
1679 // for the class.
1680 if (ForClass)
1681 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001682
1683 ObjCInterfaceDecl *OID =
1684 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1685 const llvm::Type *InterfaceTy =
1686 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001687 const llvm::StructLayout *Layout =
1688 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001689
1690 RecordDecl::field_iterator ifield, pfield;
1691 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001692 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1693 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001694 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001695 if (Field->getIdentifier())
1696 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1697 else
1698 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001699 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001700 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001701 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001702 }
1703
1704 // Return null for empty list.
1705 if (Ivars.empty())
1706 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1707
1708 std::vector<llvm::Constant*> Values(2);
1709 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1710 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1711 Ivars.size());
1712 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1713 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1714
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001715 llvm::GlobalVariable *GV;
1716 if (ForClass)
1717 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001718 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1719 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001720 else
1721 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1722 + ID->getNameAsString(),
1723 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1724 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001725 return llvm::ConstantExpr::getBitCast(GV,
1726 ObjCTypes.IvarListPtrTy);
1727}
1728
1729/*
1730 struct objc_method {
1731 SEL method_name;
1732 char *method_types;
1733 void *method;
1734 };
1735
1736 struct objc_method_list {
1737 struct objc_method_list *obsolete;
1738 int count;
1739 struct objc_method methods_list[count];
1740 };
1741*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001742
1743/// GetMethodConstant - Return a struct objc_method constant for the
1744/// given method if it has been defined. The result is null if the
1745/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001746llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001747 // FIXME: Use DenseMap::lookup
1748 llvm::Function *Fn = MethodDefinitions[MD];
1749 if (!Fn)
1750 return 0;
1751
1752 std::vector<llvm::Constant*> Method(3);
1753 Method[0] =
1754 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1755 ObjCTypes.SelectorPtrTy);
1756 Method[1] = GetMethodVarType(MD);
1757 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1758 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1759}
1760
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001761llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1762 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001763 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001764 // Return null for empty list.
1765 if (Methods.empty())
1766 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1767
1768 std::vector<llvm::Constant*> Values(3);
1769 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1770 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1771 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1772 Methods.size());
1773 Values[2] = llvm::ConstantArray::get(AT, Methods);
1774 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1775
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001776 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001777 return llvm::ConstantExpr::getBitCast(GV,
1778 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001779}
1780
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001781llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001782 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001783 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001784 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001785
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001786 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001787 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001788 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001789 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001790 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001791 llvm::GlobalValue::InternalLinkage,
1792 Name,
1793 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001794 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001795
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001796 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001797}
1798
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001799uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
1800 FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001801 if (!Field->isBitField())
1802 return Layout->getElementOffset(
1803 CGM.getTypes().getLLVMFieldNo(Field));
1804 // FIXME. Must be a better way of getting a bitfield base offset.
1805 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1806 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1807 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1808 offset = (offset*size)/8;
1809 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001810}
1811
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001812llvm::GlobalVariable *
1813CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1814 llvm::Constant *Init,
1815 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001816 unsigned Align,
1817 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001818 const llvm::Type *Ty = Init->getType();
1819 llvm::GlobalVariable *GV =
1820 new llvm::GlobalVariable(Ty, false,
1821 llvm::GlobalValue::InternalLinkage,
1822 Init,
1823 Name,
1824 &CGM.getModule());
1825 if (Section)
1826 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001827 if (Align)
1828 GV->setAlignment(Align);
1829 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001830 UsedGlobals.push_back(GV);
1831 return GV;
1832}
1833
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001834llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001835 // Abuse this interface function as a place to finalize.
1836 FinishModule();
1837
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001838 return NULL;
1839}
1840
Daniel Dunbar49f66022008-09-24 03:38:44 +00001841llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1842 return ObjCTypes.GetPropertyFn;
1843}
1844
1845llvm::Function *CGObjCMac::GetPropertySetFunction() {
1846 return ObjCTypes.SetPropertyFn;
1847}
1848
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001849llvm::Function *CGObjCMac::EnumerationMutationFunction()
1850{
1851 return ObjCTypes.EnumerationMutationFn;
1852}
1853
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001854/*
1855
1856Objective-C setjmp-longjmp (sjlj) Exception Handling
1857--
1858
1859The basic framework for a @try-catch-finally is as follows:
1860{
1861 objc_exception_data d;
1862 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001863 bool _call_try_exit = true;
1864
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001865 objc_exception_try_enter(&d);
1866 if (!setjmp(d.jmp_buf)) {
1867 ... try body ...
1868 } else {
1869 // exception path
1870 id _caught = objc_exception_extract(&d);
1871
1872 // enter new try scope for handlers
1873 if (!setjmp(d.jmp_buf)) {
1874 ... match exception and execute catch blocks ...
1875
1876 // fell off end, rethrow.
1877 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001878 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001879 } else {
1880 // exception in catch block
1881 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001882 _call_try_exit = false;
1883 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001884 }
1885 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001886 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001887
1888finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001889 if (_call_try_exit)
1890 objc_exception_try_exit(&d);
1891
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001892 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001893 ... dispatch to finally destination ...
1894
1895finally_rethrow:
1896 objc_exception_throw(_rethrow);
1897
1898finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001899}
1900
1901This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001902uses _rethrow to determine if objc_exception_try_exit should be called
1903and if the object should be rethrown. This breaks in the face of
1904throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001905
1906We specialize this framework for a few particular circumstances:
1907
1908 - If there are no catch blocks, then we avoid emitting the second
1909 exception handling context.
1910
1911 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1912 e)) we avoid emitting the code to rethrow an uncaught exception.
1913
1914 - FIXME: If there is no @finally block we can do a few more
1915 simplifications.
1916
1917Rethrows and Jumps-Through-Finally
1918--
1919
1920Support for implicit rethrows and jumping through the finally block is
1921handled by storing the current exception-handling context in
1922ObjCEHStack.
1923
Daniel Dunbar898d5082008-09-30 01:06:03 +00001924In order to implement proper @finally semantics, we support one basic
1925mechanism for jumping through the finally block to an arbitrary
1926destination. Constructs which generate exits from a @try or @catch
1927block use this mechanism to implement the proper semantics by chaining
1928jumps, as necessary.
1929
1930This mechanism works like the one used for indirect goto: we
1931arbitrarily assign an ID to each destination and store the ID for the
1932destination in a variable prior to entering the finally block. At the
1933end of the finally block we simply create a switch to the proper
1934destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001935
1936Code gen for @synchronized(expr) stmt;
1937Effectively generating code for:
1938objc_sync_enter(expr);
1939@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001940*/
1941
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001942void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1943 const Stmt &S) {
1944 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001945 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001946 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001947 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001948 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1949 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1950 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001951
1952 // For @synchronized, call objc_sync_enter(sync.expr). The
1953 // evaluation of the expression must occur before we enter the
1954 // @synchronized. We can safely avoid a temp here because jumps into
1955 // @synchronized are illegal & this will dominate uses.
1956 llvm::Value *SyncArg = 0;
1957 if (!isTry) {
1958 SyncArg =
1959 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1960 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1961 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1962 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001963
1964 // Push an EH context entry, used for handling rethrows and jumps
1965 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001966 CGF.PushCleanupBlock(FinallyBlock);
1967
Anders Carlsson273558f2009-02-07 21:37:21 +00001968 CGF.ObjCEHValueStack.push_back(0);
1969
Daniel Dunbar898d5082008-09-30 01:06:03 +00001970 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001971 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1972 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001973 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1974 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001975 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1976 "_call_try_exit");
1977 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1978
Anders Carlsson80f25672008-09-09 17:59:25 +00001979 // Enter a new try block and call setjmp.
1980 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1981 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1982 "jmpbufarray");
1983 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1984 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1985 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001986
Daniel Dunbar55e87422008-11-11 02:29:29 +00001987 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1988 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001989 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001990 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001991
1992 // Emit the @try block.
1993 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001994 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1995 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001996 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001997
1998 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001999 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002000
2001 // Retrieve the exception object. We may emit multiple blocks but
2002 // nothing can cross this so the value is already in SSA form.
2003 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2004 ExceptionData,
2005 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002006 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002007 if (!isTry)
2008 {
2009 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002010 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002011 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002012 }
2013 else if (const ObjCAtCatchStmt* CatchStmt =
2014 cast<ObjCAtTryStmt>(S).getCatchStmts())
2015 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002016 // Enter a new exception try block (in case a @catch block throws
2017 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002018 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002019
Anders Carlsson80f25672008-09-09 17:59:25 +00002020 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2021 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002022 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002023
Daniel Dunbar55e87422008-11-11 02:29:29 +00002024 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2025 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002026 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002027
2028 CGF.EmitBlock(CatchBlock);
2029
Daniel Dunbar55e40722008-09-27 07:03:52 +00002030 // Handle catch list. As a special case we check if everything is
2031 // matched and avoid generating code for falling off the end if
2032 // so.
2033 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002034 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002035 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002036
Steve Naroff7ba138a2009-03-03 19:52:17 +00002037 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002038 const PointerType *PT = 0;
2039
Anders Carlsson80f25672008-09-09 17:59:25 +00002040 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002041 if (!CatchParam) {
2042 AllMatched = true;
2043 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002044 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002045
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002046 // catch(id e) always matches.
2047 // FIXME: For the time being we also match id<X>; this should
2048 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002049 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002050 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002051 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002052 }
2053
Daniel Dunbar55e40722008-09-27 07:03:52 +00002054 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002055 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002056 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002057 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002058 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002059 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002060
Anders Carlssondde0a942008-09-11 09:15:33 +00002061 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002062 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002063 break;
2064 }
2065
Daniel Dunbar129271a2008-09-27 07:36:24 +00002066 assert(PT && "Unexpected non-pointer type in @catch");
2067 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002068 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002069 assert(ObjCType && "Catch parameter must have Objective-C type!");
2070
2071 // Check if the @catch block matches the exception object.
2072 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2073
Anders Carlsson80f25672008-09-09 17:59:25 +00002074 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2075 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002076
Daniel Dunbar55e87422008-11-11 02:29:29 +00002077 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002078
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002079 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002080 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002081
2082 // Emit the @catch block.
2083 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002084 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002085 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002086
2087 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002088 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002089 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002090 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002091
2092 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002093 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002094
2095 CGF.EmitBlock(NextCatchBlock);
2096 }
2097
Daniel Dunbar55e40722008-09-27 07:03:52 +00002098 if (!AllMatched) {
2099 // None of the handlers caught the exception, so store it to be
2100 // rethrown at the end of the @finally block.
2101 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002102 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002103 }
2104
2105 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002106 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002107 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2108 ExceptionData),
2109 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002110 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002111 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002112 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002113 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002114 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002115 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002116 }
2117
Daniel Dunbar898d5082008-09-30 01:06:03 +00002118 // Pop the exception-handling stack entry. It is important to do
2119 // this now, because the code in the @finally block is not in this
2120 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002121 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2122
Anders Carlsson273558f2009-02-07 21:37:21 +00002123 CGF.ObjCEHValueStack.pop_back();
2124
Anders Carlsson80f25672008-09-09 17:59:25 +00002125 // Emit the @finally block.
2126 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002127 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2128
2129 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2130
2131 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002132 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002133
2134 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002135 if (isTry) {
2136 if (const ObjCAtFinallyStmt* FinallyStmt =
2137 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2138 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002139 } else {
2140 // Emit objc_sync_exit(expr); as finally's sole statement for
2141 // @synchronized.
2142 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002143 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002144
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002145 // Emit the switch block
2146 if (Info.SwitchBlock)
2147 CGF.EmitBlock(Info.SwitchBlock);
2148 if (Info.EndBlock)
2149 CGF.EmitBlock(Info.EndBlock);
2150
Daniel Dunbar898d5082008-09-30 01:06:03 +00002151 CGF.EmitBlock(FinallyRethrow);
2152 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2153 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002154 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002155
2156 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002157}
2158
2159void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002160 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002161 llvm::Value *ExceptionAsObject;
2162
2163 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2164 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2165 ExceptionAsObject =
2166 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2167 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002168 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002169 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002170 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002171 }
2172
2173 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002174 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002175
2176 // Clear the insertion point to indicate we are in unreachable code.
2177 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002178}
2179
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002180/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002181/// object: objc_read_weak (id *src)
2182///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002183llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002184 llvm::Value *AddrWeakObj)
2185{
Eli Friedman8339b352009-03-07 03:57:15 +00002186 const llvm::Type* DestTy =
2187 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002188 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002189 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002190 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002191 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002192 return read_weak;
2193}
2194
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002195/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2196/// objc_assign_weak (id src, id *dst)
2197///
2198void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2199 llvm::Value *src, llvm::Value *dst)
2200{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002201 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2202 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002203 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2204 src, dst, "weakassign");
2205 return;
2206}
2207
Fariborz Jahanian58626502008-11-19 00:59:10 +00002208/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2209/// objc_assign_global (id src, id *dst)
2210///
2211void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2212 llvm::Value *src, llvm::Value *dst)
2213{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002214 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2215 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002216 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2217 src, dst, "globalassign");
2218 return;
2219}
2220
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002221/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2222/// objc_assign_ivar (id src, id *dst)
2223///
2224void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2225 llvm::Value *src, llvm::Value *dst)
2226{
2227 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2228 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2229 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2230 src, dst, "assignivar");
2231 return;
2232}
2233
Fariborz Jahanian58626502008-11-19 00:59:10 +00002234/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2235/// objc_assign_strongCast (id src, id *dst)
2236///
2237void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2238 llvm::Value *src, llvm::Value *dst)
2239{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002240 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2241 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002242 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2243 src, dst, "weakassign");
2244 return;
2245}
2246
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002247/// EmitObjCValueForIvar - Code Gen for ivar reference.
2248///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002249LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2250 QualType ObjectTy,
2251 llvm::Value *BaseValue,
2252 const ObjCIvarDecl *Ivar,
2253 const FieldDecl *Field,
2254 unsigned CVRQualifiers) {
2255 if (Ivar->isBitField())
2256 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2257 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002258 // TODO: Add a special case for isa (index 0)
2259 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2260 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002261 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002262 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2263 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002264 LValue::SetObjCIvar(LV, true);
2265 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002266}
2267
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002268llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2269 ObjCInterfaceDecl *Interface,
2270 const ObjCIvarDecl *Ivar) {
2271 const llvm::Type *InterfaceLTy =
2272 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2273 const llvm::StructLayout *Layout =
2274 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2275 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002276 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002277 return llvm::ConstantInt::get(
2278 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2279 Offset);
2280}
2281
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002282/* *** Private Interface *** */
2283
2284/// EmitImageInfo - Emit the image info marker used to encode some module
2285/// level information.
2286///
2287/// See: <rdr://4810609&4810587&4810587>
2288/// struct IMAGE_INFO {
2289/// unsigned version;
2290/// unsigned flags;
2291/// };
2292enum ImageInfoFlags {
2293 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2294 eImageInfo_GarbageCollected = (1 << 1),
2295 eImageInfo_GCOnly = (1 << 2)
2296};
2297
2298void CGObjCMac::EmitImageInfo() {
2299 unsigned version = 0; // Version is unused?
2300 unsigned flags = 0;
2301
2302 // FIXME: Fix and continue?
2303 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2304 flags |= eImageInfo_GarbageCollected;
2305 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2306 flags |= eImageInfo_GCOnly;
2307
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002308 // Emitted as int[2];
2309 llvm::Constant *values[2] = {
2310 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2311 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2312 };
2313 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002314
2315 const char *Section;
2316 if (ObjCABI == 1)
2317 Section = "__OBJC, __image_info,regular";
2318 else
2319 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002320 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002321 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2322 llvm::ConstantArray::get(AT, values, 2),
2323 Section,
2324 0,
2325 true);
2326 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002327}
2328
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002329
2330// struct objc_module {
2331// unsigned long version;
2332// unsigned long size;
2333// const char *name;
2334// Symtab symtab;
2335// };
2336
2337// FIXME: Get from somewhere
2338static const int ModuleVersion = 7;
2339
2340void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002341 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002342
2343 std::vector<llvm::Constant*> Values(4);
2344 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2345 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002346 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002347 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002348 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002349 CreateMetadataVar("\01L_OBJC_MODULES",
2350 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2351 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002352 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002353}
2354
2355llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002356 unsigned NumClasses = DefinedClasses.size();
2357 unsigned NumCategories = DefinedCategories.size();
2358
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002359 // Return null if no symbols were defined.
2360 if (!NumClasses && !NumCategories)
2361 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2362
2363 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002364 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2365 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2366 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2367 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2368
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002369 // The runtime expects exactly the list of defined classes followed
2370 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002371 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002372 for (unsigned i=0; i<NumClasses; i++)
2373 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2374 ObjCTypes.Int8PtrTy);
2375 for (unsigned i=0; i<NumCategories; i++)
2376 Symbols[NumClasses + i] =
2377 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2378 ObjCTypes.Int8PtrTy);
2379
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002380 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002381 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002382 NumClasses + NumCategories),
2383 Symbols);
2384
2385 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2386
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002387 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002388 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2389 "__OBJC,__symbols,regular,no_dead_strip",
2390 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002391 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2392}
2393
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002394llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002395 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002396 LazySymbols.insert(ID->getIdentifier());
2397
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002398 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2399
2400 if (!Entry) {
2401 llvm::Constant *Casted =
2402 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2403 ObjCTypes.ClassPtrTy);
2404 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002405 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2406 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2407 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002408 }
2409
2410 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002411}
2412
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002413llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002414 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2415
2416 if (!Entry) {
2417 llvm::Constant *Casted =
2418 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2419 ObjCTypes.SelectorPtrTy);
2420 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002421 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2422 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2423 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002424 }
2425
2426 return Builder.CreateLoad(Entry, false, "tmp");
2427}
2428
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002429llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002430 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002431
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002432 if (!Entry)
2433 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2434 llvm::ConstantArray::get(Ident->getName()),
2435 "__TEXT,__cstring,cstring_literals",
2436 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002437
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002438 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002439}
2440
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002441/// GetIvarLayoutName - Returns a unique constant for the given
2442/// ivar layout bitmap.
2443llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2444 const ObjCCommonTypesHelper &ObjCTypes) {
2445 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2446}
2447
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002448void CGObjCCommonMac::BuildAggrIvarLayout(RecordDecl *RD,
2449 const std::vector<FieldDecl*>& RecFields,
2450 unsigned int BytePos, bool ForStrongLayout,
2451 int &Index, int &SkIndex, bool &HasUnion) {
2452 return;
2453}
2454
2455/// BuildIvarLayout - Builds ivar layout bitmap for the class
2456/// implementation for the __strong or __weak case.
2457/// The layout map displays which words in ivar list must be skipped
2458/// and which must be scanned by GC (see below). String is built of bytes.
2459/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2460/// of words to skip and right nibble is count of words to scan. So, each
2461/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2462/// represented by a 0x00 byte which also ends the string.
2463/// 1. when ForStrongLayout is true, following ivars are scanned:
2464/// - id, Class
2465/// - object *
2466/// - __strong anything
2467///
2468/// 2. When ForStrongLayout is false, following ivars are scanned:
2469/// - __weak anything
2470///
2471llvm::Constant *CGObjCCommonMac::BuildIvarLayout(ObjCImplementationDecl *OMD,
2472 bool ForStrongLayout) {
2473 int iIndex = -1;
2474 int iSkIndex = -1;
2475 bool hasUnion = false;
2476
2477 std::vector<FieldDecl*> RecFields;
2478 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2479 CGM.getContext().CollectObjCIvars(OI, RecFields);
2480 if (RecFields.empty())
2481 return 0;
2482 BuildAggrIvarLayout (0, RecFields, 0, ForStrongLayout,
2483 iIndex, iSkIndex, hasUnion);
2484 return 0;
2485}
2486
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002487llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002488 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2489
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002490 // FIXME: Avoid std::string copying.
2491 if (!Entry)
2492 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2493 llvm::ConstantArray::get(Sel.getAsString()),
2494 "__TEXT,__cstring,cstring_literals",
2495 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002496
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002497 return getConstantGEP(Entry, 0, 0);
2498}
2499
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002500// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002501llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002502 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2503}
2504
2505// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002506llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002507 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2508}
2509
Devang Patel7794bb82009-03-04 18:21:39 +00002510llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2511 std::string TypeStr;
2512 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2513
2514 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002515
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002516 if (!Entry)
2517 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2518 llvm::ConstantArray::get(TypeStr),
2519 "__TEXT,__cstring,cstring_literals",
2520 0, true);
2521
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002522 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002523}
2524
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002525llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002526 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002527 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2528 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002529
2530 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2531
2532 if (!Entry) {
2533 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2534 Entry =
2535 new llvm::GlobalVariable(C->getType(), false,
2536 llvm::GlobalValue::InternalLinkage,
2537 C, "\01L_OBJC_METH_VAR_TYPE_",
2538 &CGM.getModule());
2539 Entry->setSection("__TEXT,__cstring,cstring_literals");
2540 UsedGlobals.push_back(Entry);
2541 }
2542
2543 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002544}
2545
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002546// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002547llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002548 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2549
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002550 if (!Entry)
2551 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
2552 llvm::ConstantArray::get(Ident->getName()),
2553 "__TEXT,__cstring,cstring_literals",
2554 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002555
2556 return getConstantGEP(Entry, 0, 0);
2557}
2558
2559// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002560// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002561llvm::Constant *
2562 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2563 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002564 std::string TypeStr;
2565 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002566 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2567}
2568
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002569void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2570 const ObjCContainerDecl *CD,
2571 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002572 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002573 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002574 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002575 assert (CD && "Missing container decl in GetNameForMethod");
2576 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002577 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2578 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002579 NameOut += ' ';
2580 NameOut += D->getSelector().getAsString();
2581 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002582}
2583
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002584/// GetFirstIvarInRecord - This routine returns the record for the
2585/// implementation of the fiven class OID. It also returns field
2586/// corresponding to the first ivar in the class in FIV. It also
2587/// returns the one before the first ivar.
2588///
2589const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2590 const ObjCInterfaceDecl *OID,
2591 RecordDecl::field_iterator &FIV,
2592 RecordDecl::field_iterator &PIV) {
2593 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2594 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2595 RecordDecl::field_iterator ifield = RD->field_begin();
2596 RecordDecl::field_iterator pfield = RD->field_end();
2597 while (countSuperClassIvars-- > 0) {
2598 pfield = ifield;
2599 ++ifield;
2600 }
2601 FIV = ifield;
2602 PIV = pfield;
2603 return RD;
2604}
2605
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002606void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002607 EmitModuleInfo();
2608
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002609 // Emit the dummy bodies for any protocols which were referenced but
2610 // never defined.
2611 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2612 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2613 if (i->second->hasInitializer())
2614 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002615
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002616 std::vector<llvm::Constant*> Values(5);
2617 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2618 Values[1] = GetClassName(i->first);
2619 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2620 Values[3] = Values[4] =
2621 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2622 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2623 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2624 Values));
2625 }
2626
2627 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002628 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002629 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002630 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002631 }
2632
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002633 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002634 llvm::GlobalValue *GV =
2635 new llvm::GlobalVariable(AT, false,
2636 llvm::GlobalValue::AppendingLinkage,
2637 llvm::ConstantArray::get(AT, Used),
2638 "llvm.used",
2639 &CGM.getModule());
2640
2641 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002642
2643 // Add assembler directives to add lazy undefined symbol references
2644 // for classes which are referenced but not defined. This is
2645 // important for correct linker interaction.
2646
2647 // FIXME: Uh, this isn't particularly portable.
2648 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002649
2650 if (!CGM.getModule().getModuleInlineAsm().empty())
2651 s << "\n";
2652
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002653 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2654 e = LazySymbols.end(); i != e; ++i) {
2655 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2656 }
2657 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2658 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002659 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002660 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2661 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002662
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002663 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002664}
2665
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002666CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002667 : CGObjCCommonMac(cgm),
2668 ObjCTypes(cgm)
2669{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002670 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002671 ObjCABI = 2;
2672}
2673
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002674/* *** */
2675
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002676ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2677: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002678{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002679 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2680 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002681
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002682 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002683 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002684 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002685 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2686
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002687 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002688 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002689 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002690
2691 // FIXME: It would be nice to unify this with the opaque type, so
2692 // that the IR comes out a bit cleaner.
2693 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2694 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002695
2696 // I'm not sure I like this. The implicit coordination is a bit
2697 // gross. We should solve this in a reasonable fashion because this
2698 // is a pretty common task (match some runtime data structure with
2699 // an LLVM data structure).
2700
2701 // FIXME: This is leaked.
2702 // FIXME: Merge with rewriter code?
2703
2704 // struct _objc_super {
2705 // id self;
2706 // Class cls;
2707 // }
2708 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2709 SourceLocation(),
2710 &Ctx.Idents.get("_objc_super"));
2711 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2712 Ctx.getObjCIdType(), 0, false));
2713 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2714 Ctx.getObjCClassType(), 0, false));
2715 RD->completeDefinition(Ctx);
2716
2717 SuperCTy = Ctx.getTagDeclType(RD);
2718 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2719
2720 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002721 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2722
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002723 // struct _prop_t {
2724 // char *name;
2725 // char *attributes;
2726 // }
2727 PropertyTy = llvm::StructType::get(Int8PtrTy,
2728 Int8PtrTy,
2729 NULL);
2730 CGM.getModule().addTypeName("struct._prop_t",
2731 PropertyTy);
2732
2733 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002734 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002735 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002736 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002737 // }
2738 PropertyListTy = llvm::StructType::get(IntTy,
2739 IntTy,
2740 llvm::ArrayType::get(PropertyTy, 0),
2741 NULL);
2742 CGM.getModule().addTypeName("struct._prop_list_t",
2743 PropertyListTy);
2744 // struct _prop_list_t *
2745 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2746
2747 // struct _objc_method {
2748 // SEL _cmd;
2749 // char *method_type;
2750 // char *_imp;
2751 // }
2752 MethodTy = llvm::StructType::get(SelectorPtrTy,
2753 Int8PtrTy,
2754 Int8PtrTy,
2755 NULL);
2756 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002757
2758 // struct _objc_cache *
2759 CacheTy = llvm::OpaqueType::get();
2760 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2761 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002762
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002763 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002764
2765 QualType IdType = Ctx.getObjCIdType();
2766 QualType SelType = Ctx.getObjCSelType();
2767 llvm::SmallVector<QualType,16> Params;
2768 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002769
2770 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002771 Params.push_back(IdType);
2772 Params.push_back(SelType);
2773 Params.push_back(Ctx.LongTy);
2774 Params.push_back(Ctx.BoolTy);
2775 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2776 false);
2777 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002778
2779 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2780 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002781 Params.push_back(IdType);
2782 Params.push_back(SelType);
2783 Params.push_back(Ctx.LongTy);
2784 Params.push_back(IdType);
2785 Params.push_back(Ctx.BoolTy);
2786 Params.push_back(Ctx.BoolTy);
2787 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2788 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2789
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002790 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002791
2792 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002793 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002794 Params.push_back(IdType);
2795 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2796 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2797 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002798
2799 // gc's API
2800 // id objc_read_weak (id *)
2801 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002802 Params.push_back(Ctx.getPointerType(IdType));
2803 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2804 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2805
2806 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002807 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002808 Params.push_back(IdType);
2809 Params.push_back(Ctx.getPointerType(IdType));
2810
2811 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2812 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2813 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2814 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2815 GcAssignStrongCastFn =
2816 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002817
2818 // void objc_exception_throw(id)
2819 Params.clear();
2820 Params.push_back(IdType);
2821
2822 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002823 ExceptionThrowFn =
2824 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002825
2826 // synchronized APIs
2827 // void objc_sync_enter (id)
2828 // void objc_sync_exit (id)
2829 Params.clear();
2830 Params.push_back(IdType);
2831
2832 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2833 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2834 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002835}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002836
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002837ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2838 : ObjCCommonTypesHelper(cgm)
2839{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002840 // struct _objc_method_description {
2841 // SEL name;
2842 // char *types;
2843 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002844 MethodDescriptionTy =
2845 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002846 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002847 NULL);
2848 CGM.getModule().addTypeName("struct._objc_method_description",
2849 MethodDescriptionTy);
2850
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002851 // struct _objc_method_description_list {
2852 // int count;
2853 // struct _objc_method_description[1];
2854 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002855 MethodDescriptionListTy =
2856 llvm::StructType::get(IntTy,
2857 llvm::ArrayType::get(MethodDescriptionTy, 0),
2858 NULL);
2859 CGM.getModule().addTypeName("struct._objc_method_description_list",
2860 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002861
2862 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002863 MethodDescriptionListPtrTy =
2864 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2865
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002866 // Protocol description structures
2867
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002868 // struct _objc_protocol_extension {
2869 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2870 // struct _objc_method_description_list *optional_instance_methods;
2871 // struct _objc_method_description_list *optional_class_methods;
2872 // struct _objc_property_list *instance_properties;
2873 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002874 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002875 llvm::StructType::get(IntTy,
2876 MethodDescriptionListPtrTy,
2877 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002878 PropertyListPtrTy,
2879 NULL);
2880 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2881 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002882
2883 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002884 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2885
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002886 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002887
2888 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2889 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2890
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002891 const llvm::Type *T =
2892 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2893 LongTy,
2894 llvm::ArrayType::get(ProtocolTyHolder, 0),
2895 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002896 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2897
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002898 // struct _objc_protocol {
2899 // struct _objc_protocol_extension *isa;
2900 // char *protocol_name;
2901 // struct _objc_protocol **_objc_protocol_list;
2902 // struct _objc_method_description_list *instance_methods;
2903 // struct _objc_method_description_list *class_methods;
2904 // }
2905 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002906 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002907 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2908 MethodDescriptionListPtrTy,
2909 MethodDescriptionListPtrTy,
2910 NULL);
2911 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2912
2913 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2914 CGM.getModule().addTypeName("struct._objc_protocol_list",
2915 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002916 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002917 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2918
2919 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002920 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002921 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002922
2923 // Class description structures
2924
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002925 // struct _objc_ivar {
2926 // char *ivar_name;
2927 // char *ivar_type;
2928 // int ivar_offset;
2929 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002930 IvarTy = llvm::StructType::get(Int8PtrTy,
2931 Int8PtrTy,
2932 IntTy,
2933 NULL);
2934 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2935
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002936 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002937 IvarListTy = llvm::OpaqueType::get();
2938 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2939 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2940
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002941 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002942 MethodListTy = llvm::OpaqueType::get();
2943 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2944 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2945
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002946 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002947 ClassExtensionTy =
2948 llvm::StructType::get(IntTy,
2949 Int8PtrTy,
2950 PropertyListPtrTy,
2951 NULL);
2952 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2953 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2954
2955 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2956
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002957 // struct _objc_class {
2958 // Class isa;
2959 // Class super_class;
2960 // char *name;
2961 // long version;
2962 // long info;
2963 // long instance_size;
2964 // struct _objc_ivar_list *ivars;
2965 // struct _objc_method_list *methods;
2966 // struct _objc_cache *cache;
2967 // struct _objc_protocol_list *protocols;
2968 // char *ivar_layout;
2969 // struct _objc_class_ext *ext;
2970 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002971 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2972 llvm::PointerType::getUnqual(ClassTyHolder),
2973 Int8PtrTy,
2974 LongTy,
2975 LongTy,
2976 LongTy,
2977 IvarListPtrTy,
2978 MethodListPtrTy,
2979 CachePtrTy,
2980 ProtocolListPtrTy,
2981 Int8PtrTy,
2982 ClassExtensionPtrTy,
2983 NULL);
2984 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2985
2986 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2987 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2988 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2989
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002990 // struct _objc_category {
2991 // char *category_name;
2992 // char *class_name;
2993 // struct _objc_method_list *instance_method;
2994 // struct _objc_method_list *class_method;
2995 // uint32_t size; // sizeof(struct _objc_category)
2996 // struct _objc_property_list *instance_properties;// category's @property
2997 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002998 CategoryTy = llvm::StructType::get(Int8PtrTy,
2999 Int8PtrTy,
3000 MethodListPtrTy,
3001 MethodListPtrTy,
3002 ProtocolListPtrTy,
3003 IntTy,
3004 PropertyListPtrTy,
3005 NULL);
3006 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3007
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003008 // Global metadata structures
3009
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003010 // struct _objc_symtab {
3011 // long sel_ref_cnt;
3012 // SEL *refs;
3013 // short cls_def_cnt;
3014 // short cat_def_cnt;
3015 // char *defs[cls_def_cnt + cat_def_cnt];
3016 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003017 SymtabTy = llvm::StructType::get(LongTy,
3018 SelectorPtrTy,
3019 ShortTy,
3020 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003021 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003022 NULL);
3023 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3024 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3025
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003026 // struct _objc_module {
3027 // long version;
3028 // long size; // sizeof(struct _objc_module)
3029 // char *name;
3030 // struct _objc_symtab* symtab;
3031 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003032 ModuleTy =
3033 llvm::StructType::get(LongTy,
3034 LongTy,
3035 Int8PtrTy,
3036 SymtabPtrTy,
3037 NULL);
3038 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003039
Daniel Dunbar49f66022008-09-24 03:38:44 +00003040 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003041
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003042 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003043 std::vector<const llvm::Type*> Params;
3044 Params.push_back(ObjectPtrTy);
3045 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003046 MessageSendFn =
3047 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3048 Params,
3049 true),
3050 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003051
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003052 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003053 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003054 Params.push_back(ObjectPtrTy);
3055 Params.push_back(SelectorPtrTy);
3056 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003057 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3058 Params,
3059 true),
3060 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003061
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003062 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003063 Params.clear();
3064 Params.push_back(ObjectPtrTy);
3065 Params.push_back(SelectorPtrTy);
3066 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003067 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003068 MessageSendFpretFn =
3069 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3070 Params,
3071 true),
3072 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003073
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003074 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003075 Params.clear();
3076 Params.push_back(SuperPtrTy);
3077 Params.push_back(SelectorPtrTy);
3078 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003079 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3080 Params,
3081 true),
3082 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003083
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003084 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3085 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003086 Params.clear();
3087 Params.push_back(Int8PtrTy);
3088 Params.push_back(SuperPtrTy);
3089 Params.push_back(SelectorPtrTy);
3090 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003091 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3092 Params,
3093 true),
3094 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003095
3096 // There is no objc_msgSendSuper_fpret? How can that work?
3097 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003098
Anders Carlsson124526b2008-09-09 10:10:21 +00003099 // FIXME: This is the size of the setjmp buffer and should be
3100 // target specific. 18 is what's used on 32-bit X86.
3101 uint64_t SetJmpBufferSize = 18;
3102
3103 // Exceptions
3104 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003105 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003106
3107 ExceptionDataTy =
3108 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3109 SetJmpBufferSize),
3110 StackPtrTy, NULL);
3111 CGM.getModule().addTypeName("struct._objc_exception_data",
3112 ExceptionDataTy);
3113
3114 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003115 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3116 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003117 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3118 Params,
3119 false),
3120 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003121 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003122 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3123 Params,
3124 false),
3125 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003126 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003127 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3128 Params,
3129 false),
3130 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003131
3132 Params.clear();
3133 Params.push_back(ClassPtrTy);
3134 Params.push_back(ObjectPtrTy);
3135 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003136 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3137 Params,
3138 false),
3139 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003140
Anders Carlsson124526b2008-09-09 10:10:21 +00003141 Params.clear();
3142 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3143 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003144 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3145 Params,
3146 false),
3147 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003148
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003149}
3150
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003151ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003152: ObjCCommonTypesHelper(cgm)
3153{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003154 // struct _method_list_t {
3155 // uint32_t entsize; // sizeof(struct _objc_method)
3156 // uint32_t method_count;
3157 // struct _objc_method method_list[method_count];
3158 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003159 MethodListnfABITy = llvm::StructType::get(IntTy,
3160 IntTy,
3161 llvm::ArrayType::get(MethodTy, 0),
3162 NULL);
3163 CGM.getModule().addTypeName("struct.__method_list_t",
3164 MethodListnfABITy);
3165 // struct method_list_t *
3166 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003167
3168 // struct _protocol_t {
3169 // id isa; // NULL
3170 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003171 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003172 // const struct method_list_t * const instance_methods;
3173 // const struct method_list_t * const class_methods;
3174 // const struct method_list_t *optionalInstanceMethods;
3175 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003176 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003177 // const uint32_t size; // sizeof(struct _protocol_t)
3178 // const uint32_t flags; // = 0
3179 // }
3180
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003181 // Holder for struct _protocol_list_t *
3182 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3183
3184 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3185 Int8PtrTy,
3186 llvm::PointerType::getUnqual(
3187 ProtocolListTyHolder),
3188 MethodListnfABIPtrTy,
3189 MethodListnfABIPtrTy,
3190 MethodListnfABIPtrTy,
3191 MethodListnfABIPtrTy,
3192 PropertyListPtrTy,
3193 IntTy,
3194 IntTy,
3195 NULL);
3196 CGM.getModule().addTypeName("struct._protocol_t",
3197 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003198
3199 // struct _protocol_t*
3200 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003201
Fariborz Jahanianda320092009-01-29 19:24:30 +00003202 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003203 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003204 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003205 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003206 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3207 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003208 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003209 NULL);
3210 CGM.getModule().addTypeName("struct._objc_protocol_list",
3211 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003212 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3213 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003214
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003215 // struct _objc_protocol_list*
3216 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003217
3218 // struct _ivar_t {
3219 // unsigned long int *offset; // pointer to ivar offset location
3220 // char *name;
3221 // char *type;
3222 // uint32_t alignment;
3223 // uint32_t size;
3224 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003225 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3226 Int8PtrTy,
3227 Int8PtrTy,
3228 IntTy,
3229 IntTy,
3230 NULL);
3231 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3232
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003233 // struct _ivar_list_t {
3234 // uint32 entsize; // sizeof(struct _ivar_t)
3235 // uint32 count;
3236 // struct _iver_t list[count];
3237 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003238 IvarListnfABITy = llvm::StructType::get(IntTy,
3239 IntTy,
3240 llvm::ArrayType::get(
3241 IvarnfABITy, 0),
3242 NULL);
3243 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3244
3245 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003246
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003247 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003248 // uint32_t const flags;
3249 // uint32_t const instanceStart;
3250 // uint32_t const instanceSize;
3251 // uint32_t const reserved; // only when building for 64bit targets
3252 // const uint8_t * const ivarLayout;
3253 // const char *const name;
3254 // const struct _method_list_t * const baseMethods;
3255 // const struct _objc_protocol_list *const baseProtocols;
3256 // const struct _ivar_list_t *const ivars;
3257 // const uint8_t * const weakIvarLayout;
3258 // const struct _prop_list_t * const properties;
3259 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003260
3261 // FIXME. Add 'reserved' field in 64bit abi mode!
3262 ClassRonfABITy = llvm::StructType::get(IntTy,
3263 IntTy,
3264 IntTy,
3265 Int8PtrTy,
3266 Int8PtrTy,
3267 MethodListnfABIPtrTy,
3268 ProtocolListnfABIPtrTy,
3269 IvarListnfABIPtrTy,
3270 Int8PtrTy,
3271 PropertyListPtrTy,
3272 NULL);
3273 CGM.getModule().addTypeName("struct._class_ro_t",
3274 ClassRonfABITy);
3275
3276 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3277 std::vector<const llvm::Type*> Params;
3278 Params.push_back(ObjectPtrTy);
3279 Params.push_back(SelectorPtrTy);
3280 ImpnfABITy = llvm::PointerType::getUnqual(
3281 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3282
3283 // struct _class_t {
3284 // struct _class_t *isa;
3285 // struct _class_t * const superclass;
3286 // void *cache;
3287 // IMP *vtable;
3288 // struct class_ro_t *ro;
3289 // }
3290
3291 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3292 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3293 llvm::PointerType::getUnqual(ClassTyHolder),
3294 CachePtrTy,
3295 llvm::PointerType::getUnqual(ImpnfABITy),
3296 llvm::PointerType::getUnqual(
3297 ClassRonfABITy),
3298 NULL);
3299 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3300
3301 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3302 ClassnfABITy);
3303
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003304 // LLVM for struct _class_t *
3305 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3306
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003307 // struct _category_t {
3308 // const char * const name;
3309 // struct _class_t *const cls;
3310 // const struct _method_list_t * const instance_methods;
3311 // const struct _method_list_t * const class_methods;
3312 // const struct _protocol_list_t * const protocols;
3313 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003314 // }
3315 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003316 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003317 MethodListnfABIPtrTy,
3318 MethodListnfABIPtrTy,
3319 ProtocolListnfABIPtrTy,
3320 PropertyListPtrTy,
3321 NULL);
3322 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003323
3324 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003325 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3326 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003327
3328 // MessageRefTy - LLVM for:
3329 // struct _message_ref_t {
3330 // IMP messenger;
3331 // SEL name;
3332 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003333
3334 // First the clang type for struct _message_ref_t
3335 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3336 SourceLocation(),
3337 &Ctx.Idents.get("_message_ref_t"));
3338 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3339 Ctx.VoidPtrTy, 0, false));
3340 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3341 Ctx.getObjCSelType(), 0, false));
3342 RD->completeDefinition(Ctx);
3343
3344 MessageRefCTy = Ctx.getTagDeclType(RD);
3345 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3346 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003347
3348 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3349 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3350
3351 // SuperMessageRefTy - LLVM for:
3352 // struct _super_message_ref_t {
3353 // SUPER_IMP messenger;
3354 // SEL name;
3355 // };
3356 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3357 SelectorPtrTy,
3358 NULL);
3359 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3360
3361 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3362 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3363
3364 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3365 Params.clear();
3366 Params.push_back(ObjectPtrTy);
3367 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003368 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3369 Params,
3370 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003371 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003372 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003373 "objc_msgSend_fixup");
3374
3375 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3376 MessageSendFpretFixupFn =
3377 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3378 Params,
3379 true),
3380 "objc_msgSend_fpret_fixup");
3381
3382 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3383 MessageSendStretFixupFn =
3384 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3385 Params,
3386 true),
3387 "objc_msgSend_stret_fixup");
3388
3389 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3390 MessageSendIdFixupFn =
3391 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3392 Params,
3393 true),
3394 "objc_msgSendId_fixup");
3395
3396
3397 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3398 MessageSendIdStretFixupFn =
3399 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3400 Params,
3401 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003402 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003403
3404 // id objc_msgSendSuper2_fixup (struct objc_super *,
3405 // struct _super_message_ref_t*, ...)
3406 Params.clear();
3407 Params.push_back(SuperPtrTy);
3408 Params.push_back(SuperMessageRefPtrTy);
3409 MessageSendSuper2FixupFn =
3410 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3411 Params,
3412 true),
3413 "objc_msgSendSuper2_fixup");
3414
3415
3416 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3417 // struct _super_message_ref_t*, ...)
3418 MessageSendSuper2StretFixupFn =
3419 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3420 Params,
3421 true),
3422 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003423
3424 Params.clear();
3425 llvm::Constant *Personality =
3426 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3427 Params,
3428 true),
3429 "__objc_personality_v0");
3430 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3431
3432 Params.clear();
3433 Params.push_back(Int8PtrTy);
3434 UnwindResumeOrRethrowFn =
3435 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3436 Params,
3437 false),
3438 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003439 ObjCBeginCatchFn =
3440 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3441 Params,
3442 false),
3443 "objc_begin_catch");
3444
3445 Params.clear();
3446 ObjCEndCatchFn =
3447 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3448 Params,
3449 false),
3450 "objc_end_catch");
3451
3452 // struct objc_typeinfo {
3453 // const void** vtable; // objc_ehtype_vtable + 2
3454 // const char* name; // c++ typeinfo string
3455 // Class cls;
3456 // };
3457 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3458 Int8PtrTy,
3459 ClassnfABIPtrTy,
3460 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003461 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003462 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003463}
3464
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003465llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3466 FinishNonFragileABIModule();
3467
3468 return NULL;
3469}
3470
3471void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3472 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003473
3474 // Build list of all implemented classe addresses in array
3475 // L_OBJC_LABEL_CLASS_$.
3476 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3477 // list of 'nonlazy' implementations (defined as those with a +load{}
3478 // method!!).
3479 unsigned NumClasses = DefinedClasses.size();
3480 if (NumClasses) {
3481 std::vector<llvm::Constant*> Symbols(NumClasses);
3482 for (unsigned i=0; i<NumClasses; i++)
3483 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3484 ObjCTypes.Int8PtrTy);
3485 llvm::Constant* Init =
3486 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3487 NumClasses),
3488 Symbols);
3489
3490 llvm::GlobalVariable *GV =
3491 new llvm::GlobalVariable(Init->getType(), false,
3492 llvm::GlobalValue::InternalLinkage,
3493 Init,
3494 "\01L_OBJC_LABEL_CLASS_$",
3495 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003496 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003497 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3498 UsedGlobals.push_back(GV);
3499 }
3500
3501 // Build list of all implemented category addresses in array
3502 // L_OBJC_LABEL_CATEGORY_$.
3503 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3504 // list of 'nonlazy' category implementations (defined as those with a +load{}
3505 // method!!).
3506 unsigned NumCategory = DefinedCategories.size();
3507 if (NumCategory) {
3508 std::vector<llvm::Constant*> Symbols(NumCategory);
3509 for (unsigned i=0; i<NumCategory; i++)
3510 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3511 ObjCTypes.Int8PtrTy);
3512 llvm::Constant* Init =
3513 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3514 NumCategory),
3515 Symbols);
3516
3517 llvm::GlobalVariable *GV =
3518 new llvm::GlobalVariable(Init->getType(), false,
3519 llvm::GlobalValue::InternalLinkage,
3520 Init,
3521 "\01L_OBJC_LABEL_CATEGORY_$",
3522 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003523 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003524 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3525 UsedGlobals.push_back(GV);
3526 }
3527
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003528 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3529 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3530 std::vector<llvm::Constant*> Values(2);
3531 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003532 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003533 // FIXME: Fix and continue?
3534 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3535 flags |= eImageInfo_GarbageCollected;
3536 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3537 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003538 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003539 llvm::Constant* Init = llvm::ConstantArray::get(
3540 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3541 Values);
3542 llvm::GlobalVariable *IMGV =
3543 new llvm::GlobalVariable(Init->getType(), false,
3544 llvm::GlobalValue::InternalLinkage,
3545 Init,
3546 "\01L_OBJC_IMAGE_INFO",
3547 &CGM.getModule());
3548 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3549 UsedGlobals.push_back(IMGV);
3550
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003551 std::vector<llvm::Constant*> Used;
3552 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3553 e = UsedGlobals.end(); i != e; ++i) {
3554 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3555 }
3556
3557 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3558 llvm::GlobalValue *GV =
3559 new llvm::GlobalVariable(AT, false,
3560 llvm::GlobalValue::AppendingLinkage,
3561 llvm::ConstantArray::get(AT, Used),
3562 "llvm.used",
3563 &CGM.getModule());
3564
3565 GV->setSection("llvm.metadata");
3566
3567}
3568
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003569// Metadata flags
3570enum MetaDataDlags {
3571 CLS = 0x0,
3572 CLS_META = 0x1,
3573 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003574 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003575 CLS_EXCEPTION = 0x20
3576};
3577/// BuildClassRoTInitializer - generate meta-data for:
3578/// struct _class_ro_t {
3579/// uint32_t const flags;
3580/// uint32_t const instanceStart;
3581/// uint32_t const instanceSize;
3582/// uint32_t const reserved; // only when building for 64bit targets
3583/// const uint8_t * const ivarLayout;
3584/// const char *const name;
3585/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003586/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003587/// const struct _ivar_list_t *const ivars;
3588/// const uint8_t * const weakIvarLayout;
3589/// const struct _prop_list_t * const properties;
3590/// }
3591///
3592llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3593 unsigned flags,
3594 unsigned InstanceStart,
3595 unsigned InstanceSize,
3596 const ObjCImplementationDecl *ID) {
3597 std::string ClassName = ID->getNameAsString();
3598 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3599 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3600 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3601 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3602 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003603 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003604 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003605 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003606 // const struct _method_list_t * const baseMethods;
3607 std::vector<llvm::Constant*> Methods;
3608 std::string MethodListName("\01l_OBJC_$_");
3609 if (flags & CLS_META) {
3610 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3611 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3612 e = ID->classmeth_end(); i != e; ++i) {
3613 // Class methods should always be defined.
3614 Methods.push_back(GetMethodConstant(*i));
3615 }
3616 } else {
3617 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3618 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3619 e = ID->instmeth_end(); i != e; ++i) {
3620 // Instance methods should always be defined.
3621 Methods.push_back(GetMethodConstant(*i));
3622 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003623 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3624 e = ID->propimpl_end(); i != e; ++i) {
3625 ObjCPropertyImplDecl *PID = *i;
3626
3627 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3628 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3629
3630 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3631 if (llvm::Constant *C = GetMethodConstant(MD))
3632 Methods.push_back(C);
3633 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3634 if (llvm::Constant *C = GetMethodConstant(MD))
3635 Methods.push_back(C);
3636 }
3637 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003638 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003639 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003640 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003641
3642 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3643 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3644 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3645 + OID->getNameAsString(),
3646 OID->protocol_begin(),
3647 OID->protocol_end());
3648
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003649 if (flags & CLS_META)
3650 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3651 else
3652 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003653 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003654 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003655 if (flags & CLS_META)
3656 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3657 else
3658 Values[ 9] =
3659 EmitPropertyList(
3660 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3661 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003662 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3663 Values);
3664 llvm::GlobalVariable *CLASS_RO_GV =
3665 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3666 llvm::GlobalValue::InternalLinkage,
3667 Init,
3668 (flags & CLS_META) ?
3669 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3670 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3671 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003672 CLASS_RO_GV->setAlignment(
3673 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003674 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003675 UsedGlobals.push_back(CLASS_RO_GV);
3676 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003677
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003678}
3679
3680/// BuildClassMetaData - This routine defines that to-level meta-data
3681/// for the given ClassName for:
3682/// struct _class_t {
3683/// struct _class_t *isa;
3684/// struct _class_t * const superclass;
3685/// void *cache;
3686/// IMP *vtable;
3687/// struct class_ro_t *ro;
3688/// }
3689///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003690llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3691 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003692 llvm::Constant *IsAGV,
3693 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003694 llvm::Constant *ClassRoGV,
3695 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003696 std::vector<llvm::Constant*> Values(5);
3697 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003698 Values[1] = SuperClassGV
3699 ? SuperClassGV
3700 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003701 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3702 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3703 Values[4] = ClassRoGV; // &CLASS_RO_GV
3704 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3705 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003706 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3707 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003708 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003709 GV->setAlignment(
3710 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003711 if (HiddenVisibility)
3712 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003713 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003714 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003715}
3716
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003717void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3718 std::string ClassName = ID->getNameAsString();
3719 if (!ObjCEmptyCacheVar) {
3720 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003721 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003722 false,
3723 llvm::GlobalValue::ExternalLinkage,
3724 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003725 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003726 &CGM.getModule());
3727 UsedGlobals.push_back(ObjCEmptyCacheVar);
3728
3729 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003730 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003731 false,
3732 llvm::GlobalValue::ExternalLinkage,
3733 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003734 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003735 &CGM.getModule());
3736 UsedGlobals.push_back(ObjCEmptyVtableVar);
3737 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003738 assert(ID->getClassInterface() &&
3739 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003740 uint32_t InstanceStart =
3741 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3742 uint32_t InstanceSize = InstanceStart;
3743 uint32_t flags = CLS_META;
3744 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3745 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003746
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003747 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003748
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003749 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3750 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003751 flags |= OBJC2_CLS_HIDDEN;
3752 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003753 // class is root
3754 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003755 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3756 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003757 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003758 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003759 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3760 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3761 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003762 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003763 // work on super class metadata symbol.
3764 std::string SuperClassName =
3765 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003766 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003767 }
3768 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3769 InstanceStart,
3770 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003771 std::string TClassName = ObjCMetaClassName + ClassName;
3772 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003773 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3774 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003775
3776 // Metadata for the class
3777 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003778 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003779 flags |= OBJC2_CLS_HIDDEN;
3780 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003781 flags |= CLS_ROOT;
3782 SuperClassGV = 0;
3783 }
3784 else {
3785 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003786 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003787 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003788 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003789 }
3790
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003791 InstanceStart = InstanceSize = 0;
3792 if (ObjCInterfaceDecl *OID =
3793 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3794 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003795 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003796 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003797 const llvm::StructLayout *Layout =
3798 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003799
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003800 RecordDecl::field_iterator firstField, lastField;
3801 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003802
3803 for (RecordDecl::field_iterator e = RD->field_end(),
3804 ifield = firstField; ifield != e; ++ifield)
3805 lastField = ifield;
3806
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003807 if (lastField != RD->field_end()) {
3808 FieldDecl *Field = *lastField;
3809 const llvm::Type *FieldTy =
3810 CGM.getTypes().ConvertTypeForMem(Field->getType());
3811 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003812 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003813 if (firstField == RD->field_end())
3814 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003815 else {
3816 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003817 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003818 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003819 }
3820 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003821 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003822 InstanceStart,
3823 InstanceSize,
3824 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003825
3826 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003827 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003828 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3829 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003830 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003831}
3832
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003833/// GenerateProtocolRef - This routine is called to generate code for
3834/// a protocol reference expression; as in:
3835/// @code
3836/// @protocol(Proto1);
3837/// @endcode
3838/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3839/// which will hold address of the protocol meta-data.
3840///
3841llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3842 const ObjCProtocolDecl *PD) {
3843
3844 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3845 ObjCTypes.ExternalProtocolPtrTy);
3846
3847 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3848 ProtocolName += PD->getNameAsCString();
3849
3850 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3851 if (PTGV)
3852 return Builder.CreateLoad(PTGV, false, "tmp");
3853 PTGV = new llvm::GlobalVariable(
3854 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00003855 // FIXME: review, was WeakLinkage,
3856 // also review all other WeakLinkage changes
3857 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003858 Init,
3859 ProtocolName,
3860 &CGM.getModule());
3861 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3862 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3863 UsedGlobals.push_back(PTGV);
3864 return Builder.CreateLoad(PTGV, false, "tmp");
3865}
3866
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003867/// GenerateCategory - Build metadata for a category implementation.
3868/// struct _category_t {
3869/// const char * const name;
3870/// struct _class_t *const cls;
3871/// const struct _method_list_t * const instance_methods;
3872/// const struct _method_list_t * const class_methods;
3873/// const struct _protocol_list_t * const protocols;
3874/// const struct _prop_list_t * const properties;
3875/// }
3876///
3877void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3878{
3879 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003880 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3881 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003882 "_$_" + OCD->getNameAsString());
3883 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3884
3885 std::vector<llvm::Constant*> Values(6);
3886 Values[0] = GetClassName(OCD->getIdentifier());
3887 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003888 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003889 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003890 std::vector<llvm::Constant*> Methods;
3891 std::string MethodListName(Prefix);
3892 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3893 "_$_" + OCD->getNameAsString();
3894
3895 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3896 e = OCD->instmeth_end(); i != e; ++i) {
3897 // Instance methods should always be defined.
3898 Methods.push_back(GetMethodConstant(*i));
3899 }
3900
3901 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003902 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003903 Methods);
3904
3905 MethodListName = Prefix;
3906 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3907 OCD->getNameAsString();
3908 Methods.clear();
3909 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3910 e = OCD->classmeth_end(); i != e; ++i) {
3911 // Class methods should always be defined.
3912 Methods.push_back(GetMethodConstant(*i));
3913 }
3914
3915 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003916 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003917 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003918 const ObjCCategoryDecl *Category =
3919 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003920 if (Category) {
3921 std::string ExtName(Interface->getNameAsString() + "_$_" +
3922 OCD->getNameAsString());
3923 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3924 + Interface->getNameAsString() + "_$_"
3925 + Category->getNameAsString(),
3926 Category->protocol_begin(),
3927 Category->protocol_end());
3928 Values[5] =
3929 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3930 OCD, Category, ObjCTypes);
3931 }
3932 else {
3933 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3934 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3935 }
3936
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003937 llvm::Constant *Init =
3938 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3939 Values);
3940 llvm::GlobalVariable *GCATV
3941 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3942 false,
3943 llvm::GlobalValue::InternalLinkage,
3944 Init,
3945 ExtCatName,
3946 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003947 GCATV->setAlignment(
3948 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003949 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003950 UsedGlobals.push_back(GCATV);
3951 DefinedCategories.push_back(GCATV);
3952}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003953
3954/// GetMethodConstant - Return a struct objc_method constant for the
3955/// given method if it has been defined. The result is null if the
3956/// method has not been defined. The return value has type MethodPtrTy.
3957llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3958 const ObjCMethodDecl *MD) {
3959 // FIXME: Use DenseMap::lookup
3960 llvm::Function *Fn = MethodDefinitions[MD];
3961 if (!Fn)
3962 return 0;
3963
3964 std::vector<llvm::Constant*> Method(3);
3965 Method[0] =
3966 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3967 ObjCTypes.SelectorPtrTy);
3968 Method[1] = GetMethodVarType(MD);
3969 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3970 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3971}
3972
3973/// EmitMethodList - Build meta-data for method declarations
3974/// struct _method_list_t {
3975/// uint32_t entsize; // sizeof(struct _objc_method)
3976/// uint32_t method_count;
3977/// struct _objc_method method_list[method_count];
3978/// }
3979///
3980llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3981 const std::string &Name,
3982 const char *Section,
3983 const ConstantVector &Methods) {
3984 // Return null for empty list.
3985 if (Methods.empty())
3986 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3987
3988 std::vector<llvm::Constant*> Values(3);
3989 // sizeof(struct _objc_method)
3990 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3991 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3992 // method_count
3993 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3994 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3995 Methods.size());
3996 Values[2] = llvm::ConstantArray::get(AT, Methods);
3997 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3998
3999 llvm::GlobalVariable *GV =
4000 new llvm::GlobalVariable(Init->getType(), false,
4001 llvm::GlobalValue::InternalLinkage,
4002 Init,
4003 Name,
4004 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004005 GV->setAlignment(
4006 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004007 GV->setSection(Section);
4008 UsedGlobals.push_back(GV);
4009 return llvm::ConstantExpr::getBitCast(GV,
4010 ObjCTypes.MethodListnfABIPtrTy);
4011}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004012
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004013/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4014/// the given ivar.
4015///
4016llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4017 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004018 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004019 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004020 Name += "\01_OBJC_IVAR_$_" +
4021 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004022 + Ivar->getNameAsString();
4023 llvm::GlobalVariable *IvarOffsetGV =
4024 CGM.getModule().getGlobalVariable(Name);
4025 if (!IvarOffsetGV)
4026 IvarOffsetGV =
4027 new llvm::GlobalVariable(ObjCTypes.LongTy,
4028 false,
4029 llvm::GlobalValue::ExternalLinkage,
4030 0,
4031 Name,
4032 &CGM.getModule());
4033 return IvarOffsetGV;
4034}
4035
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004036llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004037 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004038 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004039 unsigned long int Offset) {
4040
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004041 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004042 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004043 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004044 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004045
4046 llvm::GlobalVariable *IvarOffsetGV =
4047 CGM.getModule().getGlobalVariable(ExternalName);
4048 if (IvarOffsetGV) {
4049 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004050 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004051 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004052 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004053 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004054 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004055 return IvarOffsetGV;
4056 }
4057
4058 IvarOffsetGV =
4059 new llvm::GlobalVariable(Init->getType(),
4060 false,
4061 llvm::GlobalValue::ExternalLinkage,
4062 Init,
4063 ExternalName,
4064 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004065 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004066 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004067 // @private and @package have hidden visibility.
4068 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4069 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4070 if (!globalVisibility)
4071 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004072 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004073 if (IsClassHidden(ID))
4074 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004075
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004076 IvarOffsetGV->setSection("__DATA, __objc_const");
4077 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004078 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004079}
4080
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004081/// EmitIvarList - Emit the ivar list for the given
4082/// implementation. If ForClass is true the list of class ivars
4083/// (i.e. metaclass ivars) is emitted, otherwise the list of
4084/// interface ivars will be emitted. The return value has type
4085/// IvarListnfABIPtrTy.
4086/// struct _ivar_t {
4087/// unsigned long int *offset; // pointer to ivar offset location
4088/// char *name;
4089/// char *type;
4090/// uint32_t alignment;
4091/// uint32_t size;
4092/// }
4093/// struct _ivar_list_t {
4094/// uint32 entsize; // sizeof(struct _ivar_t)
4095/// uint32 count;
4096/// struct _iver_t list[count];
4097/// }
4098///
4099llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4100 const ObjCImplementationDecl *ID) {
4101
4102 std::vector<llvm::Constant*> Ivars, Ivar(5);
4103
4104 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4105 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4106
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004107 // FIXME. Consolidate this with similar code in GenerateClass.
4108 const llvm::Type *InterfaceTy =
4109 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4110 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004111 const llvm::StructLayout *Layout =
4112 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004113
4114 RecordDecl::field_iterator i,p;
4115 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004116 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4117
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004118 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004119 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004120 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004121 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004122 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004123 if (Field->getIdentifier())
4124 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4125 else
4126 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004127 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004128 const llvm::Type *FieldTy =
4129 CGM.getTypes().ConvertTypeForMem(Field->getType());
4130 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4131 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4132 Field->getType().getTypePtr()) >> 3;
4133 Align = llvm::Log2_32(Align);
4134 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004135 // NOTE. Size of a bitfield does not match gcc's, because of the way
4136 // bitfields are treated special in each. But I am told that 'size'
4137 // for bitfield ivars is ignored by the runtime so it does not matter.
4138 // (even if it matters, some day, there is enough info. to get the bitfield
4139 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004140 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4141 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4142 }
4143 // Return null for empty list.
4144 if (Ivars.empty())
4145 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4146 std::vector<llvm::Constant*> Values(3);
4147 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4148 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4149 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4150 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4151 Ivars.size());
4152 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4153 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4154 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4155 llvm::GlobalVariable *GV =
4156 new llvm::GlobalVariable(Init->getType(), false,
4157 llvm::GlobalValue::InternalLinkage,
4158 Init,
4159 Prefix + OID->getNameAsString(),
4160 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004161 GV->setAlignment(
4162 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004163 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004164
4165 UsedGlobals.push_back(GV);
4166 return llvm::ConstantExpr::getBitCast(GV,
4167 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004168}
4169
4170llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4171 const ObjCProtocolDecl *PD) {
4172 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4173
4174 if (!Entry) {
4175 // We use the initializer as a marker of whether this is a forward
4176 // reference or not. At module finalization we add the empty
4177 // contents for protocols which were referenced but never defined.
4178 Entry =
4179 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4180 llvm::GlobalValue::ExternalLinkage,
4181 0,
4182 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4183 &CGM.getModule());
4184 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4185 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004186 }
4187
4188 return Entry;
4189}
4190
4191/// GetOrEmitProtocol - Generate the protocol meta-data:
4192/// @code
4193/// struct _protocol_t {
4194/// id isa; // NULL
4195/// const char * const protocol_name;
4196/// const struct _protocol_list_t * protocol_list; // super protocols
4197/// const struct method_list_t * const instance_methods;
4198/// const struct method_list_t * const class_methods;
4199/// const struct method_list_t *optionalInstanceMethods;
4200/// const struct method_list_t *optionalClassMethods;
4201/// const struct _prop_list_t * properties;
4202/// const uint32_t size; // sizeof(struct _protocol_t)
4203/// const uint32_t flags; // = 0
4204/// }
4205/// @endcode
4206///
4207
4208llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4209 const ObjCProtocolDecl *PD) {
4210 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4211
4212 // Early exit if a defining object has already been generated.
4213 if (Entry && Entry->hasInitializer())
4214 return Entry;
4215
4216 const char *ProtocolName = PD->getNameAsCString();
4217
4218 // Construct method lists.
4219 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4220 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4221 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4222 e = PD->instmeth_end(); i != e; ++i) {
4223 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004224 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004225 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4226 OptInstanceMethods.push_back(C);
4227 } else {
4228 InstanceMethods.push_back(C);
4229 }
4230 }
4231
4232 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4233 e = PD->classmeth_end(); i != e; ++i) {
4234 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004235 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004236 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4237 OptClassMethods.push_back(C);
4238 } else {
4239 ClassMethods.push_back(C);
4240 }
4241 }
4242
4243 std::vector<llvm::Constant*> Values(10);
4244 // isa is NULL
4245 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4246 Values[1] = GetClassName(PD->getIdentifier());
4247 Values[2] = EmitProtocolList(
4248 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4249 PD->protocol_begin(),
4250 PD->protocol_end());
4251
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004252 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004253 + PD->getNameAsString(),
4254 "__DATA, __objc_const",
4255 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004256 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004257 + PD->getNameAsString(),
4258 "__DATA, __objc_const",
4259 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004260 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004261 + PD->getNameAsString(),
4262 "__DATA, __objc_const",
4263 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004264 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004265 + PD->getNameAsString(),
4266 "__DATA, __objc_const",
4267 OptClassMethods);
4268 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4269 0, PD, ObjCTypes);
4270 uint32_t Size =
4271 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4272 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4273 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4274 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4275 Values);
4276
4277 if (Entry) {
4278 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004279 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004280 Entry->setInitializer(Init);
4281 } else {
4282 Entry =
4283 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004284 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004285 Init,
4286 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4287 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004288 Entry->setAlignment(
4289 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004290 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004291 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004292 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4293
4294 // Use this protocol meta-data to build protocol list table in section
4295 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004296 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004297 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004298 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004299 Entry,
4300 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4301 +ProtocolName,
4302 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004303 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004304 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004305 PTGV->setSection("__DATA, __objc_protolist");
4306 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4307 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004308 return Entry;
4309}
4310
4311/// EmitProtocolList - Generate protocol list meta-data:
4312/// @code
4313/// struct _protocol_list_t {
4314/// long protocol_count; // Note, this is 32/64 bit
4315/// struct _protocol_t[protocol_count];
4316/// }
4317/// @endcode
4318///
4319llvm::Constant *
4320CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4321 ObjCProtocolDecl::protocol_iterator begin,
4322 ObjCProtocolDecl::protocol_iterator end) {
4323 std::vector<llvm::Constant*> ProtocolRefs;
4324
Fariborz Jahanianda320092009-01-29 19:24:30 +00004325 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004326 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004327 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4328
Daniel Dunbar948e2582009-02-15 07:36:20 +00004329 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004330 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4331 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004332 return llvm::ConstantExpr::getBitCast(GV,
4333 ObjCTypes.ProtocolListnfABIPtrTy);
4334
4335 for (; begin != end; ++begin)
4336 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4337
Fariborz Jahanianda320092009-01-29 19:24:30 +00004338 // This list is null terminated.
4339 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004340 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004341
4342 std::vector<llvm::Constant*> Values(2);
4343 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4344 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004345 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004346 ProtocolRefs.size()),
4347 ProtocolRefs);
4348
4349 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4350 GV = new llvm::GlobalVariable(Init->getType(), false,
4351 llvm::GlobalValue::InternalLinkage,
4352 Init,
4353 Name,
4354 &CGM.getModule());
4355 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004356 GV->setAlignment(
4357 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004358 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004359 return llvm::ConstantExpr::getBitCast(GV,
4360 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004361}
4362
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004363/// GetMethodDescriptionConstant - This routine build following meta-data:
4364/// struct _objc_method {
4365/// SEL _cmd;
4366/// char *method_type;
4367/// char *_imp;
4368/// }
4369
4370llvm::Constant *
4371CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4372 std::vector<llvm::Constant*> Desc(3);
4373 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4374 ObjCTypes.SelectorPtrTy);
4375 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004376 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004377 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4378 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4379}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004380
4381/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4382/// This code gen. amounts to generating code for:
4383/// @code
4384/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4385/// @encode
4386///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004387LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004388 CodeGen::CodeGenFunction &CGF,
4389 QualType ObjectTy,
4390 llvm::Value *BaseValue,
4391 const ObjCIvarDecl *Ivar,
4392 const FieldDecl *Field,
4393 unsigned CVRQualifiers) {
4394 assert(ObjectTy->isObjCInterfaceType() &&
4395 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004396 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004397 std::string ExternalName;
4398 llvm::GlobalVariable *IvarOffsetGV =
4399 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004400
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004401 // (char *) BaseValue
4402 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4403 ObjCTypes.Int8PtrTy);
4404 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4405 // (char*)BaseValue + Offset_symbol
4406 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4407 // (type *)((char*)BaseValue + Offset_symbol)
4408 const llvm::Type *IvarTy =
4409 CGM.getTypes().ConvertType(Ivar->getType());
4410 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4411 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004412
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004413 if (Ivar->isBitField()) {
4414 CodeGenTypes::BitFieldInfo bitFieldInfo =
4415 CGM.getTypes().getBitFieldInfo(Field);
4416 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4417 Field->getType()->isSignedIntegerType(),
4418 Field->getType().getCVRQualifiers()|CVRQualifiers);
4419 }
4420
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004421 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004422 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4423 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004424 LValue::SetObjCIvar(LV, true);
4425 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004426}
4427
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004428llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4429 CodeGen::CodeGenFunction &CGF,
4430 ObjCInterfaceDecl *Interface,
4431 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004432 std::string ExternalName;
4433 llvm::GlobalVariable *IvarOffsetGV =
4434 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4435
4436 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004437}
4438
Fariborz Jahanian46551122009-02-04 00:22:57 +00004439CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4440 CodeGen::CodeGenFunction &CGF,
4441 QualType ResultType,
4442 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004443 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004444 QualType Arg0Ty,
4445 bool IsSuper,
4446 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004447 // FIXME. Even though IsSuper is passes. This function doese not
4448 // handle calls to 'super' receivers.
4449 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004450 llvm::Value *Arg0 = Receiver;
4451 if (!IsSuper)
4452 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004453
4454 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004455 // FIXME. This is too much work to get the ABI-specific result type
4456 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004457 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4458 llvm::SmallVector<QualType, 16>());
4459 llvm::Constant *Fn;
4460 std::string Name("\01l_");
4461 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004462#if 0
4463 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004464 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4465 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4466 // FIXME. Is there a better way of getting these names.
4467 // They are available in RuntimeFunctions vector pair.
4468 Name += "objc_msgSendId_stret_fixup";
4469 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004470 else
4471#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004472 if (IsSuper) {
4473 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4474 Name += "objc_msgSendSuper2_stret_fixup";
4475 }
4476 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004477 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004478 Fn = ObjCTypes.MessageSendStretFixupFn;
4479 Name += "objc_msgSend_stret_fixup";
4480 }
4481 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004482 else if (ResultType->isFloatingType() &&
4483 // Selection of frret API only happens in 32bit nonfragile ABI.
4484 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004485 Fn = ObjCTypes.MessageSendFpretFixupFn;
4486 Name += "objc_msgSend_fpret_fixup";
4487 }
4488 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004489#if 0
4490// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004491 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4492 Fn = ObjCTypes.MessageSendIdFixupFn;
4493 Name += "objc_msgSendId_fixup";
4494 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004495 else
4496#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004497 if (IsSuper) {
4498 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4499 Name += "objc_msgSendSuper2_fixup";
4500 }
4501 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004502 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004503 Fn = ObjCTypes.MessageSendFixupFn;
4504 Name += "objc_msgSend_fixup";
4505 }
4506 }
4507 Name += '_';
4508 std::string SelName(Sel.getAsString());
4509 // Replace all ':' in selector name with '_' ouch!
4510 for(unsigned i = 0; i < SelName.size(); i++)
4511 if (SelName[i] == ':')
4512 SelName[i] = '_';
4513 Name += SelName;
4514 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4515 if (!GV) {
4516 // Build messafe ref table entry.
4517 std::vector<llvm::Constant*> Values(2);
4518 Values[0] = Fn;
4519 Values[1] = GetMethodVarName(Sel);
4520 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4521 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004522 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004523 Init,
4524 Name,
4525 &CGM.getModule());
4526 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4527 GV->setAlignment(
4528 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4529 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4530 UsedGlobals.push_back(GV);
4531 }
4532 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004533
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004534 CallArgList ActualArgs;
4535 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4536 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4537 ObjCTypes.MessageRefCPtrTy));
4538 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004539 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4540 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4541 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004542 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004543 Callee = CGF.Builder.CreateBitCast(Callee,
4544 llvm::PointerType::getUnqual(FTy));
4545 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004546}
4547
4548/// Generate code for a message send expression in the nonfragile abi.
4549CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4550 CodeGen::CodeGenFunction &CGF,
4551 QualType ResultType,
4552 Selector Sel,
4553 llvm::Value *Receiver,
4554 bool IsClassMessage,
4555 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004556 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004557 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004558 false, CallArgs);
4559}
4560
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004561llvm::GlobalVariable *
4562CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4563 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4564
Daniel Dunbardfff2302009-03-02 05:18:14 +00004565 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004566 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4567 llvm::GlobalValue::ExternalLinkage,
4568 0, Name, &CGM.getModule());
4569 UsedGlobals.push_back(GV);
4570 }
4571
4572 return GV;
4573}
4574
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004575llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004576 const ObjCInterfaceDecl *ID,
4577 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004578
4579 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4580
4581 if (!Entry) {
4582 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004583 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004584 Entry =
4585 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4586 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004587 ClassGV,
4588 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4589 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004590 &CGM.getModule());
4591 Entry->setAlignment(
4592 CGM.getTargetData().getPrefTypeAlignment(
4593 ObjCTypes.ClassnfABIPtrTy));
4594
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004595 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004596 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004597 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004598 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004599 UsedGlobals.push_back(Entry);
4600 }
4601
4602 return Builder.CreateLoad(Entry, false, "tmp");
4603}
4604
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004605/// EmitMetaClassRef - Return a Value * of the address of _class_t
4606/// meta-data
4607///
4608llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4609 const ObjCInterfaceDecl *ID) {
4610 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4611 if (Entry)
4612 return Builder.CreateLoad(Entry, false, "tmp");
4613
4614 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004615 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004616 Entry =
4617 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4618 llvm::GlobalValue::InternalLinkage,
4619 MetaClassGV,
4620 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4621 &CGM.getModule());
4622 Entry->setAlignment(
4623 CGM.getTargetData().getPrefTypeAlignment(
4624 ObjCTypes.ClassnfABIPtrTy));
4625
4626 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4627 UsedGlobals.push_back(Entry);
4628
4629 return Builder.CreateLoad(Entry, false, "tmp");
4630}
4631
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004632/// GetClass - Return a reference to the class for the given interface
4633/// decl.
4634llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4635 const ObjCInterfaceDecl *ID) {
4636 return EmitClassRef(Builder, ID);
4637}
4638
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004639/// Generates a message send where the super is the receiver. This is
4640/// a message send to self with special delivery semantics indicating
4641/// which class's method should be called.
4642CodeGen::RValue
4643CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4644 QualType ResultType,
4645 Selector Sel,
4646 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004647 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004648 llvm::Value *Receiver,
4649 bool IsClassMessage,
4650 const CodeGen::CallArgList &CallArgs) {
4651 // ...
4652 // Create and init a super structure; this is a (receiver, class)
4653 // pair we will pass to objc_msgSendSuper.
4654 llvm::Value *ObjCSuper =
4655 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4656
4657 llvm::Value *ReceiverAsObject =
4658 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4659 CGF.Builder.CreateStore(ReceiverAsObject,
4660 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4661
4662 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004663 llvm::Value *Target;
4664 if (IsClassMessage) {
4665 if (isCategoryImpl) {
4666 // Message sent to "super' in a class method defined in
4667 // a category implementation.
4668 Target = EmitClassRef(CGF.Builder, Class, false);
4669 Target = CGF.Builder.CreateStructGEP(Target, 0);
4670 Target = CGF.Builder.CreateLoad(Target);
4671 }
4672 else
4673 Target = EmitMetaClassRef(CGF.Builder, Class);
4674 }
4675 else
4676 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004677
4678 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4679 // and ObjCTypes types.
4680 const llvm::Type *ClassTy =
4681 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4682 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4683 CGF.Builder.CreateStore(Target,
4684 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4685
4686 return EmitMessageSend(CGF, ResultType, Sel,
4687 ObjCSuper, ObjCTypes.SuperPtrCTy,
4688 true, CallArgs);
4689}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004690
4691llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4692 Selector Sel) {
4693 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4694
4695 if (!Entry) {
4696 llvm::Constant *Casted =
4697 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4698 ObjCTypes.SelectorPtrTy);
4699 Entry =
4700 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4701 llvm::GlobalValue::InternalLinkage,
4702 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4703 &CGM.getModule());
4704 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4705 UsedGlobals.push_back(Entry);
4706 }
4707
4708 return Builder.CreateLoad(Entry, false, "tmp");
4709}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004710/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4711/// objc_assign_ivar (id src, id *dst)
4712///
4713void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4714 llvm::Value *src, llvm::Value *dst)
4715{
4716 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4717 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4718 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4719 src, dst, "assignivar");
4720 return;
4721}
4722
4723/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4724/// objc_assign_strongCast (id src, id *dst)
4725///
4726void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4727 CodeGen::CodeGenFunction &CGF,
4728 llvm::Value *src, llvm::Value *dst)
4729{
4730 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4731 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4732 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4733 src, dst, "weakassign");
4734 return;
4735}
4736
4737/// EmitObjCWeakRead - Code gen for loading value of a __weak
4738/// object: objc_read_weak (id *src)
4739///
4740llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4741 CodeGen::CodeGenFunction &CGF,
4742 llvm::Value *AddrWeakObj)
4743{
Eli Friedman8339b352009-03-07 03:57:15 +00004744 const llvm::Type* DestTy =
4745 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004746 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4747 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4748 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00004749 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004750 return read_weak;
4751}
4752
4753/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4754/// objc_assign_weak (id src, id *dst)
4755///
4756void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4757 llvm::Value *src, llvm::Value *dst)
4758{
4759 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4760 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4761 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4762 src, dst, "weakassign");
4763 return;
4764}
4765
4766/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4767/// objc_assign_global (id src, id *dst)
4768///
4769void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4770 llvm::Value *src, llvm::Value *dst)
4771{
4772 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4773 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4774 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4775 src, dst, "globalassign");
4776 return;
4777}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004778
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004779void
4780CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4781 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004782 bool isTry = isa<ObjCAtTryStmt>(S);
4783 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4784 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004785 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004786 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004787 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004788 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4789
4790 // For @synchronized, call objc_sync_enter(sync.expr). The
4791 // evaluation of the expression must occur before we enter the
4792 // @synchronized. We can safely avoid a temp here because jumps into
4793 // @synchronized are illegal & this will dominate uses.
4794 llvm::Value *SyncArg = 0;
4795 if (!isTry) {
4796 SyncArg =
4797 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4798 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4799 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4800 }
4801
4802 // Push an EH context entry, used for handling rethrows and jumps
4803 // through finally.
4804 CGF.PushCleanupBlock(FinallyBlock);
4805
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004806 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004807
4808 CGF.EmitBlock(TryBlock);
4809 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4810 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4811 CGF.EmitBranchThroughCleanup(FinallyEnd);
4812
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004813 // Emit the exception handler.
4814
4815 CGF.EmitBlock(TryHandler);
4816
4817 llvm::Value *llvm_eh_exception =
4818 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4819 llvm::Value *llvm_eh_selector_i64 =
4820 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4821 llvm::Value *llvm_eh_typeid_for_i64 =
4822 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4823 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4824 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4825
4826 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4827 SelectorArgs.push_back(Exc);
4828 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4829
4830 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004831 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004832 bool HasCatchAll = false;
4833 if (isTry) {
4834 if (const ObjCAtCatchStmt* CatchStmt =
4835 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4836 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004837 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00004838 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004839
4840 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004841 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004842 // Use i8* null here to signal this is a catch all, not a cleanup.
4843 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4844 SelectorArgs.push_back(Null);
4845 HasCatchAll = true;
4846 break;
4847 }
4848
Daniel Dunbarede8de92009-03-06 00:01:21 +00004849 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
4850 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004851 llvm::Value *IDEHType =
4852 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4853 if (!IDEHType)
4854 IDEHType =
4855 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4856 llvm::GlobalValue::ExternalLinkage,
4857 0, "OBJC_EHTYPE_id", &CGM.getModule());
4858 SelectorArgs.push_back(IDEHType);
4859 HasCatchAll = true;
4860 break;
4861 }
4862
4863 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004864 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004865 assert(PT && "Invalid @catch type.");
4866 const ObjCInterfaceType *IT =
4867 PT->getPointeeType()->getAsObjCInterfaceType();
4868 assert(IT && "Invalid @catch type.");
4869 llvm::Value *EHType = GetInterfaceEHType(IT);
4870 SelectorArgs.push_back(EHType);
4871 }
4872 }
4873 }
4874
4875 // We use a cleanup unless there was already a catch all.
4876 if (!HasCatchAll) {
4877 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00004878 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004879 }
4880
4881 llvm::Value *Selector =
4882 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4883 SelectorArgs.begin(), SelectorArgs.end(),
4884 "selector");
4885 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004886 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004887 const Stmt *CatchBody = Handlers[i].second;
4888
4889 llvm::BasicBlock *Next = 0;
4890
4891 // The last handler always matches.
4892 if (i + 1 != e) {
4893 assert(CatchParam && "Only last handler can be a catch all.");
4894
4895 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4896 Next = CGF.createBasicBlock("catch.next");
4897 llvm::Value *Id =
4898 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4899 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4900 ObjCTypes.Int8PtrTy));
4901 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4902 Match, Next);
4903
4904 CGF.EmitBlock(Match);
4905 }
4906
4907 if (CatchBody) {
4908 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4909 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4910
4911 // Cleanups must call objc_end_catch.
4912 //
4913 // FIXME: It seems incorrect for objc_begin_catch to be inside
4914 // this context, but this matches gcc.
4915 CGF.PushCleanupBlock(MatchEnd);
4916 CGF.setInvokeDest(MatchHandler);
4917
4918 llvm::Value *ExcObject =
4919 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4920
4921 // Bind the catch parameter if it exists.
4922 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004923 ExcObject =
4924 CGF.Builder.CreateBitCast(ExcObject,
4925 CGF.ConvertType(CatchParam->getType()));
4926 // CatchParam is a ParmVarDecl because of the grammar
4927 // construction used to handle this, but for codegen purposes
4928 // we treat this as a local decl.
4929 CGF.EmitLocalBlockVarDecl(*CatchParam);
4930 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004931 }
4932
4933 CGF.ObjCEHValueStack.push_back(ExcObject);
4934 CGF.EmitStmt(CatchBody);
4935 CGF.ObjCEHValueStack.pop_back();
4936
4937 CGF.EmitBranchThroughCleanup(FinallyEnd);
4938
4939 CGF.EmitBlock(MatchHandler);
4940
4941 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4942 // We are required to emit this call to satisfy LLVM, even
4943 // though we don't use the result.
4944 llvm::SmallVector<llvm::Value*, 8> Args;
4945 Args.push_back(Exc);
4946 Args.push_back(ObjCTypes.EHPersonalityPtr);
4947 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4948 0));
4949 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4950 CGF.Builder.CreateStore(Exc, RethrowPtr);
4951 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4952
4953 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4954
4955 CGF.EmitBlock(MatchEnd);
4956
4957 // Unfortunately, we also have to generate another EH frame here
4958 // in case this throws.
4959 llvm::BasicBlock *MatchEndHandler =
4960 CGF.createBasicBlock("match.end.handler");
4961 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4962 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
4963 Cont, MatchEndHandler,
4964 Args.begin(), Args.begin());
4965
4966 CGF.EmitBlock(Cont);
4967 if (Info.SwitchBlock)
4968 CGF.EmitBlock(Info.SwitchBlock);
4969 if (Info.EndBlock)
4970 CGF.EmitBlock(Info.EndBlock);
4971
4972 CGF.EmitBlock(MatchEndHandler);
4973 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4974 // We are required to emit this call to satisfy LLVM, even
4975 // though we don't use the result.
4976 Args.clear();
4977 Args.push_back(Exc);
4978 Args.push_back(ObjCTypes.EHPersonalityPtr);
4979 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4980 0));
4981 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4982 CGF.Builder.CreateStore(Exc, RethrowPtr);
4983 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4984
4985 if (Next)
4986 CGF.EmitBlock(Next);
4987 } else {
4988 assert(!Next && "catchup should be last handler.");
4989
4990 CGF.Builder.CreateStore(Exc, RethrowPtr);
4991 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4992 }
4993 }
4994
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004995 // Pop the cleanup entry, the @finally is outside this cleanup
4996 // scope.
4997 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4998 CGF.setInvokeDest(PrevLandingPad);
4999
5000 CGF.EmitBlock(FinallyBlock);
5001
5002 if (isTry) {
5003 if (const ObjCAtFinallyStmt* FinallyStmt =
5004 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5005 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5006 } else {
5007 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5008 // @synchronized.
5009 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005010 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005011
5012 if (Info.SwitchBlock)
5013 CGF.EmitBlock(Info.SwitchBlock);
5014 if (Info.EndBlock)
5015 CGF.EmitBlock(Info.EndBlock);
5016
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005017 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005018 CGF.EmitBranch(FinallyEnd);
5019
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005020 CGF.EmitBlock(FinallyRethrow);
5021 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5022 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005023 CGF.Builder.CreateUnreachable();
5024
5025 CGF.EmitBlock(FinallyEnd);
5026}
5027
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005028/// EmitThrowStmt - Generate code for a throw statement.
5029void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5030 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005031 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005032 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005033 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005034 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005035 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5036 "Unexpected rethrow outside @catch block.");
5037 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005038 }
5039
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005040 llvm::Value *ExceptionAsObject =
5041 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5042 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5043 if (InvokeDest) {
5044 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5045 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5046 Cont, InvokeDest,
5047 &ExceptionAsObject, &ExceptionAsObject + 1);
5048 CGF.EmitBlock(Cont);
5049 } else
5050 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5051 CGF.Builder.CreateUnreachable();
5052
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005053 // Clear the insertion point to indicate we are in unreachable code.
5054 CGF.Builder.ClearInsertionPoint();
5055}
Daniel Dunbare588b992009-03-01 04:46:24 +00005056
5057llvm::Value *
5058CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5059 const ObjCInterfaceDecl *ID = IT->getDecl();
5060 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5061 if (Entry)
5062 return Entry;
5063
5064 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5065 std::string VTableName = "objc_ehtype_vtable";
5066 llvm::GlobalVariable *VTableGV =
5067 CGM.getModule().getGlobalVariable(VTableName);
5068 if (!VTableGV)
5069 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5070 llvm::GlobalValue::ExternalLinkage,
5071 0, VTableName, &CGM.getModule());
5072
5073 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5074
5075 std::vector<llvm::Constant*> Values(3);
5076 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5077 Values[1] = GetClassName(ID->getIdentifier());
5078 Values[2] = GetClassGlobal(ClassName);
5079 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5080
5081 Entry =
5082 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005083 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005084 Init,
5085 (std::string("OBJC_EHTYPE_$_") +
5086 ID->getIdentifier()->getName()),
5087 &CGM.getModule());
5088
5089 return Entry;
5090}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005091
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005092/* *** */
5093
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005094CodeGen::CGObjCRuntime *
5095CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005096 return new CGObjCMac(CGM);
5097}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005098
5099CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005100CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005101 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005102}