blob: bbbed3fe2b1baaf25106b8db0fa945768d9b5512 [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);
384 llvm::Constant *GetMethodVarType(const std::string &Name);
385
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 Jahanian46b86c62009-01-28 19:12:34 +0000398 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
399 RecordDecl::field_iterator &FIV,
400 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000401 /// EmitPropertyList - Emit the given property list. The return
402 /// value has type PropertyListPtrTy.
403 llvm::Constant *EmitPropertyList(const std::string &Name,
404 const Decl *Container,
405 const ObjCContainerDecl *OCD,
406 const ObjCCommonTypesHelper &ObjCTypes);
407
Fariborz Jahanianda320092009-01-29 19:24:30 +0000408 /// GetProtocolRef - Return a reference to the internal protocol
409 /// description, creating an empty one if it has not been
410 /// defined. The return value has type ProtocolPtrTy.
411 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
412
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000413public:
414 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
415 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000416
417 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000418
419 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
420 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000421
422 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
423
424 /// GetOrEmitProtocol - Get the protocol object for the given
425 /// declaration, emitting it if necessary. The return value has type
426 /// ProtocolPtrTy.
427 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
428
429 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
430 /// object for the given declaration, emitting it if needed. These
431 /// forward references will be filled in with empty bodies if no
432 /// definition is seen. The return value has type ProtocolPtrTy.
433 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000434};
435
436class CGObjCMac : public CGObjCCommonMac {
437private:
438 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000439 /// EmitImageInfo - Emit the image info marker used to encode some module
440 /// level information.
441 void EmitImageInfo();
442
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000443 /// EmitModuleInfo - Another marker encoding module level
444 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000445 void EmitModuleInfo();
446
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000447 /// EmitModuleSymols - Emit module symbols, the list of defined
448 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000449 llvm::Constant *EmitModuleSymbols();
450
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000451 /// FinishModule - Write out global data structures at the end of
452 /// processing a translation unit.
453 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000454
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000455 /// EmitClassExtension - Generate the class extension structure used
456 /// to store the weak ivar layout and properties. The return value
457 /// has type ClassExtensionPtrTy.
458 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
459
460 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
461 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000462 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000463 const ObjCInterfaceDecl *ID);
464
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000465 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000466 QualType ResultType,
467 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000468 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000469 QualType Arg0Ty,
470 bool IsSuper,
471 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000472
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000473 /// EmitIvarList - Emit the ivar list for the given
474 /// implementation. If ForClass is true the list of class ivars
475 /// (i.e. metaclass ivars) is emitted, otherwise the list of
476 /// interface ivars will be emitted. The return value has type
477 /// IvarListPtrTy.
478 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000479 bool ForClass);
480
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000481 /// EmitMetaClass - Emit a forward reference to the class structure
482 /// for the metaclass of the given interface. The return value has
483 /// type ClassPtrTy.
484 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
485
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000486 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000487 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000488 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
489 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000490 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000491 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000492
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000493 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000494
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000495 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000496
497 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000498 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000499 llvm::Constant *EmitMethodList(const std::string &Name,
500 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000501 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000502
503 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000504 /// method declarations.
505 /// - TypeName: The name for the type containing the methods.
506 /// - IsProtocol: True iff these methods are for a protocol.
507 /// - ClassMethds: True iff these are class methods.
508 /// - Required: When true, only "required" methods are
509 /// listed. Similarly, when false only "optional" methods are
510 /// listed. For classes this should always be true.
511 /// - begin, end: The method list to output.
512 ///
513 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000514 llvm::Constant *EmitMethodDescList(const std::string &Name,
515 const char *Section,
516 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000517
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000518 /// GetOrEmitProtocol - Get the protocol object for the given
519 /// declaration, emitting it if necessary. The return value has type
520 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000521 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000522
523 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
524 /// object for the given declaration, emitting it if needed. These
525 /// forward references will be filled in with empty bodies if no
526 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000527 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000528
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000529 /// EmitProtocolExtension - Generate the protocol extension
530 /// structure used to store optional instance and class methods, and
531 /// protocol properties. The return value has type
532 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000533 llvm::Constant *
534 EmitProtocolExtension(const ObjCProtocolDecl *PD,
535 const ConstantVector &OptInstanceMethods,
536 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000537
538 /// EmitProtocolList - Generate the list of referenced
539 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000540 llvm::Constant *EmitProtocolList(const std::string &Name,
541 ObjCProtocolDecl::protocol_iterator begin,
542 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000543
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000544 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
545 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000546 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000547
Fariborz Jahanianda320092009-01-29 19:24:30 +0000548 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000549 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000550
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000551 virtual llvm::Function *ModuleInitFunction();
552
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000553 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000554 QualType ResultType,
555 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000556 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000557 bool IsClassMessage,
558 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000559
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000560 virtual CodeGen::RValue
561 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000562 QualType ResultType,
563 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000564 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000565 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000566 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000567 bool IsClassMessage,
568 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000569
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000570 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000571 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000572
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000573 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000574
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000575 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000576
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000577 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000578
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000579 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000580 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000581
Daniel Dunbar49f66022008-09-24 03:38:44 +0000582 virtual llvm::Function *GetPropertyGetFunction();
583 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000584 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000585
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000586 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
587 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000588 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
589 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000590 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000591 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000592 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
593 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000594 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
595 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000596 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
597 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000598 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
599 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000600
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000601 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
602 QualType ObjectTy,
603 llvm::Value *BaseValue,
604 const ObjCIvarDecl *Ivar,
605 const FieldDecl *Field,
606 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000607 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
608 ObjCInterfaceDecl *Interface,
609 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000610};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000611
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000612class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000613private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000614 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000615 llvm::GlobalVariable* ObjCEmptyCacheVar;
616 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000617
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000618 /// MetaClassReferences - uniqued meta class references.
619 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000620
621 /// EHTypeReferences - uniqued class ehtype references.
622 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000623
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000624 /// FinishNonFragileABIModule - Write out global data structures at the end of
625 /// processing a translation unit.
626 void FinishNonFragileABIModule();
627
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000628 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
629 unsigned InstanceStart,
630 unsigned InstanceSize,
631 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000632 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
633 llvm::Constant *IsAGV,
634 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000635 llvm::Constant *ClassRoGV,
636 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000637
638 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
639
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000640 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
641
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000642 /// EmitMethodList - Emit the method list for the given
643 /// implementation. The return value has type MethodListnfABITy.
644 llvm::Constant *EmitMethodList(const std::string &Name,
645 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000646 const ConstantVector &Methods);
647 /// EmitIvarList - Emit the ivar list for the given
648 /// implementation. If ForClass is true the list of class ivars
649 /// (i.e. metaclass ivars) is emitted, otherwise the list of
650 /// interface ivars will be emitted. The return value has type
651 /// IvarListnfABIPtrTy.
652 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000653
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000654 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000655 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000656 unsigned long int offset);
657
Fariborz Jahanianda320092009-01-29 19:24:30 +0000658 /// GetOrEmitProtocol - Get the protocol object for the given
659 /// declaration, emitting it if necessary. The return value has type
660 /// ProtocolPtrTy.
661 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
662
663 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
664 /// object for the given declaration, emitting it if needed. These
665 /// forward references will be filled in with empty bodies if no
666 /// definition is seen. The return value has type ProtocolPtrTy.
667 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
668
669 /// EmitProtocolList - Generate the list of referenced
670 /// protocols. The return value has type ProtocolListPtrTy.
671 llvm::Constant *EmitProtocolList(const std::string &Name,
672 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000673 ObjCProtocolDecl::protocol_iterator end);
674
675 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
676 QualType ResultType,
677 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000678 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000679 QualType Arg0Ty,
680 bool IsSuper,
681 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000682
683 /// GetClassGlobal - Return the global variable for the Objective-C
684 /// class of the given name.
685 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000686
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000687 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
688 /// for the given class.
689 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000690 const ObjCInterfaceDecl *ID,
691 bool IsSuper = false);
692
693 /// EmitMetaClassRef - Return a Value * of the address of _class_t
694 /// meta-data
695 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
696 const ObjCInterfaceDecl *ID);
697
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000698 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
699 /// the given ivar.
700 ///
701 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000702 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000703 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000704
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000705 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
706 /// for the given selector.
707 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000708
709 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
710 /// interface. The return value has type EHTypePtrTy.
711 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000712
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000713public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000714 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000715 // FIXME. All stubs for now!
716 virtual llvm::Function *ModuleInitFunction();
717
718 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
719 QualType ResultType,
720 Selector Sel,
721 llvm::Value *Receiver,
722 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000723 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000724
725 virtual CodeGen::RValue
726 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
727 QualType ResultType,
728 Selector Sel,
729 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000730 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000731 llvm::Value *Receiver,
732 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000733 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000734
735 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000736 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000737
738 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000739 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000740
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000741 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000742
743 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000744 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000745 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000746
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000747 virtual llvm::Function *GetPropertyGetFunction(){
748 return ObjCTypes.GetPropertyFn;
749 }
750 virtual llvm::Function *GetPropertySetFunction(){
751 return ObjCTypes.SetPropertyFn;
752 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000753 virtual llvm::Function *EnumerationMutationFunction() {
754 return ObjCTypes.EnumerationMutationFn;
755 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000756
757 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000758 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000759 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000760 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000761 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000762 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000763 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000764 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000765 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000766 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000767 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000768 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000769 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000770 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000771 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
772 QualType ObjectTy,
773 llvm::Value *BaseValue,
774 const ObjCIvarDecl *Ivar,
775 const FieldDecl *Field,
776 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000777 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
778 ObjCInterfaceDecl *Interface,
779 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000780};
781
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000782} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000783
784/* *** Helper Functions *** */
785
786/// getConstantGEP() - Help routine to construct simple GEPs.
787static llvm::Constant *getConstantGEP(llvm::Constant *C,
788 unsigned idx0,
789 unsigned idx1) {
790 llvm::Value *Idxs[] = {
791 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
792 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
793 };
794 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
795}
796
797/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000798
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000799CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
800 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000801{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000802 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000803 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000804}
805
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000806/// GetClass - Return a reference to the class for the given interface
807/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000808llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000809 const ObjCInterfaceDecl *ID) {
810 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000811}
812
813/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000814llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000815 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000816}
817
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000818/// Generate a constant CFString object.
819/*
820 struct __builtin_CFString {
821 const int *isa; // point to __CFConstantStringClassReference
822 int flags;
823 const char *str;
824 long length;
825 };
826*/
827
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000828llvm::Constant *CGObjCCommonMac::GenerateConstantString(
829 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000830 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000831}
832
833/// Generates a message send where the super is the receiver. This is
834/// a message send to self with special delivery semantics indicating
835/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000836CodeGen::RValue
837CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000838 QualType ResultType,
839 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000840 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000841 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000842 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000843 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000844 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000845 // Create and init a super structure; this is a (receiver, class)
846 // pair we will pass to objc_msgSendSuper.
847 llvm::Value *ObjCSuper =
848 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
849 llvm::Value *ReceiverAsObject =
850 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
851 CGF.Builder.CreateStore(ReceiverAsObject,
852 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000853
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000854 // If this is a class message the metaclass is passed as the target.
855 llvm::Value *Target;
856 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000857 if (isCategoryImpl) {
858 // Message sent to 'super' in a class method defined in a category
859 // implementation requires an odd treatment.
860 // If we are in a class method, we must retrieve the
861 // _metaclass_ for the current class, pointed at by
862 // the class's "isa" pointer. The following assumes that
863 // isa" is the first ivar in a class (which it must be).
864 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
865 Target = CGF.Builder.CreateStructGEP(Target, 0);
866 Target = CGF.Builder.CreateLoad(Target);
867 }
868 else {
869 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
870 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
871 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
872 Target = Super;
873 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000874 } else {
875 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
876 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000877 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
878 // and ObjCTypes types.
879 const llvm::Type *ClassTy =
880 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000881 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000882 CGF.Builder.CreateStore(Target,
883 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
884
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000885 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000886 ObjCSuper, ObjCTypes.SuperPtrCTy,
887 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000888}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000889
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000890/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000891CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000892 QualType ResultType,
893 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000894 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000895 bool IsClassMessage,
896 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000897 llvm::Value *Arg0 =
898 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000899 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000900 Arg0, CGF.getContext().getObjCIdType(),
901 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000902}
903
904CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000905 QualType ResultType,
906 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000907 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000908 QualType Arg0Ty,
909 bool IsSuper,
910 const CallArgList &CallArgs) {
911 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000912 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
913 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
914 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000915 CGF.getContext().getObjCSelType()));
916 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000917
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000918 CodeGenTypes &Types = CGM.getTypes();
919 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
920 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000921
922 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000923 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000924 Fn = ObjCTypes.getSendStretFn(IsSuper);
925 } else if (ResultType->isFloatingType()) {
926 // FIXME: Sadly, this is wrong. This actually depends on the
927 // architecture. This happens to be right for x86-32 though.
928 Fn = ObjCTypes.getSendFpretFn(IsSuper);
929 } else {
930 Fn = ObjCTypes.getSendFn(IsSuper);
931 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000932 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000933 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000934}
935
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000936llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000937 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000938 // FIXME: I don't understand why gcc generates this, or where it is
939 // resolved. Investigate. Its also wasteful to look this up over and
940 // over.
941 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
942
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000943 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
944 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000945}
946
Fariborz Jahanianda320092009-01-29 19:24:30 +0000947void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000948 // FIXME: We shouldn't need this, the protocol decl should contain
949 // enough information to tell us whether this was a declaration or a
950 // definition.
951 DefinedProtocols.insert(PD->getIdentifier());
952
953 // If we have generated a forward reference to this protocol, emit
954 // it now. Otherwise do nothing, the protocol objects are lazily
955 // emitted.
956 if (Protocols.count(PD->getIdentifier()))
957 GetOrEmitProtocol(PD);
958}
959
Fariborz Jahanianda320092009-01-29 19:24:30 +0000960llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000961 if (DefinedProtocols.count(PD->getIdentifier()))
962 return GetOrEmitProtocol(PD);
963 return GetOrEmitProtocolRef(PD);
964}
965
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000966/*
967 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
968 struct _objc_protocol {
969 struct _objc_protocol_extension *isa;
970 char *protocol_name;
971 struct _objc_protocol_list *protocol_list;
972 struct _objc__method_prototype_list *instance_methods;
973 struct _objc__method_prototype_list *class_methods
974 };
975
976 See EmitProtocolExtension().
977*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000978llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
979 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
980
981 // Early exit if a defining object has already been generated.
982 if (Entry && Entry->hasInitializer())
983 return Entry;
984
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000985 // FIXME: I don't understand why gcc generates this, or where it is
986 // resolved. Investigate. Its also wasteful to look this up over and
987 // over.
988 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
989
Chris Lattner8ec03f52008-11-24 03:54:41 +0000990 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000991
992 // Construct method lists.
993 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
994 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
995 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
996 e = PD->instmeth_end(); i != e; ++i) {
997 ObjCMethodDecl *MD = *i;
998 llvm::Constant *C = GetMethodDescriptionConstant(MD);
999 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1000 OptInstanceMethods.push_back(C);
1001 } else {
1002 InstanceMethods.push_back(C);
1003 }
1004 }
1005
1006 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1007 e = PD->classmeth_end(); i != e; ++i) {
1008 ObjCMethodDecl *MD = *i;
1009 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1010 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1011 OptClassMethods.push_back(C);
1012 } else {
1013 ClassMethods.push_back(C);
1014 }
1015 }
1016
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001017 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001018 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001019 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001020 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001021 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001022 PD->protocol_begin(),
1023 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001024 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001025 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1026 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001027 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1028 InstanceMethods);
1029 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001030 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1031 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001032 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1033 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001034 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1035 Values);
1036
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001037 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001038 // Already created, fix the linkage and update the initializer.
1039 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001040 Entry->setInitializer(Init);
1041 } else {
1042 Entry =
1043 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1044 llvm::GlobalValue::InternalLinkage,
1045 Init,
1046 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1047 &CGM.getModule());
1048 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1049 UsedGlobals.push_back(Entry);
1050 // FIXME: Is this necessary? Why only for protocol?
1051 Entry->setAlignment(4);
1052 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001053
1054 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001055}
1056
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001057llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001058 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1059
1060 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001061 // We use the initializer as a marker of whether this is a forward
1062 // reference or not. At module finalization we add the empty
1063 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001064 Entry =
1065 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001066 llvm::GlobalValue::ExternalLinkage,
1067 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001068 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001069 &CGM.getModule());
1070 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1071 UsedGlobals.push_back(Entry);
1072 // FIXME: Is this necessary? Why only for protocol?
1073 Entry->setAlignment(4);
1074 }
1075
1076 return Entry;
1077}
1078
1079/*
1080 struct _objc_protocol_extension {
1081 uint32_t size;
1082 struct objc_method_description_list *optional_instance_methods;
1083 struct objc_method_description_list *optional_class_methods;
1084 struct objc_property_list *instance_properties;
1085 };
1086*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001087llvm::Constant *
1088CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1089 const ConstantVector &OptInstanceMethods,
1090 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001091 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001092 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001093 std::vector<llvm::Constant*> Values(4);
1094 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001095 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001096 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1097 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001098 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1099 OptInstanceMethods);
1100 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001101 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1102 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1104 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001105 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1106 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001107 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001108
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001109 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001110 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1111 Values[3]->isNullValue())
1112 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1113
1114 llvm::Constant *Init =
1115 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1116 llvm::GlobalVariable *GV =
1117 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1118 llvm::GlobalValue::InternalLinkage,
1119 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001121 &CGM.getModule());
1122 // No special section, but goes in llvm.used
1123 UsedGlobals.push_back(GV);
1124
1125 return GV;
1126}
1127
1128/*
1129 struct objc_protocol_list {
1130 struct objc_protocol_list *next;
1131 long count;
1132 Protocol *list[];
1133 };
1134*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001135llvm::Constant *
1136CGObjCMac::EmitProtocolList(const std::string &Name,
1137 ObjCProtocolDecl::protocol_iterator begin,
1138 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001139 std::vector<llvm::Constant*> ProtocolRefs;
1140
Daniel Dunbardbc93372008-08-21 21:57:41 +00001141 for (; begin != end; ++begin)
1142 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001143
1144 // Just return null for empty protocol lists
1145 if (ProtocolRefs.empty())
1146 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1147
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001148 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001149 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1150
1151 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001152 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001153 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1154 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1155 Values[2] =
1156 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1157 ProtocolRefs.size()),
1158 ProtocolRefs);
1159
1160 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1161 llvm::GlobalVariable *GV =
1162 new llvm::GlobalVariable(Init->getType(), false,
1163 llvm::GlobalValue::InternalLinkage,
1164 Init,
Daniel Dunbardbc93372008-08-21 21:57:41 +00001165 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 &CGM.getModule());
1167 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1168 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1169}
1170
1171/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001172 struct _objc_property {
1173 const char * const name;
1174 const char * const attributes;
1175 };
1176
1177 struct _objc_property_list {
1178 uint32_t entsize; // sizeof (struct _objc_property)
1179 uint32_t prop_count;
1180 struct _objc_property[prop_count];
1181 };
1182*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001183llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1184 const Decl *Container,
1185 const ObjCContainerDecl *OCD,
1186 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001187 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001188 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1189 E = OCD->prop_end(); I != E; ++I) {
1190 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001191 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001192 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001193 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1194 Prop));
1195 }
1196
1197 // Return null for empty list.
1198 if (Properties.empty())
1199 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1200
1201 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001202 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001203 std::vector<llvm::Constant*> Values(3);
1204 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1205 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1206 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1207 Properties.size());
1208 Values[2] = llvm::ConstantArray::get(AT, Properties);
1209 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1210
1211 llvm::GlobalVariable *GV =
1212 new llvm::GlobalVariable(Init->getType(), false,
1213 llvm::GlobalValue::InternalLinkage,
1214 Init,
1215 Name,
1216 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001217 if (ObjCABI == 2)
1218 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001219 // No special section on property lists?
1220 UsedGlobals.push_back(GV);
1221 return llvm::ConstantExpr::getBitCast(GV,
1222 ObjCTypes.PropertyListPtrTy);
1223
1224}
1225
1226/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001227 struct objc_method_description_list {
1228 int count;
1229 struct objc_method_description list[];
1230 };
1231*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001232llvm::Constant *
1233CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1234 std::vector<llvm::Constant*> Desc(2);
1235 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1236 ObjCTypes.SelectorPtrTy);
1237 Desc[1] = GetMethodVarType(MD);
1238 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1239 Desc);
1240}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001241
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001242llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1243 const char *Section,
1244 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001245 // Return null for empty list.
1246 if (Methods.empty())
1247 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1248
1249 std::vector<llvm::Constant*> Values(2);
1250 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1251 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1252 Methods.size());
1253 Values[1] = llvm::ConstantArray::get(AT, Methods);
1254 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1255
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001256 llvm::GlobalVariable *GV =
1257 new llvm::GlobalVariable(Init->getType(), false,
1258 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001259 Init, Name, &CGM.getModule());
1260 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 UsedGlobals.push_back(GV);
1262 return llvm::ConstantExpr::getBitCast(GV,
1263 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001264}
1265
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001266/*
1267 struct _objc_category {
1268 char *category_name;
1269 char *class_name;
1270 struct _objc_method_list *instance_methods;
1271 struct _objc_method_list *class_methods;
1272 struct _objc_protocol_list *protocols;
1273 uint32_t size; // <rdar://4585769>
1274 struct _objc_property_list *instance_properties;
1275 };
1276 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001277void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001278 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001279
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001280 // FIXME: This is poor design, the OCD should have a pointer to the
1281 // category decl. Additionally, note that Category can be null for
1282 // the @implementation w/o an @interface case. Sema should just
1283 // create one for us as it does for @implementation so everyone else
1284 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001285 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001286 const ObjCCategoryDecl *Category =
1287 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001288 std::string ExtName(Interface->getNameAsString() + "_" +
1289 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001290
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001291 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1292 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1293 e = OCD->instmeth_end(); i != e; ++i) {
1294 // Instance methods should always be defined.
1295 InstanceMethods.push_back(GetMethodConstant(*i));
1296 }
1297 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1298 e = OCD->classmeth_end(); i != e; ++i) {
1299 // Class methods should always be defined.
1300 ClassMethods.push_back(GetMethodConstant(*i));
1301 }
1302
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001303 std::vector<llvm::Constant*> Values(7);
1304 Values[0] = GetClassName(OCD->getIdentifier());
1305 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001306 Values[2] =
1307 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1308 ExtName,
1309 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001310 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 Values[3] =
1312 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1313 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001314 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001315 if (Category) {
1316 Values[4] =
1317 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1318 Category->protocol_begin(),
1319 Category->protocol_end());
1320 } else {
1321 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1322 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001323 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001324
1325 // If there is no category @interface then there can be no properties.
1326 if (Category) {
1327 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001328 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001329 } else {
1330 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1331 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001332
1333 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1334 Values);
1335
1336 llvm::GlobalVariable *GV =
1337 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1338 llvm::GlobalValue::InternalLinkage,
1339 Init,
1340 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1341 &CGM.getModule());
1342 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1343 UsedGlobals.push_back(GV);
1344 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001345}
1346
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001347// FIXME: Get from somewhere?
1348enum ClassFlags {
1349 eClassFlags_Factory = 0x00001,
1350 eClassFlags_Meta = 0x00002,
1351 // <rdr://5142207>
1352 eClassFlags_HasCXXStructors = 0x02000,
1353 eClassFlags_Hidden = 0x20000,
1354 eClassFlags_ABI2_Hidden = 0x00010,
1355 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1356};
1357
1358// <rdr://5142207&4705298&4843145>
1359static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1360 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1361 // FIXME: Support -fvisibility
1362 switch (attr->getVisibility()) {
1363 default:
1364 assert(0 && "Unknown visibility");
1365 return false;
1366 case VisibilityAttr::DefaultVisibility:
1367 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1368 return false;
1369 case VisibilityAttr::HiddenVisibility:
1370 return true;
1371 }
1372 } else {
1373 return false; // FIXME: Support -fvisibility
1374 }
1375}
1376
1377/*
1378 struct _objc_class {
1379 Class isa;
1380 Class super_class;
1381 const char *name;
1382 long version;
1383 long info;
1384 long instance_size;
1385 struct _objc_ivar_list *ivars;
1386 struct _objc_method_list *methods;
1387 struct _objc_cache *cache;
1388 struct _objc_protocol_list *protocols;
1389 // Objective-C 1.0 extensions (<rdr://4585769>)
1390 const char *ivar_layout;
1391 struct _objc_class_ext *ext;
1392 };
1393
1394 See EmitClassExtension();
1395 */
1396void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001397 DefinedSymbols.insert(ID->getIdentifier());
1398
Chris Lattner8ec03f52008-11-24 03:54:41 +00001399 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001400 // FIXME: Gross
1401 ObjCInterfaceDecl *Interface =
1402 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001403 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001404 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001405 Interface->protocol_begin(),
1406 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001407 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001408 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001409 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001410 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001411
1412 // FIXME: Set CXX-structors flag.
1413 if (IsClassHidden(ID->getClassInterface()))
1414 Flags |= eClassFlags_Hidden;
1415
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001416 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1417 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1418 e = ID->instmeth_end(); i != e; ++i) {
1419 // Instance methods should always be defined.
1420 InstanceMethods.push_back(GetMethodConstant(*i));
1421 }
1422 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1423 e = ID->classmeth_end(); i != e; ++i) {
1424 // Class methods should always be defined.
1425 ClassMethods.push_back(GetMethodConstant(*i));
1426 }
1427
1428 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1429 e = ID->propimpl_end(); i != e; ++i) {
1430 ObjCPropertyImplDecl *PID = *i;
1431
1432 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1433 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1434
1435 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1436 if (llvm::Constant *C = GetMethodConstant(MD))
1437 InstanceMethods.push_back(C);
1438 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1439 if (llvm::Constant *C = GetMethodConstant(MD))
1440 InstanceMethods.push_back(C);
1441 }
1442 }
1443
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001444 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001445 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001446 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001447 // Record a reference to the super class.
1448 LazySymbols.insert(Super->getIdentifier());
1449
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001450 Values[ 1] =
1451 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1452 ObjCTypes.ClassPtrTy);
1453 } else {
1454 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1455 }
1456 Values[ 2] = GetClassName(ID->getIdentifier());
1457 // Version is always 0.
1458 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1459 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1460 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001461 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001462 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001463 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001464 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001465 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 // cache is always NULL.
1467 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1468 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001469 // FIXME: Set ivar_layout
1470 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 Values[11] = EmitClassExtension(ID);
1472 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1473 Values);
1474
1475 llvm::GlobalVariable *GV =
1476 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1477 llvm::GlobalValue::InternalLinkage,
1478 Init,
1479 std::string("\01L_OBJC_CLASS_")+ClassName,
1480 &CGM.getModule());
1481 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1482 UsedGlobals.push_back(GV);
1483 // FIXME: Why?
1484 GV->setAlignment(32);
1485 DefinedClasses.push_back(GV);
1486}
1487
1488llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1489 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001490 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001491 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001492 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001493 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001494
1495 if (IsClassHidden(ID->getClassInterface()))
1496 Flags |= eClassFlags_Hidden;
1497
1498 std::vector<llvm::Constant*> Values(12);
1499 // The isa for the metaclass is the root of the hierarchy.
1500 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1501 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1502 Root = Super;
1503 Values[ 0] =
1504 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1505 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001506 // The super class for the metaclass is emitted as the name of the
1507 // super class. The runtime fixes this up to point to the
1508 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001509 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1510 Values[ 1] =
1511 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1512 ObjCTypes.ClassPtrTy);
1513 } else {
1514 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1515 }
1516 Values[ 2] = GetClassName(ID->getIdentifier());
1517 // Version is always 0.
1518 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1519 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1520 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001521 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001522 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001524 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001525 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001526 // cache is always NULL.
1527 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1528 Values[ 9] = Protocols;
1529 // ivar_layout for metaclass is always NULL.
1530 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1531 // The class extension is always unused for metaclasses.
1532 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1533 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1534 Values);
1535
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001536 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001537 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001538
1539 // Check for a forward reference.
1540 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1541 if (GV) {
1542 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1543 "Forward metaclass reference has incorrect type.");
1544 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1545 GV->setInitializer(Init);
1546 } else {
1547 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1548 llvm::GlobalValue::InternalLinkage,
1549 Init, Name,
1550 &CGM.getModule());
1551 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001552 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1553 UsedGlobals.push_back(GV);
1554 // FIXME: Why?
1555 GV->setAlignment(32);
1556
1557 return GV;
1558}
1559
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001560llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001561 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001562
1563 // FIXME: Should we look these up somewhere other than the
1564 // module. Its a bit silly since we only generate these while
1565 // processing an implementation, so exactly one pointer would work
1566 // if know when we entered/exitted an implementation block.
1567
1568 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001569 // Previously, metaclass with internal linkage may have been defined.
1570 // pass 'true' as 2nd argument so it is returned.
1571 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001572 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1573 "Forward metaclass reference has incorrect type.");
1574 return GV;
1575 } else {
1576 // Generate as an external reference to keep a consistent
1577 // module. This will be patched up when we emit the metaclass.
1578 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1579 llvm::GlobalValue::ExternalLinkage,
1580 0,
1581 Name,
1582 &CGM.getModule());
1583 }
1584}
1585
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001586/*
1587 struct objc_class_ext {
1588 uint32_t size;
1589 const char *weak_ivar_layout;
1590 struct _objc_property_list *properties;
1591 };
1592*/
1593llvm::Constant *
1594CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1595 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001596 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001597
1598 std::vector<llvm::Constant*> Values(3);
1599 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001600 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001601 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001602 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001603 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001604
1605 // Return null if no extension bits are used.
1606 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1607 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1608
1609 llvm::Constant *Init =
1610 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1611 llvm::GlobalVariable *GV =
1612 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1613 llvm::GlobalValue::InternalLinkage,
1614 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001615 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001616 &CGM.getModule());
1617 // No special section, but goes in llvm.used
1618 UsedGlobals.push_back(GV);
1619
1620 return GV;
1621}
1622
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001623/// countInheritedIvars - count number of ivars in class and its super class(s)
1624///
1625static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1626 int count = 0;
1627 if (!OI)
1628 return 0;
1629 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1630 if (SuperClass)
1631 count += countInheritedIvars(SuperClass);
1632 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1633 E = OI->ivar_end(); I != E; ++I)
1634 ++count;
1635 return count;
1636}
1637
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001638/// getInterfaceDeclForIvar - Get the interface declaration node where
1639/// this ivar is declared in.
1640/// FIXME. Ideally, this info should be in the ivar node. But currently
1641/// it is not and prevailing wisdom is that ASTs should not have more
1642/// info than is absolutely needed, even though this info reflects the
1643/// source language.
1644///
1645static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1646 const ObjCInterfaceDecl *OI,
1647 const ObjCIvarDecl *IVD) {
1648 if (!OI)
1649 return 0;
1650 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1651 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1652 E = OI->ivar_end(); I != E; ++I)
1653 if ((*I)->getIdentifier() == IVD->getIdentifier())
1654 return OI;
1655 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1656}
1657
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001658/*
1659 struct objc_ivar {
1660 char *ivar_name;
1661 char *ivar_type;
1662 int ivar_offset;
1663 };
1664
1665 struct objc_ivar_list {
1666 int ivar_count;
1667 struct objc_ivar list[count];
1668 };
1669 */
1670llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001671 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001672 std::vector<llvm::Constant*> Ivars, Ivar(3);
1673
1674 // When emitting the root class GCC emits ivar entries for the
1675 // actual class structure. It is not clear if we need to follow this
1676 // behavior; for now lets try and get away with not doing it. If so,
1677 // the cleanest solution would be to make up an ObjCInterfaceDecl
1678 // for the class.
1679 if (ForClass)
1680 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001681
1682 ObjCInterfaceDecl *OID =
1683 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1684 const llvm::Type *InterfaceTy =
1685 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001686 const llvm::StructLayout *Layout =
1687 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001688
1689 RecordDecl::field_iterator ifield, pfield;
1690 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001691 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1692 FieldDecl *Field = *ifield;
1693 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1694 getLLVMFieldNo(Field));
1695 if (Field->getIdentifier())
1696 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1697 else
1698 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001699 std::string TypeStr;
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001700 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001701 Ivar[1] = GetMethodVarType(TypeStr);
1702 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001703 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001704 }
1705
1706 // Return null for empty list.
1707 if (Ivars.empty())
1708 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1709
1710 std::vector<llvm::Constant*> Values(2);
1711 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1712 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1713 Ivars.size());
1714 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1715 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1716
1717 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1718 "\01L_OBJC_INSTANCE_VARIABLES_");
1719 llvm::GlobalVariable *GV =
1720 new llvm::GlobalVariable(Init->getType(), false,
1721 llvm::GlobalValue::InternalLinkage,
1722 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001723 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001724 &CGM.getModule());
1725 if (ForClass) {
1726 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1727 // FIXME: Why is this only here?
1728 GV->setAlignment(32);
1729 } else {
1730 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1731 }
1732 UsedGlobals.push_back(GV);
1733 return llvm::ConstantExpr::getBitCast(GV,
1734 ObjCTypes.IvarListPtrTy);
1735}
1736
1737/*
1738 struct objc_method {
1739 SEL method_name;
1740 char *method_types;
1741 void *method;
1742 };
1743
1744 struct objc_method_list {
1745 struct objc_method_list *obsolete;
1746 int count;
1747 struct objc_method methods_list[count];
1748 };
1749*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001750
1751/// GetMethodConstant - Return a struct objc_method constant for the
1752/// given method if it has been defined. The result is null if the
1753/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001754llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001755 // FIXME: Use DenseMap::lookup
1756 llvm::Function *Fn = MethodDefinitions[MD];
1757 if (!Fn)
1758 return 0;
1759
1760 std::vector<llvm::Constant*> Method(3);
1761 Method[0] =
1762 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1763 ObjCTypes.SelectorPtrTy);
1764 Method[1] = GetMethodVarType(MD);
1765 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1766 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1767}
1768
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001769llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1770 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001771 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001772 // Return null for empty list.
1773 if (Methods.empty())
1774 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1775
1776 std::vector<llvm::Constant*> Values(3);
1777 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1778 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1779 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1780 Methods.size());
1781 Values[2] = llvm::ConstantArray::get(AT, Methods);
1782 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1783
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001784 llvm::GlobalVariable *GV =
1785 new llvm::GlobalVariable(Init->getType(), false,
1786 llvm::GlobalValue::InternalLinkage,
1787 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001788 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001790 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001791 UsedGlobals.push_back(GV);
1792 return llvm::ConstantExpr::getBitCast(GV,
1793 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001794}
1795
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001796llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001797 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001798 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001799 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001800
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001801 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001802 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001803 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001804 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001805 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001806 llvm::GlobalValue::InternalLinkage,
1807 Name,
1808 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001809 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001810
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001811 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001812}
1813
1814llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001815 // Abuse this interface function as a place to finalize.
1816 FinishModule();
1817
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001818 return NULL;
1819}
1820
Daniel Dunbar49f66022008-09-24 03:38:44 +00001821llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1822 return ObjCTypes.GetPropertyFn;
1823}
1824
1825llvm::Function *CGObjCMac::GetPropertySetFunction() {
1826 return ObjCTypes.SetPropertyFn;
1827}
1828
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001829llvm::Function *CGObjCMac::EnumerationMutationFunction()
1830{
1831 return ObjCTypes.EnumerationMutationFn;
1832}
1833
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001834/*
1835
1836Objective-C setjmp-longjmp (sjlj) Exception Handling
1837--
1838
1839The basic framework for a @try-catch-finally is as follows:
1840{
1841 objc_exception_data d;
1842 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001843 bool _call_try_exit = true;
1844
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001845 objc_exception_try_enter(&d);
1846 if (!setjmp(d.jmp_buf)) {
1847 ... try body ...
1848 } else {
1849 // exception path
1850 id _caught = objc_exception_extract(&d);
1851
1852 // enter new try scope for handlers
1853 if (!setjmp(d.jmp_buf)) {
1854 ... match exception and execute catch blocks ...
1855
1856 // fell off end, rethrow.
1857 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001858 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001859 } else {
1860 // exception in catch block
1861 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001862 _call_try_exit = false;
1863 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001864 }
1865 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001866 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001867
1868finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001869 if (_call_try_exit)
1870 objc_exception_try_exit(&d);
1871
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001872 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001873 ... dispatch to finally destination ...
1874
1875finally_rethrow:
1876 objc_exception_throw(_rethrow);
1877
1878finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001879}
1880
1881This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001882uses _rethrow to determine if objc_exception_try_exit should be called
1883and if the object should be rethrown. This breaks in the face of
1884throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001885
1886We specialize this framework for a few particular circumstances:
1887
1888 - If there are no catch blocks, then we avoid emitting the second
1889 exception handling context.
1890
1891 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1892 e)) we avoid emitting the code to rethrow an uncaught exception.
1893
1894 - FIXME: If there is no @finally block we can do a few more
1895 simplifications.
1896
1897Rethrows and Jumps-Through-Finally
1898--
1899
1900Support for implicit rethrows and jumping through the finally block is
1901handled by storing the current exception-handling context in
1902ObjCEHStack.
1903
Daniel Dunbar898d5082008-09-30 01:06:03 +00001904In order to implement proper @finally semantics, we support one basic
1905mechanism for jumping through the finally block to an arbitrary
1906destination. Constructs which generate exits from a @try or @catch
1907block use this mechanism to implement the proper semantics by chaining
1908jumps, as necessary.
1909
1910This mechanism works like the one used for indirect goto: we
1911arbitrarily assign an ID to each destination and store the ID for the
1912destination in a variable prior to entering the finally block. At the
1913end of the finally block we simply create a switch to the proper
1914destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001915
1916Code gen for @synchronized(expr) stmt;
1917Effectively generating code for:
1918objc_sync_enter(expr);
1919@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001920*/
1921
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001922void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1923 const Stmt &S) {
1924 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001925 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001926 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001927 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001928 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1929 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1930 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001931
1932 // For @synchronized, call objc_sync_enter(sync.expr). The
1933 // evaluation of the expression must occur before we enter the
1934 // @synchronized. We can safely avoid a temp here because jumps into
1935 // @synchronized are illegal & this will dominate uses.
1936 llvm::Value *SyncArg = 0;
1937 if (!isTry) {
1938 SyncArg =
1939 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1940 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1941 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1942 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001943
1944 // Push an EH context entry, used for handling rethrows and jumps
1945 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001946 CGF.PushCleanupBlock(FinallyBlock);
1947
Anders Carlsson273558f2009-02-07 21:37:21 +00001948 CGF.ObjCEHValueStack.push_back(0);
1949
Daniel Dunbar898d5082008-09-30 01:06:03 +00001950 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001951 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1952 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001953 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1954 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001955 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1956 "_call_try_exit");
1957 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1958
Anders Carlsson80f25672008-09-09 17:59:25 +00001959 // Enter a new try block and call setjmp.
1960 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1961 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1962 "jmpbufarray");
1963 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1964 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1965 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001966
Daniel Dunbar55e87422008-11-11 02:29:29 +00001967 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1968 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001969 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001970 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001971
1972 // Emit the @try block.
1973 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001974 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1975 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001976 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001977
1978 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001979 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001980
1981 // Retrieve the exception object. We may emit multiple blocks but
1982 // nothing can cross this so the value is already in SSA form.
1983 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1984 ExceptionData,
1985 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00001986 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001987 if (!isTry)
1988 {
1989 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001990 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001991 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001992 }
1993 else if (const ObjCAtCatchStmt* CatchStmt =
1994 cast<ObjCAtTryStmt>(S).getCatchStmts())
1995 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001996 // Enter a new exception try block (in case a @catch block throws
1997 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001998 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001999
Anders Carlsson80f25672008-09-09 17:59:25 +00002000 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2001 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002002 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002003
Daniel Dunbar55e87422008-11-11 02:29:29 +00002004 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2005 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002006 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002007
2008 CGF.EmitBlock(CatchBlock);
2009
Daniel Dunbar55e40722008-09-27 07:03:52 +00002010 // Handle catch list. As a special case we check if everything is
2011 // matched and avoid generating code for falling off the end if
2012 // so.
2013 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002014 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002015 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002016
Steve Naroff7ba138a2009-03-03 19:52:17 +00002017 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002018 const PointerType *PT = 0;
2019
Anders Carlsson80f25672008-09-09 17:59:25 +00002020 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002021 if (!CatchParam) {
2022 AllMatched = true;
2023 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002024 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002025
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002026 // catch(id e) always matches.
2027 // FIXME: For the time being we also match id<X>; this should
2028 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002029 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002030 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002031 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002032 }
2033
Daniel Dunbar55e40722008-09-27 07:03:52 +00002034 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002035 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002036 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002037 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002038 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002039 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002040
Anders Carlssondde0a942008-09-11 09:15:33 +00002041 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002042 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002043 break;
2044 }
2045
Daniel Dunbar129271a2008-09-27 07:36:24 +00002046 assert(PT && "Unexpected non-pointer type in @catch");
2047 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002048 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002049 assert(ObjCType && "Catch parameter must have Objective-C type!");
2050
2051 // Check if the @catch block matches the exception object.
2052 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2053
Anders Carlsson80f25672008-09-09 17:59:25 +00002054 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2055 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002056
Daniel Dunbar55e87422008-11-11 02:29:29 +00002057 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002058
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002059 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002060 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002061
2062 // Emit the @catch block.
2063 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002064 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002065 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002066
2067 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002068 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002069 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002070 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002071
2072 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002073 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002074
2075 CGF.EmitBlock(NextCatchBlock);
2076 }
2077
Daniel Dunbar55e40722008-09-27 07:03:52 +00002078 if (!AllMatched) {
2079 // None of the handlers caught the exception, so store it to be
2080 // rethrown at the end of the @finally block.
2081 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002082 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002083 }
2084
2085 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002086 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002087 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2088 ExceptionData),
2089 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002090 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002091 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002092 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002093 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002094 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002095 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002096 }
2097
Daniel Dunbar898d5082008-09-30 01:06:03 +00002098 // Pop the exception-handling stack entry. It is important to do
2099 // this now, because the code in the @finally block is not in this
2100 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002101 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2102
Anders Carlsson273558f2009-02-07 21:37:21 +00002103 CGF.ObjCEHValueStack.pop_back();
2104
Anders Carlsson80f25672008-09-09 17:59:25 +00002105 // Emit the @finally block.
2106 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002107 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2108
2109 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2110
2111 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002112 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002113
2114 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002115 if (isTry) {
2116 if (const ObjCAtFinallyStmt* FinallyStmt =
2117 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2118 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002119 } else {
2120 // Emit objc_sync_exit(expr); as finally's sole statement for
2121 // @synchronized.
2122 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002123 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002124
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002125 // Emit the switch block
2126 if (Info.SwitchBlock)
2127 CGF.EmitBlock(Info.SwitchBlock);
2128 if (Info.EndBlock)
2129 CGF.EmitBlock(Info.EndBlock);
2130
Daniel Dunbar898d5082008-09-30 01:06:03 +00002131 CGF.EmitBlock(FinallyRethrow);
2132 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2133 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002134 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002135
2136 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002137}
2138
2139void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002140 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002141 llvm::Value *ExceptionAsObject;
2142
2143 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2144 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2145 ExceptionAsObject =
2146 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2147 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002148 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002149 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002150 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002151 }
2152
2153 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002154 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002155
2156 // Clear the insertion point to indicate we are in unreachable code.
2157 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002158}
2159
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002160/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002161/// object: objc_read_weak (id *src)
2162///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002163llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002164 llvm::Value *AddrWeakObj)
2165{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002166 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002167 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002168 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002169 return read_weak;
2170}
2171
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002172/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2173/// objc_assign_weak (id src, id *dst)
2174///
2175void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2176 llvm::Value *src, llvm::Value *dst)
2177{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002178 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2179 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002180 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2181 src, dst, "weakassign");
2182 return;
2183}
2184
Fariborz Jahanian58626502008-11-19 00:59:10 +00002185/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2186/// objc_assign_global (id src, id *dst)
2187///
2188void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2189 llvm::Value *src, llvm::Value *dst)
2190{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002191 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2192 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002193 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2194 src, dst, "globalassign");
2195 return;
2196}
2197
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002198/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2199/// objc_assign_ivar (id src, id *dst)
2200///
2201void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2202 llvm::Value *src, llvm::Value *dst)
2203{
2204 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2205 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2206 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2207 src, dst, "assignivar");
2208 return;
2209}
2210
Fariborz Jahanian58626502008-11-19 00:59:10 +00002211/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2212/// objc_assign_strongCast (id src, id *dst)
2213///
2214void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2215 llvm::Value *src, llvm::Value *dst)
2216{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002217 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2218 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002219 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2220 src, dst, "weakassign");
2221 return;
2222}
2223
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002224/// EmitObjCValueForIvar - Code Gen for ivar reference.
2225///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002226LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2227 QualType ObjectTy,
2228 llvm::Value *BaseValue,
2229 const ObjCIvarDecl *Ivar,
2230 const FieldDecl *Field,
2231 unsigned CVRQualifiers) {
2232 if (Ivar->isBitField())
2233 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2234 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002235 // TODO: Add a special case for isa (index 0)
2236 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2237 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002238 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002239 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2240 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002241 LValue::SetObjCIvar(LV, true);
2242 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002243}
2244
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002245llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2246 ObjCInterfaceDecl *Interface,
2247 const ObjCIvarDecl *Ivar) {
2248 const llvm::Type *InterfaceLTy =
2249 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2250 const llvm::StructLayout *Layout =
2251 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2252 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2253 uint64_t Offset =
2254 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2255
2256 return llvm::ConstantInt::get(
2257 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2258 Offset);
2259}
2260
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002261/* *** Private Interface *** */
2262
2263/// EmitImageInfo - Emit the image info marker used to encode some module
2264/// level information.
2265///
2266/// See: <rdr://4810609&4810587&4810587>
2267/// struct IMAGE_INFO {
2268/// unsigned version;
2269/// unsigned flags;
2270/// };
2271enum ImageInfoFlags {
2272 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2273 eImageInfo_GarbageCollected = (1 << 1),
2274 eImageInfo_GCOnly = (1 << 2)
2275};
2276
2277void CGObjCMac::EmitImageInfo() {
2278 unsigned version = 0; // Version is unused?
2279 unsigned flags = 0;
2280
2281 // FIXME: Fix and continue?
2282 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2283 flags |= eImageInfo_GarbageCollected;
2284 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2285 flags |= eImageInfo_GCOnly;
2286
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002287 // Emitted as int[2];
2288 llvm::Constant *values[2] = {
2289 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2290 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2291 };
2292 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002293 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002294 new llvm::GlobalVariable(AT, true,
2295 llvm::GlobalValue::InternalLinkage,
2296 llvm::ConstantArray::get(AT, values, 2),
2297 "\01L_OBJC_IMAGE_INFO",
2298 &CGM.getModule());
2299
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002300 if (ObjCABI == 1) {
2301 GV->setSection("__OBJC, __image_info,regular");
2302 } else {
2303 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2304 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002305
2306 UsedGlobals.push_back(GV);
2307}
2308
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002309
2310// struct objc_module {
2311// unsigned long version;
2312// unsigned long size;
2313// const char *name;
2314// Symtab symtab;
2315// };
2316
2317// FIXME: Get from somewhere
2318static const int ModuleVersion = 7;
2319
2320void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002321 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002322
2323 std::vector<llvm::Constant*> Values(4);
2324 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2325 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002326 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002327 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002328 Values[3] = EmitModuleSymbols();
2329
2330 llvm::GlobalVariable *GV =
2331 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2332 llvm::GlobalValue::InternalLinkage,
2333 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2334 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002335 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002336 &CGM.getModule());
2337 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2338 UsedGlobals.push_back(GV);
2339}
2340
2341llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002342 unsigned NumClasses = DefinedClasses.size();
2343 unsigned NumCategories = DefinedCategories.size();
2344
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002345 // Return null if no symbols were defined.
2346 if (!NumClasses && !NumCategories)
2347 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2348
2349 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002350 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2351 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2352 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2353 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2354
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002355 // The runtime expects exactly the list of defined classes followed
2356 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002357 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002358 for (unsigned i=0; i<NumClasses; i++)
2359 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2360 ObjCTypes.Int8PtrTy);
2361 for (unsigned i=0; i<NumCategories; i++)
2362 Symbols[NumClasses + i] =
2363 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2364 ObjCTypes.Int8PtrTy);
2365
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002366 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002367 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002368 NumClasses + NumCategories),
2369 Symbols);
2370
2371 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2372
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002373 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002374 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002375 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002376 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002377 "\01L_OBJC_SYMBOLS",
2378 &CGM.getModule());
2379 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2380 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002381 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2382}
2383
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002384llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002385 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002386 LazySymbols.insert(ID->getIdentifier());
2387
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002388 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2389
2390 if (!Entry) {
2391 llvm::Constant *Casted =
2392 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2393 ObjCTypes.ClassPtrTy);
2394 Entry =
2395 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2396 llvm::GlobalValue::InternalLinkage,
2397 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2398 &CGM.getModule());
2399 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2400 UsedGlobals.push_back(Entry);
2401 }
2402
2403 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002404}
2405
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002406llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002407 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2408
2409 if (!Entry) {
2410 llvm::Constant *Casted =
2411 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2412 ObjCTypes.SelectorPtrTy);
2413 Entry =
2414 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2415 llvm::GlobalValue::InternalLinkage,
2416 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2417 &CGM.getModule());
2418 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2419 UsedGlobals.push_back(Entry);
2420 }
2421
2422 return Builder.CreateLoad(Entry, false, "tmp");
2423}
2424
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002425llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002426 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002427
2428 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002429 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002431 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002432 llvm::GlobalValue::InternalLinkage,
2433 C, "\01L_OBJC_CLASS_NAME_",
2434 &CGM.getModule());
2435 Entry->setSection("__TEXT,__cstring,cstring_literals");
2436 UsedGlobals.push_back(Entry);
2437 }
2438
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002439 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002440}
2441
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002442llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002443 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2444
2445 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002446 // FIXME: Avoid std::string copying.
2447 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002448 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002449 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002450 llvm::GlobalValue::InternalLinkage,
2451 C, "\01L_OBJC_METH_VAR_NAME_",
2452 &CGM.getModule());
2453 Entry->setSection("__TEXT,__cstring,cstring_literals");
2454 UsedGlobals.push_back(Entry);
2455 }
2456
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002457 return getConstantGEP(Entry, 0, 0);
2458}
2459
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002460// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002461llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002462 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2463}
2464
2465// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002466llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002467 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2468}
2469
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002470llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002471 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002472
2473 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002474 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002475 Entry =
2476 new llvm::GlobalVariable(C->getType(), false,
2477 llvm::GlobalValue::InternalLinkage,
2478 C, "\01L_OBJC_METH_VAR_TYPE_",
2479 &CGM.getModule());
2480 Entry->setSection("__TEXT,__cstring,cstring_literals");
2481 UsedGlobals.push_back(Entry);
2482 }
2483
2484 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002485}
2486
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002487// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002488llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002489 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002490 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2491 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002492 return GetMethodVarType(TypeStr);
2493}
2494
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002495// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002496llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002497 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2498
2499 if (!Entry) {
2500 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2501 Entry =
2502 new llvm::GlobalVariable(C->getType(), false,
2503 llvm::GlobalValue::InternalLinkage,
2504 C, "\01L_OBJC_PROP_NAME_ATTR_",
2505 &CGM.getModule());
2506 Entry->setSection("__TEXT,__cstring,cstring_literals");
2507 UsedGlobals.push_back(Entry);
2508 }
2509
2510 return getConstantGEP(Entry, 0, 0);
2511}
2512
2513// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002514// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002515llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002516 const Decl *Container) {
2517 std::string TypeStr;
2518 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002519 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2520}
2521
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002522void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2523 const ObjCContainerDecl *CD,
2524 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002525 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002526 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002527 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002528 assert (CD && "Missing container decl in GetNameForMethod");
2529 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002530 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2531 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002532 NameOut += ' ';
2533 NameOut += D->getSelector().getAsString();
2534 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002535}
2536
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002537/// GetFirstIvarInRecord - This routine returns the record for the
2538/// implementation of the fiven class OID. It also returns field
2539/// corresponding to the first ivar in the class in FIV. It also
2540/// returns the one before the first ivar.
2541///
2542const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2543 const ObjCInterfaceDecl *OID,
2544 RecordDecl::field_iterator &FIV,
2545 RecordDecl::field_iterator &PIV) {
2546 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2547 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2548 RecordDecl::field_iterator ifield = RD->field_begin();
2549 RecordDecl::field_iterator pfield = RD->field_end();
2550 while (countSuperClassIvars-- > 0) {
2551 pfield = ifield;
2552 ++ifield;
2553 }
2554 FIV = ifield;
2555 PIV = pfield;
2556 return RD;
2557}
2558
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002559void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002560 EmitModuleInfo();
2561
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002562 // Emit the dummy bodies for any protocols which were referenced but
2563 // never defined.
2564 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2565 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2566 if (i->second->hasInitializer())
2567 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002568
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002569 std::vector<llvm::Constant*> Values(5);
2570 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2571 Values[1] = GetClassName(i->first);
2572 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2573 Values[3] = Values[4] =
2574 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2575 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2576 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2577 Values));
2578 }
2579
2580 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002581 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002582 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002583 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002584 }
2585
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002586 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002587 llvm::GlobalValue *GV =
2588 new llvm::GlobalVariable(AT, false,
2589 llvm::GlobalValue::AppendingLinkage,
2590 llvm::ConstantArray::get(AT, Used),
2591 "llvm.used",
2592 &CGM.getModule());
2593
2594 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002595
2596 // Add assembler directives to add lazy undefined symbol references
2597 // for classes which are referenced but not defined. This is
2598 // important for correct linker interaction.
2599
2600 // FIXME: Uh, this isn't particularly portable.
2601 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002602
2603 if (!CGM.getModule().getModuleInlineAsm().empty())
2604 s << "\n";
2605
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002606 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2607 e = LazySymbols.end(); i != e; ++i) {
2608 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2609 }
2610 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2611 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002612 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002613 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2614 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002615
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002616 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002617}
2618
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002619CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002620 : CGObjCCommonMac(cgm),
2621 ObjCTypes(cgm)
2622{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002623 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002624 ObjCABI = 2;
2625}
2626
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002627/* *** */
2628
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002629ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2630: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002631{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002632 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2633 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002634
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002635 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002636 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002637 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002638 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2639
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002640 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002641 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002642 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002643
2644 // FIXME: It would be nice to unify this with the opaque type, so
2645 // that the IR comes out a bit cleaner.
2646 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2647 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002648
2649 // I'm not sure I like this. The implicit coordination is a bit
2650 // gross. We should solve this in a reasonable fashion because this
2651 // is a pretty common task (match some runtime data structure with
2652 // an LLVM data structure).
2653
2654 // FIXME: This is leaked.
2655 // FIXME: Merge with rewriter code?
2656
2657 // struct _objc_super {
2658 // id self;
2659 // Class cls;
2660 // }
2661 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2662 SourceLocation(),
2663 &Ctx.Idents.get("_objc_super"));
2664 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2665 Ctx.getObjCIdType(), 0, false));
2666 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2667 Ctx.getObjCClassType(), 0, false));
2668 RD->completeDefinition(Ctx);
2669
2670 SuperCTy = Ctx.getTagDeclType(RD);
2671 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2672
2673 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002674 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2675
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002676 // struct _prop_t {
2677 // char *name;
2678 // char *attributes;
2679 // }
2680 PropertyTy = llvm::StructType::get(Int8PtrTy,
2681 Int8PtrTy,
2682 NULL);
2683 CGM.getModule().addTypeName("struct._prop_t",
2684 PropertyTy);
2685
2686 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002687 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002688 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002689 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002690 // }
2691 PropertyListTy = llvm::StructType::get(IntTy,
2692 IntTy,
2693 llvm::ArrayType::get(PropertyTy, 0),
2694 NULL);
2695 CGM.getModule().addTypeName("struct._prop_list_t",
2696 PropertyListTy);
2697 // struct _prop_list_t *
2698 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2699
2700 // struct _objc_method {
2701 // SEL _cmd;
2702 // char *method_type;
2703 // char *_imp;
2704 // }
2705 MethodTy = llvm::StructType::get(SelectorPtrTy,
2706 Int8PtrTy,
2707 Int8PtrTy,
2708 NULL);
2709 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002710
2711 // struct _objc_cache *
2712 CacheTy = llvm::OpaqueType::get();
2713 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2714 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002715
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002716 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002717
2718 QualType IdType = Ctx.getObjCIdType();
2719 QualType SelType = Ctx.getObjCSelType();
2720 llvm::SmallVector<QualType,16> Params;
2721 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002722
2723 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002724 Params.push_back(IdType);
2725 Params.push_back(SelType);
2726 Params.push_back(Ctx.LongTy);
2727 Params.push_back(Ctx.BoolTy);
2728 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2729 false);
2730 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002731
2732 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2733 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002734 Params.push_back(IdType);
2735 Params.push_back(SelType);
2736 Params.push_back(Ctx.LongTy);
2737 Params.push_back(IdType);
2738 Params.push_back(Ctx.BoolTy);
2739 Params.push_back(Ctx.BoolTy);
2740 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2741 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2742
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002743 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002744
2745 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002746 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002747 Params.push_back(IdType);
2748 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2749 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2750 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002751
2752 // gc's API
2753 // id objc_read_weak (id *)
2754 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002755 Params.push_back(Ctx.getPointerType(IdType));
2756 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2757 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2758
2759 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002760 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002761 Params.push_back(IdType);
2762 Params.push_back(Ctx.getPointerType(IdType));
2763
2764 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2765 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2766 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2767 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2768 GcAssignStrongCastFn =
2769 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002770
2771 // void objc_exception_throw(id)
2772 Params.clear();
2773 Params.push_back(IdType);
2774
2775 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002776 ExceptionThrowFn =
2777 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002778
2779 // synchronized APIs
2780 // void objc_sync_enter (id)
2781 // void objc_sync_exit (id)
2782 Params.clear();
2783 Params.push_back(IdType);
2784
2785 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2786 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2787 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002788}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002789
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002790ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2791 : ObjCCommonTypesHelper(cgm)
2792{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002793 // struct _objc_method_description {
2794 // SEL name;
2795 // char *types;
2796 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002797 MethodDescriptionTy =
2798 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002799 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002800 NULL);
2801 CGM.getModule().addTypeName("struct._objc_method_description",
2802 MethodDescriptionTy);
2803
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002804 // struct _objc_method_description_list {
2805 // int count;
2806 // struct _objc_method_description[1];
2807 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002808 MethodDescriptionListTy =
2809 llvm::StructType::get(IntTy,
2810 llvm::ArrayType::get(MethodDescriptionTy, 0),
2811 NULL);
2812 CGM.getModule().addTypeName("struct._objc_method_description_list",
2813 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002814
2815 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002816 MethodDescriptionListPtrTy =
2817 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2818
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002819 // Protocol description structures
2820
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002821 // struct _objc_protocol_extension {
2822 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2823 // struct _objc_method_description_list *optional_instance_methods;
2824 // struct _objc_method_description_list *optional_class_methods;
2825 // struct _objc_property_list *instance_properties;
2826 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002827 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002828 llvm::StructType::get(IntTy,
2829 MethodDescriptionListPtrTy,
2830 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002831 PropertyListPtrTy,
2832 NULL);
2833 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2834 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002835
2836 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002837 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2838
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002839 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002840
2841 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2842 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2843
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002844 const llvm::Type *T =
2845 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2846 LongTy,
2847 llvm::ArrayType::get(ProtocolTyHolder, 0),
2848 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002849 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2850
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002851 // struct _objc_protocol {
2852 // struct _objc_protocol_extension *isa;
2853 // char *protocol_name;
2854 // struct _objc_protocol **_objc_protocol_list;
2855 // struct _objc_method_description_list *instance_methods;
2856 // struct _objc_method_description_list *class_methods;
2857 // }
2858 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002859 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002860 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2861 MethodDescriptionListPtrTy,
2862 MethodDescriptionListPtrTy,
2863 NULL);
2864 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2865
2866 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2867 CGM.getModule().addTypeName("struct._objc_protocol_list",
2868 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002869 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002870 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2871
2872 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002873 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002874 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002875
2876 // Class description structures
2877
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002878 // struct _objc_ivar {
2879 // char *ivar_name;
2880 // char *ivar_type;
2881 // int ivar_offset;
2882 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002883 IvarTy = llvm::StructType::get(Int8PtrTy,
2884 Int8PtrTy,
2885 IntTy,
2886 NULL);
2887 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2888
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002889 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002890 IvarListTy = llvm::OpaqueType::get();
2891 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2892 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2893
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002894 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002895 MethodListTy = llvm::OpaqueType::get();
2896 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2897 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2898
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002899 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002900 ClassExtensionTy =
2901 llvm::StructType::get(IntTy,
2902 Int8PtrTy,
2903 PropertyListPtrTy,
2904 NULL);
2905 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2906 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2907
2908 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2909
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002910 // struct _objc_class {
2911 // Class isa;
2912 // Class super_class;
2913 // char *name;
2914 // long version;
2915 // long info;
2916 // long instance_size;
2917 // struct _objc_ivar_list *ivars;
2918 // struct _objc_method_list *methods;
2919 // struct _objc_cache *cache;
2920 // struct _objc_protocol_list *protocols;
2921 // char *ivar_layout;
2922 // struct _objc_class_ext *ext;
2923 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002924 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2925 llvm::PointerType::getUnqual(ClassTyHolder),
2926 Int8PtrTy,
2927 LongTy,
2928 LongTy,
2929 LongTy,
2930 IvarListPtrTy,
2931 MethodListPtrTy,
2932 CachePtrTy,
2933 ProtocolListPtrTy,
2934 Int8PtrTy,
2935 ClassExtensionPtrTy,
2936 NULL);
2937 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2938
2939 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2940 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2941 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2942
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002943 // struct _objc_category {
2944 // char *category_name;
2945 // char *class_name;
2946 // struct _objc_method_list *instance_method;
2947 // struct _objc_method_list *class_method;
2948 // uint32_t size; // sizeof(struct _objc_category)
2949 // struct _objc_property_list *instance_properties;// category's @property
2950 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002951 CategoryTy = llvm::StructType::get(Int8PtrTy,
2952 Int8PtrTy,
2953 MethodListPtrTy,
2954 MethodListPtrTy,
2955 ProtocolListPtrTy,
2956 IntTy,
2957 PropertyListPtrTy,
2958 NULL);
2959 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2960
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002961 // Global metadata structures
2962
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002963 // struct _objc_symtab {
2964 // long sel_ref_cnt;
2965 // SEL *refs;
2966 // short cls_def_cnt;
2967 // short cat_def_cnt;
2968 // char *defs[cls_def_cnt + cat_def_cnt];
2969 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002970 SymtabTy = llvm::StructType::get(LongTy,
2971 SelectorPtrTy,
2972 ShortTy,
2973 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002974 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002975 NULL);
2976 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2977 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2978
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002979 // struct _objc_module {
2980 // long version;
2981 // long size; // sizeof(struct _objc_module)
2982 // char *name;
2983 // struct _objc_symtab* symtab;
2984 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002985 ModuleTy =
2986 llvm::StructType::get(LongTy,
2987 LongTy,
2988 Int8PtrTy,
2989 SymtabPtrTy,
2990 NULL);
2991 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002992
Daniel Dunbar49f66022008-09-24 03:38:44 +00002993 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002994
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002995 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002996 std::vector<const llvm::Type*> Params;
2997 Params.push_back(ObjectPtrTy);
2998 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002999 MessageSendFn =
3000 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3001 Params,
3002 true),
3003 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003004
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003005 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003006 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003007 Params.push_back(ObjectPtrTy);
3008 Params.push_back(SelectorPtrTy);
3009 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003010 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3011 Params,
3012 true),
3013 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003014
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003015 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003016 Params.clear();
3017 Params.push_back(ObjectPtrTy);
3018 Params.push_back(SelectorPtrTy);
3019 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003020 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003021 MessageSendFpretFn =
3022 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3023 Params,
3024 true),
3025 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003026
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003027 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003028 Params.clear();
3029 Params.push_back(SuperPtrTy);
3030 Params.push_back(SelectorPtrTy);
3031 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003032 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3033 Params,
3034 true),
3035 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003036
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003037 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3038 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003039 Params.clear();
3040 Params.push_back(Int8PtrTy);
3041 Params.push_back(SuperPtrTy);
3042 Params.push_back(SelectorPtrTy);
3043 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003044 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3045 Params,
3046 true),
3047 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003048
3049 // There is no objc_msgSendSuper_fpret? How can that work?
3050 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003051
Anders Carlsson124526b2008-09-09 10:10:21 +00003052 // FIXME: This is the size of the setjmp buffer and should be
3053 // target specific. 18 is what's used on 32-bit X86.
3054 uint64_t SetJmpBufferSize = 18;
3055
3056 // Exceptions
3057 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003058 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003059
3060 ExceptionDataTy =
3061 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3062 SetJmpBufferSize),
3063 StackPtrTy, NULL);
3064 CGM.getModule().addTypeName("struct._objc_exception_data",
3065 ExceptionDataTy);
3066
3067 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003068 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3069 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003070 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3071 Params,
3072 false),
3073 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003074 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003075 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3076 Params,
3077 false),
3078 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003079 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003080 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3081 Params,
3082 false),
3083 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003084
3085 Params.clear();
3086 Params.push_back(ClassPtrTy);
3087 Params.push_back(ObjectPtrTy);
3088 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003089 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3090 Params,
3091 false),
3092 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003093
Anders Carlsson124526b2008-09-09 10:10:21 +00003094 Params.clear();
3095 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3096 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003097 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3098 Params,
3099 false),
3100 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003101
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003102}
3103
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003104ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003105: ObjCCommonTypesHelper(cgm)
3106{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003107 // struct _method_list_t {
3108 // uint32_t entsize; // sizeof(struct _objc_method)
3109 // uint32_t method_count;
3110 // struct _objc_method method_list[method_count];
3111 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003112 MethodListnfABITy = llvm::StructType::get(IntTy,
3113 IntTy,
3114 llvm::ArrayType::get(MethodTy, 0),
3115 NULL);
3116 CGM.getModule().addTypeName("struct.__method_list_t",
3117 MethodListnfABITy);
3118 // struct method_list_t *
3119 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003120
3121 // struct _protocol_t {
3122 // id isa; // NULL
3123 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003124 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003125 // const struct method_list_t * const instance_methods;
3126 // const struct method_list_t * const class_methods;
3127 // const struct method_list_t *optionalInstanceMethods;
3128 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003129 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003130 // const uint32_t size; // sizeof(struct _protocol_t)
3131 // const uint32_t flags; // = 0
3132 // }
3133
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003134 // Holder for struct _protocol_list_t *
3135 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3136
3137 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3138 Int8PtrTy,
3139 llvm::PointerType::getUnqual(
3140 ProtocolListTyHolder),
3141 MethodListnfABIPtrTy,
3142 MethodListnfABIPtrTy,
3143 MethodListnfABIPtrTy,
3144 MethodListnfABIPtrTy,
3145 PropertyListPtrTy,
3146 IntTy,
3147 IntTy,
3148 NULL);
3149 CGM.getModule().addTypeName("struct._protocol_t",
3150 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003151
3152 // struct _protocol_t*
3153 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003154
Fariborz Jahanianda320092009-01-29 19:24:30 +00003155 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003156 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003157 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003158 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003159 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3160 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003161 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003162 NULL);
3163 CGM.getModule().addTypeName("struct._objc_protocol_list",
3164 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003165 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3166 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003167
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003168 // struct _objc_protocol_list*
3169 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003170
3171 // struct _ivar_t {
3172 // unsigned long int *offset; // pointer to ivar offset location
3173 // char *name;
3174 // char *type;
3175 // uint32_t alignment;
3176 // uint32_t size;
3177 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003178 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3179 Int8PtrTy,
3180 Int8PtrTy,
3181 IntTy,
3182 IntTy,
3183 NULL);
3184 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3185
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003186 // struct _ivar_list_t {
3187 // uint32 entsize; // sizeof(struct _ivar_t)
3188 // uint32 count;
3189 // struct _iver_t list[count];
3190 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003191 IvarListnfABITy = llvm::StructType::get(IntTy,
3192 IntTy,
3193 llvm::ArrayType::get(
3194 IvarnfABITy, 0),
3195 NULL);
3196 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3197
3198 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003199
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003200 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003201 // uint32_t const flags;
3202 // uint32_t const instanceStart;
3203 // uint32_t const instanceSize;
3204 // uint32_t const reserved; // only when building for 64bit targets
3205 // const uint8_t * const ivarLayout;
3206 // const char *const name;
3207 // const struct _method_list_t * const baseMethods;
3208 // const struct _objc_protocol_list *const baseProtocols;
3209 // const struct _ivar_list_t *const ivars;
3210 // const uint8_t * const weakIvarLayout;
3211 // const struct _prop_list_t * const properties;
3212 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003213
3214 // FIXME. Add 'reserved' field in 64bit abi mode!
3215 ClassRonfABITy = llvm::StructType::get(IntTy,
3216 IntTy,
3217 IntTy,
3218 Int8PtrTy,
3219 Int8PtrTy,
3220 MethodListnfABIPtrTy,
3221 ProtocolListnfABIPtrTy,
3222 IvarListnfABIPtrTy,
3223 Int8PtrTy,
3224 PropertyListPtrTy,
3225 NULL);
3226 CGM.getModule().addTypeName("struct._class_ro_t",
3227 ClassRonfABITy);
3228
3229 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3230 std::vector<const llvm::Type*> Params;
3231 Params.push_back(ObjectPtrTy);
3232 Params.push_back(SelectorPtrTy);
3233 ImpnfABITy = llvm::PointerType::getUnqual(
3234 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3235
3236 // struct _class_t {
3237 // struct _class_t *isa;
3238 // struct _class_t * const superclass;
3239 // void *cache;
3240 // IMP *vtable;
3241 // struct class_ro_t *ro;
3242 // }
3243
3244 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3245 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3246 llvm::PointerType::getUnqual(ClassTyHolder),
3247 CachePtrTy,
3248 llvm::PointerType::getUnqual(ImpnfABITy),
3249 llvm::PointerType::getUnqual(
3250 ClassRonfABITy),
3251 NULL);
3252 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3253
3254 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3255 ClassnfABITy);
3256
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003257 // LLVM for struct _class_t *
3258 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3259
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003260 // struct _category_t {
3261 // const char * const name;
3262 // struct _class_t *const cls;
3263 // const struct _method_list_t * const instance_methods;
3264 // const struct _method_list_t * const class_methods;
3265 // const struct _protocol_list_t * const protocols;
3266 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003267 // }
3268 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003269 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003270 MethodListnfABIPtrTy,
3271 MethodListnfABIPtrTy,
3272 ProtocolListnfABIPtrTy,
3273 PropertyListPtrTy,
3274 NULL);
3275 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003276
3277 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003278 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3279 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003280
3281 // MessageRefTy - LLVM for:
3282 // struct _message_ref_t {
3283 // IMP messenger;
3284 // SEL name;
3285 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003286
3287 // First the clang type for struct _message_ref_t
3288 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3289 SourceLocation(),
3290 &Ctx.Idents.get("_message_ref_t"));
3291 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3292 Ctx.VoidPtrTy, 0, false));
3293 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3294 Ctx.getObjCSelType(), 0, false));
3295 RD->completeDefinition(Ctx);
3296
3297 MessageRefCTy = Ctx.getTagDeclType(RD);
3298 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3299 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003300
3301 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3302 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3303
3304 // SuperMessageRefTy - LLVM for:
3305 // struct _super_message_ref_t {
3306 // SUPER_IMP messenger;
3307 // SEL name;
3308 // };
3309 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3310 SelectorPtrTy,
3311 NULL);
3312 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3313
3314 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3315 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3316
3317 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3318 Params.clear();
3319 Params.push_back(ObjectPtrTy);
3320 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003321 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3322 Params,
3323 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003324 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003325 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003326 "objc_msgSend_fixup");
3327
3328 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3329 MessageSendFpretFixupFn =
3330 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3331 Params,
3332 true),
3333 "objc_msgSend_fpret_fixup");
3334
3335 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3336 MessageSendStretFixupFn =
3337 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3338 Params,
3339 true),
3340 "objc_msgSend_stret_fixup");
3341
3342 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3343 MessageSendIdFixupFn =
3344 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3345 Params,
3346 true),
3347 "objc_msgSendId_fixup");
3348
3349
3350 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3351 MessageSendIdStretFixupFn =
3352 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3353 Params,
3354 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003355 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003356
3357 // id objc_msgSendSuper2_fixup (struct objc_super *,
3358 // struct _super_message_ref_t*, ...)
3359 Params.clear();
3360 Params.push_back(SuperPtrTy);
3361 Params.push_back(SuperMessageRefPtrTy);
3362 MessageSendSuper2FixupFn =
3363 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3364 Params,
3365 true),
3366 "objc_msgSendSuper2_fixup");
3367
3368
3369 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3370 // struct _super_message_ref_t*, ...)
3371 MessageSendSuper2StretFixupFn =
3372 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3373 Params,
3374 true),
3375 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003376
3377 Params.clear();
3378 llvm::Constant *Personality =
3379 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3380 Params,
3381 true),
3382 "__objc_personality_v0");
3383 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3384
3385 Params.clear();
3386 Params.push_back(Int8PtrTy);
3387 UnwindResumeOrRethrowFn =
3388 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3389 Params,
3390 false),
3391 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003392 ObjCBeginCatchFn =
3393 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3394 Params,
3395 false),
3396 "objc_begin_catch");
3397
3398 Params.clear();
3399 ObjCEndCatchFn =
3400 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3401 Params,
3402 false),
3403 "objc_end_catch");
3404
3405 // struct objc_typeinfo {
3406 // const void** vtable; // objc_ehtype_vtable + 2
3407 // const char* name; // c++ typeinfo string
3408 // Class cls;
3409 // };
3410 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3411 Int8PtrTy,
3412 ClassnfABIPtrTy,
3413 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003414 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003415 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003416}
3417
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003418llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3419 FinishNonFragileABIModule();
3420
3421 return NULL;
3422}
3423
3424void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3425 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003426
3427 // Build list of all implemented classe addresses in array
3428 // L_OBJC_LABEL_CLASS_$.
3429 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3430 // list of 'nonlazy' implementations (defined as those with a +load{}
3431 // method!!).
3432 unsigned NumClasses = DefinedClasses.size();
3433 if (NumClasses) {
3434 std::vector<llvm::Constant*> Symbols(NumClasses);
3435 for (unsigned i=0; i<NumClasses; i++)
3436 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3437 ObjCTypes.Int8PtrTy);
3438 llvm::Constant* Init =
3439 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3440 NumClasses),
3441 Symbols);
3442
3443 llvm::GlobalVariable *GV =
3444 new llvm::GlobalVariable(Init->getType(), false,
3445 llvm::GlobalValue::InternalLinkage,
3446 Init,
3447 "\01L_OBJC_LABEL_CLASS_$",
3448 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003449 GV->setAlignment(
3450 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003451 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3452 UsedGlobals.push_back(GV);
3453 }
3454
3455 // Build list of all implemented category addresses in array
3456 // L_OBJC_LABEL_CATEGORY_$.
3457 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3458 // list of 'nonlazy' category implementations (defined as those with a +load{}
3459 // method!!).
3460 unsigned NumCategory = DefinedCategories.size();
3461 if (NumCategory) {
3462 std::vector<llvm::Constant*> Symbols(NumCategory);
3463 for (unsigned i=0; i<NumCategory; i++)
3464 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3465 ObjCTypes.Int8PtrTy);
3466 llvm::Constant* Init =
3467 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3468 NumCategory),
3469 Symbols);
3470
3471 llvm::GlobalVariable *GV =
3472 new llvm::GlobalVariable(Init->getType(), false,
3473 llvm::GlobalValue::InternalLinkage,
3474 Init,
3475 "\01L_OBJC_LABEL_CATEGORY_$",
3476 &CGM.getModule());
3477 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3478 UsedGlobals.push_back(GV);
3479 }
3480
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003481 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3482 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3483 std::vector<llvm::Constant*> Values(2);
3484 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003485 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003486 // FIXME: Fix and continue?
3487 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3488 flags |= eImageInfo_GarbageCollected;
3489 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3490 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003491 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003492 llvm::Constant* Init = llvm::ConstantArray::get(
3493 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3494 Values);
3495 llvm::GlobalVariable *IMGV =
3496 new llvm::GlobalVariable(Init->getType(), false,
3497 llvm::GlobalValue::InternalLinkage,
3498 Init,
3499 "\01L_OBJC_IMAGE_INFO",
3500 &CGM.getModule());
3501 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3502 UsedGlobals.push_back(IMGV);
3503
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003504 std::vector<llvm::Constant*> Used;
3505 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3506 e = UsedGlobals.end(); i != e; ++i) {
3507 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3508 }
3509
3510 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3511 llvm::GlobalValue *GV =
3512 new llvm::GlobalVariable(AT, false,
3513 llvm::GlobalValue::AppendingLinkage,
3514 llvm::ConstantArray::get(AT, Used),
3515 "llvm.used",
3516 &CGM.getModule());
3517
3518 GV->setSection("llvm.metadata");
3519
3520}
3521
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003522// Metadata flags
3523enum MetaDataDlags {
3524 CLS = 0x0,
3525 CLS_META = 0x1,
3526 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003527 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003528 CLS_EXCEPTION = 0x20
3529};
3530/// BuildClassRoTInitializer - generate meta-data for:
3531/// struct _class_ro_t {
3532/// uint32_t const flags;
3533/// uint32_t const instanceStart;
3534/// uint32_t const instanceSize;
3535/// uint32_t const reserved; // only when building for 64bit targets
3536/// const uint8_t * const ivarLayout;
3537/// const char *const name;
3538/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003539/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003540/// const struct _ivar_list_t *const ivars;
3541/// const uint8_t * const weakIvarLayout;
3542/// const struct _prop_list_t * const properties;
3543/// }
3544///
3545llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3546 unsigned flags,
3547 unsigned InstanceStart,
3548 unsigned InstanceSize,
3549 const ObjCImplementationDecl *ID) {
3550 std::string ClassName = ID->getNameAsString();
3551 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3552 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3553 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3554 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3555 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003556 // FIXME. ivarLayout is currently null!
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003557 Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3558 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003559 // const struct _method_list_t * const baseMethods;
3560 std::vector<llvm::Constant*> Methods;
3561 std::string MethodListName("\01l_OBJC_$_");
3562 if (flags & CLS_META) {
3563 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3564 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3565 e = ID->classmeth_end(); i != e; ++i) {
3566 // Class methods should always be defined.
3567 Methods.push_back(GetMethodConstant(*i));
3568 }
3569 } else {
3570 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3571 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3572 e = ID->instmeth_end(); i != e; ++i) {
3573 // Instance methods should always be defined.
3574 Methods.push_back(GetMethodConstant(*i));
3575 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003576 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3577 e = ID->propimpl_end(); i != e; ++i) {
3578 ObjCPropertyImplDecl *PID = *i;
3579
3580 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3581 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3582
3583 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3584 if (llvm::Constant *C = GetMethodConstant(MD))
3585 Methods.push_back(C);
3586 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3587 if (llvm::Constant *C = GetMethodConstant(MD))
3588 Methods.push_back(C);
3589 }
3590 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003591 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003592 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003593 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003594
3595 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3596 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3597 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3598 + OID->getNameAsString(),
3599 OID->protocol_begin(),
3600 OID->protocol_end());
3601
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003602 if (flags & CLS_META)
3603 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3604 else
3605 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003606 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003607 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003608 if (flags & CLS_META)
3609 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3610 else
3611 Values[ 9] =
3612 EmitPropertyList(
3613 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3614 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003615 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3616 Values);
3617 llvm::GlobalVariable *CLASS_RO_GV =
3618 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3619 llvm::GlobalValue::InternalLinkage,
3620 Init,
3621 (flags & CLS_META) ?
3622 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3623 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3624 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003625 CLASS_RO_GV->setAlignment(
3626 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003627 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003628 UsedGlobals.push_back(CLASS_RO_GV);
3629 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003630
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003631}
3632
3633/// BuildClassMetaData - This routine defines that to-level meta-data
3634/// for the given ClassName for:
3635/// struct _class_t {
3636/// struct _class_t *isa;
3637/// struct _class_t * const superclass;
3638/// void *cache;
3639/// IMP *vtable;
3640/// struct class_ro_t *ro;
3641/// }
3642///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003643llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3644 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003645 llvm::Constant *IsAGV,
3646 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003647 llvm::Constant *ClassRoGV,
3648 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003649 std::vector<llvm::Constant*> Values(5);
3650 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003651 Values[1] = SuperClassGV
3652 ? SuperClassGV
3653 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003654 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3655 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3656 Values[4] = ClassRoGV; // &CLASS_RO_GV
3657 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3658 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003659 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3660 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003661 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003662 GV->setAlignment(
3663 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003664 if (HiddenVisibility)
3665 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003666 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003667 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003668}
3669
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003670void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3671 std::string ClassName = ID->getNameAsString();
3672 if (!ObjCEmptyCacheVar) {
3673 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003674 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003675 false,
3676 llvm::GlobalValue::ExternalLinkage,
3677 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003678 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003679 &CGM.getModule());
3680 UsedGlobals.push_back(ObjCEmptyCacheVar);
3681
3682 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003683 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003684 false,
3685 llvm::GlobalValue::ExternalLinkage,
3686 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003687 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003688 &CGM.getModule());
3689 UsedGlobals.push_back(ObjCEmptyVtableVar);
3690 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003691 assert(ID->getClassInterface() &&
3692 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003693 uint32_t InstanceStart =
3694 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3695 uint32_t InstanceSize = InstanceStart;
3696 uint32_t flags = CLS_META;
3697 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3698 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003699
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003700 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003701
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003702 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3703 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003704 flags |= OBJC2_CLS_HIDDEN;
3705 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003706 // class is root
3707 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003708 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3709 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003710 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003711 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003712 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3713 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3714 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003715 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003716 // work on super class metadata symbol.
3717 std::string SuperClassName =
3718 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003719 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003720 }
3721 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3722 InstanceStart,
3723 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003724 std::string TClassName = ObjCMetaClassName + ClassName;
3725 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003726 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3727 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003728
3729 // Metadata for the class
3730 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003731 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003732 flags |= OBJC2_CLS_HIDDEN;
3733 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003734 flags |= CLS_ROOT;
3735 SuperClassGV = 0;
3736 }
3737 else {
3738 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003739 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003740 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003741 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003742 }
3743
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003744 InstanceStart = InstanceSize = 0;
3745 if (ObjCInterfaceDecl *OID =
3746 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3747 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003748 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003749 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003750 const llvm::StructLayout *Layout =
3751 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003752
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003753 RecordDecl::field_iterator firstField, lastField;
3754 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003755
3756 for (RecordDecl::field_iterator e = RD->field_end(),
3757 ifield = firstField; ifield != e; ++ifield)
3758 lastField = ifield;
3759
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003760 if (lastField != RD->field_end()) {
3761 FieldDecl *Field = *lastField;
3762 const llvm::Type *FieldTy =
3763 CGM.getTypes().ConvertTypeForMem(Field->getType());
3764 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3765 InstanceSize = Layout->getElementOffset(
3766 CGM.getTypes().getLLVMFieldNo(Field)) +
3767 Size;
3768 if (firstField == RD->field_end())
3769 InstanceStart = InstanceSize;
3770 else
3771 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3772 getLLVMFieldNo(*firstField));
3773 }
3774 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003775 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003776 InstanceStart,
3777 InstanceSize,
3778 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003779
3780 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003781 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003782 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3783 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003784 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003785}
3786
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003787/// GenerateProtocolRef - This routine is called to generate code for
3788/// a protocol reference expression; as in:
3789/// @code
3790/// @protocol(Proto1);
3791/// @endcode
3792/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3793/// which will hold address of the protocol meta-data.
3794///
3795llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3796 const ObjCProtocolDecl *PD) {
3797
3798 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3799 ObjCTypes.ExternalProtocolPtrTy);
3800
3801 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3802 ProtocolName += PD->getNameAsCString();
3803
3804 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3805 if (PTGV)
3806 return Builder.CreateLoad(PTGV, false, "tmp");
3807 PTGV = new llvm::GlobalVariable(
3808 Init->getType(), false,
3809 llvm::GlobalValue::WeakLinkage,
3810 Init,
3811 ProtocolName,
3812 &CGM.getModule());
3813 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3814 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3815 UsedGlobals.push_back(PTGV);
3816 return Builder.CreateLoad(PTGV, false, "tmp");
3817}
3818
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003819/// GenerateCategory - Build metadata for a category implementation.
3820/// struct _category_t {
3821/// const char * const name;
3822/// struct _class_t *const cls;
3823/// const struct _method_list_t * const instance_methods;
3824/// const struct _method_list_t * const class_methods;
3825/// const struct _protocol_list_t * const protocols;
3826/// const struct _prop_list_t * const properties;
3827/// }
3828///
3829void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3830{
3831 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003832 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3833 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003834 "_$_" + OCD->getNameAsString());
3835 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3836
3837 std::vector<llvm::Constant*> Values(6);
3838 Values[0] = GetClassName(OCD->getIdentifier());
3839 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003840 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003841 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003842 std::vector<llvm::Constant*> Methods;
3843 std::string MethodListName(Prefix);
3844 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3845 "_$_" + OCD->getNameAsString();
3846
3847 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3848 e = OCD->instmeth_end(); i != e; ++i) {
3849 // Instance methods should always be defined.
3850 Methods.push_back(GetMethodConstant(*i));
3851 }
3852
3853 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003854 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003855 Methods);
3856
3857 MethodListName = Prefix;
3858 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3859 OCD->getNameAsString();
3860 Methods.clear();
3861 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3862 e = OCD->classmeth_end(); i != e; ++i) {
3863 // Class methods should always be defined.
3864 Methods.push_back(GetMethodConstant(*i));
3865 }
3866
3867 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003868 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003869 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003870 const ObjCCategoryDecl *Category =
3871 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003872 if (Category) {
3873 std::string ExtName(Interface->getNameAsString() + "_$_" +
3874 OCD->getNameAsString());
3875 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3876 + Interface->getNameAsString() + "_$_"
3877 + Category->getNameAsString(),
3878 Category->protocol_begin(),
3879 Category->protocol_end());
3880 Values[5] =
3881 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3882 OCD, Category, ObjCTypes);
3883 }
3884 else {
3885 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3886 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3887 }
3888
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003889 llvm::Constant *Init =
3890 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3891 Values);
3892 llvm::GlobalVariable *GCATV
3893 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3894 false,
3895 llvm::GlobalValue::InternalLinkage,
3896 Init,
3897 ExtCatName,
3898 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003899 GCATV->setAlignment(
3900 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003901 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003902 UsedGlobals.push_back(GCATV);
3903 DefinedCategories.push_back(GCATV);
3904}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003905
3906/// GetMethodConstant - Return a struct objc_method constant for the
3907/// given method if it has been defined. The result is null if the
3908/// method has not been defined. The return value has type MethodPtrTy.
3909llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3910 const ObjCMethodDecl *MD) {
3911 // FIXME: Use DenseMap::lookup
3912 llvm::Function *Fn = MethodDefinitions[MD];
3913 if (!Fn)
3914 return 0;
3915
3916 std::vector<llvm::Constant*> Method(3);
3917 Method[0] =
3918 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3919 ObjCTypes.SelectorPtrTy);
3920 Method[1] = GetMethodVarType(MD);
3921 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3922 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3923}
3924
3925/// EmitMethodList - Build meta-data for method declarations
3926/// struct _method_list_t {
3927/// uint32_t entsize; // sizeof(struct _objc_method)
3928/// uint32_t method_count;
3929/// struct _objc_method method_list[method_count];
3930/// }
3931///
3932llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3933 const std::string &Name,
3934 const char *Section,
3935 const ConstantVector &Methods) {
3936 // Return null for empty list.
3937 if (Methods.empty())
3938 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3939
3940 std::vector<llvm::Constant*> Values(3);
3941 // sizeof(struct _objc_method)
3942 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3943 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3944 // method_count
3945 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3946 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3947 Methods.size());
3948 Values[2] = llvm::ConstantArray::get(AT, Methods);
3949 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3950
3951 llvm::GlobalVariable *GV =
3952 new llvm::GlobalVariable(Init->getType(), false,
3953 llvm::GlobalValue::InternalLinkage,
3954 Init,
3955 Name,
3956 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003957 GV->setAlignment(
3958 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003959 GV->setSection(Section);
3960 UsedGlobals.push_back(GV);
3961 return llvm::ConstantExpr::getBitCast(GV,
3962 ObjCTypes.MethodListnfABIPtrTy);
3963}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003964
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003965/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
3966/// the given ivar.
3967///
3968llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
3969 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00003970 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003971 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00003972 Name += "\01_OBJC_IVAR_$_" +
3973 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003974 + Ivar->getNameAsString();
3975 llvm::GlobalVariable *IvarOffsetGV =
3976 CGM.getModule().getGlobalVariable(Name);
3977 if (!IvarOffsetGV)
3978 IvarOffsetGV =
3979 new llvm::GlobalVariable(ObjCTypes.LongTy,
3980 false,
3981 llvm::GlobalValue::ExternalLinkage,
3982 0,
3983 Name,
3984 &CGM.getModule());
3985 return IvarOffsetGV;
3986}
3987
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003988llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003989 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00003990 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003991 unsigned long int Offset) {
3992
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003993 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003994 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00003995 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00003996 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003997
3998 llvm::GlobalVariable *IvarOffsetGV =
3999 CGM.getModule().getGlobalVariable(ExternalName);
4000 if (IvarOffsetGV) {
4001 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004002 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004003 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004004 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004005 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004006 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004007 return IvarOffsetGV;
4008 }
4009
4010 IvarOffsetGV =
4011 new llvm::GlobalVariable(Init->getType(),
4012 false,
4013 llvm::GlobalValue::ExternalLinkage,
4014 Init,
4015 ExternalName,
4016 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004017 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004018 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004019 // @private and @package have hidden visibility.
4020 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4021 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4022 if (!globalVisibility)
4023 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004024 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004025 if (IsClassHidden(ID))
4026 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004027
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004028 IvarOffsetGV->setSection("__DATA, __objc_const");
4029 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004030 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004031}
4032
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004033/// EmitIvarList - Emit the ivar list for the given
4034/// implementation. If ForClass is true the list of class ivars
4035/// (i.e. metaclass ivars) is emitted, otherwise the list of
4036/// interface ivars will be emitted. The return value has type
4037/// IvarListnfABIPtrTy.
4038/// struct _ivar_t {
4039/// unsigned long int *offset; // pointer to ivar offset location
4040/// char *name;
4041/// char *type;
4042/// uint32_t alignment;
4043/// uint32_t size;
4044/// }
4045/// struct _ivar_list_t {
4046/// uint32 entsize; // sizeof(struct _ivar_t)
4047/// uint32 count;
4048/// struct _iver_t list[count];
4049/// }
4050///
4051llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4052 const ObjCImplementationDecl *ID) {
4053
4054 std::vector<llvm::Constant*> Ivars, Ivar(5);
4055
4056 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4057 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4058
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004059 // FIXME. Consolidate this with similar code in GenerateClass.
4060 const llvm::Type *InterfaceTy =
4061 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4062 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004063 const llvm::StructLayout *Layout =
4064 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004065
4066 RecordDecl::field_iterator i,p;
4067 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004068 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4069
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004070 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004071 FieldDecl *Field = *i;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004072 unsigned long offset = Layout->getElementOffset(CGM.getTypes().
4073 getLLVMFieldNo(Field));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004074 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004075 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004076 if (Field->getIdentifier())
4077 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4078 else
4079 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4080 std::string TypeStr;
4081 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
4082 Ivar[2] = GetMethodVarType(TypeStr);
4083 const llvm::Type *FieldTy =
4084 CGM.getTypes().ConvertTypeForMem(Field->getType());
4085 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4086 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4087 Field->getType().getTypePtr()) >> 3;
4088 Align = llvm::Log2_32(Align);
4089 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004090 // NOTE. Size of a bitfield does not match gcc's, because of the way
4091 // bitfields are treated special in each. But I am told that 'size'
4092 // for bitfield ivars is ignored by the runtime so it does not matter.
4093 // (even if it matters, some day, there is enough info. to get the bitfield
4094 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004095 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4096 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4097 }
4098 // Return null for empty list.
4099 if (Ivars.empty())
4100 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4101 std::vector<llvm::Constant*> Values(3);
4102 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4103 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4104 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4105 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4106 Ivars.size());
4107 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4108 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4109 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4110 llvm::GlobalVariable *GV =
4111 new llvm::GlobalVariable(Init->getType(), false,
4112 llvm::GlobalValue::InternalLinkage,
4113 Init,
4114 Prefix + OID->getNameAsString(),
4115 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004116 GV->setAlignment(
4117 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004118 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004119
4120 UsedGlobals.push_back(GV);
4121 return llvm::ConstantExpr::getBitCast(GV,
4122 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004123}
4124
4125llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4126 const ObjCProtocolDecl *PD) {
4127 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4128
4129 if (!Entry) {
4130 // We use the initializer as a marker of whether this is a forward
4131 // reference or not. At module finalization we add the empty
4132 // contents for protocols which were referenced but never defined.
4133 Entry =
4134 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4135 llvm::GlobalValue::ExternalLinkage,
4136 0,
4137 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4138 &CGM.getModule());
4139 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4140 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004141 }
4142
4143 return Entry;
4144}
4145
4146/// GetOrEmitProtocol - Generate the protocol meta-data:
4147/// @code
4148/// struct _protocol_t {
4149/// id isa; // NULL
4150/// const char * const protocol_name;
4151/// const struct _protocol_list_t * protocol_list; // super protocols
4152/// const struct method_list_t * const instance_methods;
4153/// const struct method_list_t * const class_methods;
4154/// const struct method_list_t *optionalInstanceMethods;
4155/// const struct method_list_t *optionalClassMethods;
4156/// const struct _prop_list_t * properties;
4157/// const uint32_t size; // sizeof(struct _protocol_t)
4158/// const uint32_t flags; // = 0
4159/// }
4160/// @endcode
4161///
4162
4163llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4164 const ObjCProtocolDecl *PD) {
4165 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4166
4167 // Early exit if a defining object has already been generated.
4168 if (Entry && Entry->hasInitializer())
4169 return Entry;
4170
4171 const char *ProtocolName = PD->getNameAsCString();
4172
4173 // Construct method lists.
4174 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4175 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4176 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4177 e = PD->instmeth_end(); i != e; ++i) {
4178 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004179 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004180 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4181 OptInstanceMethods.push_back(C);
4182 } else {
4183 InstanceMethods.push_back(C);
4184 }
4185 }
4186
4187 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4188 e = PD->classmeth_end(); i != e; ++i) {
4189 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004190 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004191 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4192 OptClassMethods.push_back(C);
4193 } else {
4194 ClassMethods.push_back(C);
4195 }
4196 }
4197
4198 std::vector<llvm::Constant*> Values(10);
4199 // isa is NULL
4200 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4201 Values[1] = GetClassName(PD->getIdentifier());
4202 Values[2] = EmitProtocolList(
4203 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4204 PD->protocol_begin(),
4205 PD->protocol_end());
4206
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004207 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004208 + PD->getNameAsString(),
4209 "__DATA, __objc_const",
4210 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004211 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004212 + PD->getNameAsString(),
4213 "__DATA, __objc_const",
4214 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004215 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004216 + PD->getNameAsString(),
4217 "__DATA, __objc_const",
4218 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004219 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004220 + PD->getNameAsString(),
4221 "__DATA, __objc_const",
4222 OptClassMethods);
4223 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4224 0, PD, ObjCTypes);
4225 uint32_t Size =
4226 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4227 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4228 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4229 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4230 Values);
4231
4232 if (Entry) {
4233 // Already created, fix the linkage and update the initializer.
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004234 Entry->setLinkage(llvm::GlobalValue::WeakLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004235 Entry->setInitializer(Init);
4236 } else {
4237 Entry =
4238 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004239 llvm::GlobalValue::WeakLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004240 Init,
4241 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4242 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004243 Entry->setAlignment(
4244 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004245 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004246 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004247 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4248
4249 // Use this protocol meta-data to build protocol list table in section
4250 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004251 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004252 ObjCTypes.ProtocolnfABIPtrTy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004253 llvm::GlobalValue::WeakLinkage,
4254 Entry,
4255 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4256 +ProtocolName,
4257 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004258 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004259 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004260 PTGV->setSection("__DATA, __objc_protolist");
4261 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4262 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004263 return Entry;
4264}
4265
4266/// EmitProtocolList - Generate protocol list meta-data:
4267/// @code
4268/// struct _protocol_list_t {
4269/// long protocol_count; // Note, this is 32/64 bit
4270/// struct _protocol_t[protocol_count];
4271/// }
4272/// @endcode
4273///
4274llvm::Constant *
4275CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4276 ObjCProtocolDecl::protocol_iterator begin,
4277 ObjCProtocolDecl::protocol_iterator end) {
4278 std::vector<llvm::Constant*> ProtocolRefs;
4279
Fariborz Jahanianda320092009-01-29 19:24:30 +00004280 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004281 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004282 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4283
Daniel Dunbar948e2582009-02-15 07:36:20 +00004284 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004285 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4286 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004287 return llvm::ConstantExpr::getBitCast(GV,
4288 ObjCTypes.ProtocolListnfABIPtrTy);
4289
4290 for (; begin != end; ++begin)
4291 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4292
Fariborz Jahanianda320092009-01-29 19:24:30 +00004293 // This list is null terminated.
4294 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004295 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004296
4297 std::vector<llvm::Constant*> Values(2);
4298 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4299 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004300 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004301 ProtocolRefs.size()),
4302 ProtocolRefs);
4303
4304 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4305 GV = new llvm::GlobalVariable(Init->getType(), false,
4306 llvm::GlobalValue::InternalLinkage,
4307 Init,
4308 Name,
4309 &CGM.getModule());
4310 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004311 GV->setAlignment(
4312 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004313 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004314 return llvm::ConstantExpr::getBitCast(GV,
4315 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004316}
4317
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004318/// GetMethodDescriptionConstant - This routine build following meta-data:
4319/// struct _objc_method {
4320/// SEL _cmd;
4321/// char *method_type;
4322/// char *_imp;
4323/// }
4324
4325llvm::Constant *
4326CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4327 std::vector<llvm::Constant*> Desc(3);
4328 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4329 ObjCTypes.SelectorPtrTy);
4330 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004331 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004332 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4333 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4334}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004335
4336/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4337/// This code gen. amounts to generating code for:
4338/// @code
4339/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4340/// @encode
4341///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004342LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004343 CodeGen::CodeGenFunction &CGF,
4344 QualType ObjectTy,
4345 llvm::Value *BaseValue,
4346 const ObjCIvarDecl *Ivar,
4347 const FieldDecl *Field,
4348 unsigned CVRQualifiers) {
4349 assert(ObjectTy->isObjCInterfaceType() &&
4350 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004351 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004352 std::string ExternalName;
4353 llvm::GlobalVariable *IvarOffsetGV =
4354 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004355
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004356 // (char *) BaseValue
4357 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4358 ObjCTypes.Int8PtrTy);
4359 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4360 // (char*)BaseValue + Offset_symbol
4361 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4362 // (type *)((char*)BaseValue + Offset_symbol)
4363 const llvm::Type *IvarTy =
4364 CGM.getTypes().ConvertType(Ivar->getType());
4365 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4366 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004367
4368 if (Ivar->isBitField())
4369 return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4370 CVRQualifiers);
4371
4372 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004373 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4374 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004375 LValue::SetObjCIvar(LV, true);
4376 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004377}
4378
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004379llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4380 CodeGen::CodeGenFunction &CGF,
4381 ObjCInterfaceDecl *Interface,
4382 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004383 std::string ExternalName;
4384 llvm::GlobalVariable *IvarOffsetGV =
4385 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4386
4387 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004388}
4389
Fariborz Jahanian46551122009-02-04 00:22:57 +00004390CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4391 CodeGen::CodeGenFunction &CGF,
4392 QualType ResultType,
4393 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004394 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004395 QualType Arg0Ty,
4396 bool IsSuper,
4397 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004398 // FIXME. Even though IsSuper is passes. This function doese not
4399 // handle calls to 'super' receivers.
4400 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004401 llvm::Value *Arg0 = Receiver;
4402 if (!IsSuper)
4403 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004404
4405 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004406 // FIXME. This is too much work to get the ABI-specific result type
4407 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004408 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4409 llvm::SmallVector<QualType, 16>());
4410 llvm::Constant *Fn;
4411 std::string Name("\01l_");
4412 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004413#if 0
4414 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004415 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4416 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4417 // FIXME. Is there a better way of getting these names.
4418 // They are available in RuntimeFunctions vector pair.
4419 Name += "objc_msgSendId_stret_fixup";
4420 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004421 else
4422#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004423 if (IsSuper) {
4424 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4425 Name += "objc_msgSendSuper2_stret_fixup";
4426 }
4427 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004428 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004429 Fn = ObjCTypes.MessageSendStretFixupFn;
4430 Name += "objc_msgSend_stret_fixup";
4431 }
4432 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004433 else if (ResultType->isFloatingType() &&
4434 // Selection of frret API only happens in 32bit nonfragile ABI.
4435 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004436 Fn = ObjCTypes.MessageSendFpretFixupFn;
4437 Name += "objc_msgSend_fpret_fixup";
4438 }
4439 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004440#if 0
4441// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004442 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4443 Fn = ObjCTypes.MessageSendIdFixupFn;
4444 Name += "objc_msgSendId_fixup";
4445 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004446 else
4447#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004448 if (IsSuper) {
4449 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4450 Name += "objc_msgSendSuper2_fixup";
4451 }
4452 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004453 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004454 Fn = ObjCTypes.MessageSendFixupFn;
4455 Name += "objc_msgSend_fixup";
4456 }
4457 }
4458 Name += '_';
4459 std::string SelName(Sel.getAsString());
4460 // Replace all ':' in selector name with '_' ouch!
4461 for(unsigned i = 0; i < SelName.size(); i++)
4462 if (SelName[i] == ':')
4463 SelName[i] = '_';
4464 Name += SelName;
4465 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4466 if (!GV) {
4467 // Build messafe ref table entry.
4468 std::vector<llvm::Constant*> Values(2);
4469 Values[0] = Fn;
4470 Values[1] = GetMethodVarName(Sel);
4471 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4472 GV = new llvm::GlobalVariable(Init->getType(), false,
4473 llvm::GlobalValue::WeakLinkage,
4474 Init,
4475 Name,
4476 &CGM.getModule());
4477 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4478 GV->setAlignment(
4479 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4480 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4481 UsedGlobals.push_back(GV);
4482 }
4483 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004484
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004485 CallArgList ActualArgs;
4486 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4487 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4488 ObjCTypes.MessageRefCPtrTy));
4489 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004490 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4491 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4492 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004493 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004494 Callee = CGF.Builder.CreateBitCast(Callee,
4495 llvm::PointerType::getUnqual(FTy));
4496 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004497}
4498
4499/// Generate code for a message send expression in the nonfragile abi.
4500CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4501 CodeGen::CodeGenFunction &CGF,
4502 QualType ResultType,
4503 Selector Sel,
4504 llvm::Value *Receiver,
4505 bool IsClassMessage,
4506 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004507 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004508 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004509 false, CallArgs);
4510}
4511
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004512llvm::GlobalVariable *
4513CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4514 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4515
Daniel Dunbardfff2302009-03-02 05:18:14 +00004516 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004517 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4518 llvm::GlobalValue::ExternalLinkage,
4519 0, Name, &CGM.getModule());
4520 UsedGlobals.push_back(GV);
4521 }
4522
4523 return GV;
4524}
4525
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004526llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004527 const ObjCInterfaceDecl *ID,
4528 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004529
4530 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4531
4532 if (!Entry) {
4533 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004534 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004535 Entry =
4536 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4537 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004538 ClassGV,
4539 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4540 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004541 &CGM.getModule());
4542 Entry->setAlignment(
4543 CGM.getTargetData().getPrefTypeAlignment(
4544 ObjCTypes.ClassnfABIPtrTy));
4545
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004546 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004547 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004548 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004549 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004550 UsedGlobals.push_back(Entry);
4551 }
4552
4553 return Builder.CreateLoad(Entry, false, "tmp");
4554}
4555
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004556/// EmitMetaClassRef - Return a Value * of the address of _class_t
4557/// meta-data
4558///
4559llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4560 const ObjCInterfaceDecl *ID) {
4561 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4562 if (Entry)
4563 return Builder.CreateLoad(Entry, false, "tmp");
4564
4565 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004566 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004567 Entry =
4568 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4569 llvm::GlobalValue::InternalLinkage,
4570 MetaClassGV,
4571 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4572 &CGM.getModule());
4573 Entry->setAlignment(
4574 CGM.getTargetData().getPrefTypeAlignment(
4575 ObjCTypes.ClassnfABIPtrTy));
4576
4577 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4578 UsedGlobals.push_back(Entry);
4579
4580 return Builder.CreateLoad(Entry, false, "tmp");
4581}
4582
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004583/// GetClass - Return a reference to the class for the given interface
4584/// decl.
4585llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4586 const ObjCInterfaceDecl *ID) {
4587 return EmitClassRef(Builder, ID);
4588}
4589
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004590/// Generates a message send where the super is the receiver. This is
4591/// a message send to self with special delivery semantics indicating
4592/// which class's method should be called.
4593CodeGen::RValue
4594CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4595 QualType ResultType,
4596 Selector Sel,
4597 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004598 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004599 llvm::Value *Receiver,
4600 bool IsClassMessage,
4601 const CodeGen::CallArgList &CallArgs) {
4602 // ...
4603 // Create and init a super structure; this is a (receiver, class)
4604 // pair we will pass to objc_msgSendSuper.
4605 llvm::Value *ObjCSuper =
4606 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4607
4608 llvm::Value *ReceiverAsObject =
4609 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4610 CGF.Builder.CreateStore(ReceiverAsObject,
4611 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4612
4613 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004614 llvm::Value *Target;
4615 if (IsClassMessage) {
4616 if (isCategoryImpl) {
4617 // Message sent to "super' in a class method defined in
4618 // a category implementation.
4619 Target = EmitClassRef(CGF.Builder, Class, false);
4620 Target = CGF.Builder.CreateStructGEP(Target, 0);
4621 Target = CGF.Builder.CreateLoad(Target);
4622 }
4623 else
4624 Target = EmitMetaClassRef(CGF.Builder, Class);
4625 }
4626 else
4627 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004628
4629 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4630 // and ObjCTypes types.
4631 const llvm::Type *ClassTy =
4632 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4633 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4634 CGF.Builder.CreateStore(Target,
4635 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4636
4637 return EmitMessageSend(CGF, ResultType, Sel,
4638 ObjCSuper, ObjCTypes.SuperPtrCTy,
4639 true, CallArgs);
4640}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004641
4642llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4643 Selector Sel) {
4644 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4645
4646 if (!Entry) {
4647 llvm::Constant *Casted =
4648 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4649 ObjCTypes.SelectorPtrTy);
4650 Entry =
4651 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4652 llvm::GlobalValue::InternalLinkage,
4653 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4654 &CGM.getModule());
4655 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4656 UsedGlobals.push_back(Entry);
4657 }
4658
4659 return Builder.CreateLoad(Entry, false, "tmp");
4660}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004661/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4662/// objc_assign_ivar (id src, id *dst)
4663///
4664void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4665 llvm::Value *src, llvm::Value *dst)
4666{
4667 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4668 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4669 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4670 src, dst, "assignivar");
4671 return;
4672}
4673
4674/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4675/// objc_assign_strongCast (id src, id *dst)
4676///
4677void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4678 CodeGen::CodeGenFunction &CGF,
4679 llvm::Value *src, llvm::Value *dst)
4680{
4681 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4682 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4683 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4684 src, dst, "weakassign");
4685 return;
4686}
4687
4688/// EmitObjCWeakRead - Code gen for loading value of a __weak
4689/// object: objc_read_weak (id *src)
4690///
4691llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4692 CodeGen::CodeGenFunction &CGF,
4693 llvm::Value *AddrWeakObj)
4694{
4695 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4696 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4697 AddrWeakObj, "weakread");
4698 return read_weak;
4699}
4700
4701/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4702/// objc_assign_weak (id src, id *dst)
4703///
4704void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4705 llvm::Value *src, llvm::Value *dst)
4706{
4707 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4708 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4709 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4710 src, dst, "weakassign");
4711 return;
4712}
4713
4714/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4715/// objc_assign_global (id src, id *dst)
4716///
4717void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4718 llvm::Value *src, llvm::Value *dst)
4719{
4720 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4721 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4722 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4723 src, dst, "globalassign");
4724 return;
4725}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004726
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004727void
4728CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4729 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004730 bool isTry = isa<ObjCAtTryStmt>(S);
4731 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4732 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004733 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004734 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004735 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004736 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4737
4738 // For @synchronized, call objc_sync_enter(sync.expr). The
4739 // evaluation of the expression must occur before we enter the
4740 // @synchronized. We can safely avoid a temp here because jumps into
4741 // @synchronized are illegal & this will dominate uses.
4742 llvm::Value *SyncArg = 0;
4743 if (!isTry) {
4744 SyncArg =
4745 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4746 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4747 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4748 }
4749
4750 // Push an EH context entry, used for handling rethrows and jumps
4751 // through finally.
4752 CGF.PushCleanupBlock(FinallyBlock);
4753
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004754 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004755
4756 CGF.EmitBlock(TryBlock);
4757 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4758 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4759 CGF.EmitBranchThroughCleanup(FinallyEnd);
4760
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004761 // Emit the exception handler.
4762
4763 CGF.EmitBlock(TryHandler);
4764
4765 llvm::Value *llvm_eh_exception =
4766 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4767 llvm::Value *llvm_eh_selector_i64 =
4768 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4769 llvm::Value *llvm_eh_typeid_for_i64 =
4770 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4771 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4772 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4773
4774 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4775 SelectorArgs.push_back(Exc);
4776 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4777
4778 // Construct the lists of (type, catch body) to handle.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004779 llvm::SmallVector<std::pair<const Decl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004780 bool HasCatchAll = false;
4781 if (isTry) {
4782 if (const ObjCAtCatchStmt* CatchStmt =
4783 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4784 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004785 const Decl *CatchDecl = CatchStmt->getCatchParamDecl();
4786 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004787
4788 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004789 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004790 // Use i8* null here to signal this is a catch all, not a cleanup.
4791 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4792 SelectorArgs.push_back(Null);
4793 HasCatchAll = true;
4794 break;
4795 }
4796
Steve Naroff7ba138a2009-03-03 19:52:17 +00004797 const VarDecl *VD = cast<VarDecl>(CatchDecl);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004798 if (CGF.getContext().isObjCIdType(VD->getType()) ||
4799 VD->getType()->isObjCQualifiedIdType()) {
4800 llvm::Value *IDEHType =
4801 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4802 if (!IDEHType)
4803 IDEHType =
4804 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4805 llvm::GlobalValue::ExternalLinkage,
4806 0, "OBJC_EHTYPE_id", &CGM.getModule());
4807 SelectorArgs.push_back(IDEHType);
4808 HasCatchAll = true;
4809 break;
4810 }
4811
4812 // All other types should be Objective-C interface pointer types.
4813 const PointerType *PT = VD->getType()->getAsPointerType();
4814 assert(PT && "Invalid @catch type.");
4815 const ObjCInterfaceType *IT =
4816 PT->getPointeeType()->getAsObjCInterfaceType();
4817 assert(IT && "Invalid @catch type.");
4818 llvm::Value *EHType = GetInterfaceEHType(IT);
4819 SelectorArgs.push_back(EHType);
4820 }
4821 }
4822 }
4823
4824 // We use a cleanup unless there was already a catch all.
4825 if (!HasCatchAll) {
4826 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004827 Handlers.push_back(std::make_pair((const Decl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004828 }
4829
4830 llvm::Value *Selector =
4831 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4832 SelectorArgs.begin(), SelectorArgs.end(),
4833 "selector");
4834 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004835 const Decl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004836 const Stmt *CatchBody = Handlers[i].second;
4837
4838 llvm::BasicBlock *Next = 0;
4839
4840 // The last handler always matches.
4841 if (i + 1 != e) {
4842 assert(CatchParam && "Only last handler can be a catch all.");
4843
4844 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4845 Next = CGF.createBasicBlock("catch.next");
4846 llvm::Value *Id =
4847 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4848 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4849 ObjCTypes.Int8PtrTy));
4850 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4851 Match, Next);
4852
4853 CGF.EmitBlock(Match);
4854 }
4855
4856 if (CatchBody) {
4857 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4858 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4859
4860 // Cleanups must call objc_end_catch.
4861 //
4862 // FIXME: It seems incorrect for objc_begin_catch to be inside
4863 // this context, but this matches gcc.
4864 CGF.PushCleanupBlock(MatchEnd);
4865 CGF.setInvokeDest(MatchHandler);
4866
4867 llvm::Value *ExcObject =
4868 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4869
4870 // Bind the catch parameter if it exists.
4871 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004872 const VarDecl *VD = dyn_cast<VarDecl>(CatchParam);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004873 ExcObject = CGF.Builder.CreateBitCast(ExcObject,
4874 CGF.ConvertType(VD->getType()));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004875 CGF.EmitLocalBlockVarDecl(*VD);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004876 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(VD));
4877 }
4878
4879 CGF.ObjCEHValueStack.push_back(ExcObject);
4880 CGF.EmitStmt(CatchBody);
4881 CGF.ObjCEHValueStack.pop_back();
4882
4883 CGF.EmitBranchThroughCleanup(FinallyEnd);
4884
4885 CGF.EmitBlock(MatchHandler);
4886
4887 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4888 // We are required to emit this call to satisfy LLVM, even
4889 // though we don't use the result.
4890 llvm::SmallVector<llvm::Value*, 8> Args;
4891 Args.push_back(Exc);
4892 Args.push_back(ObjCTypes.EHPersonalityPtr);
4893 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4894 0));
4895 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4896 CGF.Builder.CreateStore(Exc, RethrowPtr);
4897 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4898
4899 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4900
4901 CGF.EmitBlock(MatchEnd);
4902
4903 // Unfortunately, we also have to generate another EH frame here
4904 // in case this throws.
4905 llvm::BasicBlock *MatchEndHandler =
4906 CGF.createBasicBlock("match.end.handler");
4907 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4908 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
4909 Cont, MatchEndHandler,
4910 Args.begin(), Args.begin());
4911
4912 CGF.EmitBlock(Cont);
4913 if (Info.SwitchBlock)
4914 CGF.EmitBlock(Info.SwitchBlock);
4915 if (Info.EndBlock)
4916 CGF.EmitBlock(Info.EndBlock);
4917
4918 CGF.EmitBlock(MatchEndHandler);
4919 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4920 // We are required to emit this call to satisfy LLVM, even
4921 // though we don't use the result.
4922 Args.clear();
4923 Args.push_back(Exc);
4924 Args.push_back(ObjCTypes.EHPersonalityPtr);
4925 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4926 0));
4927 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4928 CGF.Builder.CreateStore(Exc, RethrowPtr);
4929 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4930
4931 if (Next)
4932 CGF.EmitBlock(Next);
4933 } else {
4934 assert(!Next && "catchup should be last handler.");
4935
4936 CGF.Builder.CreateStore(Exc, RethrowPtr);
4937 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4938 }
4939 }
4940
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004941 // Pop the cleanup entry, the @finally is outside this cleanup
4942 // scope.
4943 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4944 CGF.setInvokeDest(PrevLandingPad);
4945
4946 CGF.EmitBlock(FinallyBlock);
4947
4948 if (isTry) {
4949 if (const ObjCAtFinallyStmt* FinallyStmt =
4950 cast<ObjCAtTryStmt>(S).getFinallyStmt())
4951 CGF.EmitStmt(FinallyStmt->getFinallyBody());
4952 } else {
4953 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
4954 // @synchronized.
4955 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004956 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004957
4958 if (Info.SwitchBlock)
4959 CGF.EmitBlock(Info.SwitchBlock);
4960 if (Info.EndBlock)
4961 CGF.EmitBlock(Info.EndBlock);
4962
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004963 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004964 CGF.EmitBranch(FinallyEnd);
4965
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004966 CGF.EmitBlock(FinallyRethrow);
4967 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
4968 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004969 CGF.Builder.CreateUnreachable();
4970
4971 CGF.EmitBlock(FinallyEnd);
4972}
4973
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004974/// EmitThrowStmt - Generate code for a throw statement.
4975void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
4976 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004977 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004978 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004979 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004980 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004981 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4982 "Unexpected rethrow outside @catch block.");
4983 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004984 }
4985
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004986 llvm::Value *ExceptionAsObject =
4987 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
4988 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
4989 if (InvokeDest) {
4990 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4991 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
4992 Cont, InvokeDest,
4993 &ExceptionAsObject, &ExceptionAsObject + 1);
4994 CGF.EmitBlock(Cont);
4995 } else
4996 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
4997 CGF.Builder.CreateUnreachable();
4998
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004999 // Clear the insertion point to indicate we are in unreachable code.
5000 CGF.Builder.ClearInsertionPoint();
5001}
Daniel Dunbare588b992009-03-01 04:46:24 +00005002
5003llvm::Value *
5004CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5005 const ObjCInterfaceDecl *ID = IT->getDecl();
5006 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5007 if (Entry)
5008 return Entry;
5009
5010 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5011 std::string VTableName = "objc_ehtype_vtable";
5012 llvm::GlobalVariable *VTableGV =
5013 CGM.getModule().getGlobalVariable(VTableName);
5014 if (!VTableGV)
5015 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5016 llvm::GlobalValue::ExternalLinkage,
5017 0, VTableName, &CGM.getModule());
5018
5019 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5020
5021 std::vector<llvm::Constant*> Values(3);
5022 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5023 Values[1] = GetClassName(ID->getIdentifier());
5024 Values[2] = GetClassGlobal(ClassName);
5025 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5026
5027 Entry =
5028 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5029 llvm::GlobalValue::WeakLinkage,
5030 Init,
5031 (std::string("OBJC_EHTYPE_$_") +
5032 ID->getIdentifier()->getName()),
5033 &CGM.getModule());
5034
5035 return Entry;
5036}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005037
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005038/* *** */
5039
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005040CodeGen::CGObjCRuntime *
5041CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005042 return new CGObjCMac(CGM);
5043}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005044
5045CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005046CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005047 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005048}