blob: 4d957ebd652f0ecf79c420cbd55a5f31aa335245 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy;
45 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Fariborz Jahaniandb286862009-01-22 00:37:21 +000087 llvm::Function *GetPropertyFn, *SetPropertyFn;
88
89 llvm::Function *EnumerationMutationFn;
90
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
92 llvm::Function *GcReadWeakFn;
93
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
95 llvm::Function *GcAssignWeakFn;
96
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
98 llvm::Function *GcAssignGlobalFn;
99
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
101 llvm::Function *GcAssignIvarFn;
102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
104 llvm::Function *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
107 llvm::Function *ExceptionThrowFn;
108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
110 llvm::Function *SyncEnterFn;
111
112 /// SyncExitFn - LLVM object_sync_exit function.
113 llvm::Function *SyncExitFn;
114
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000115 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
116 ~ObjCCommonTypesHelper(){}
117};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000118
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000119/// ObjCTypesHelper - Helper class that encapsulates lazy
120/// construction of varies types used during ObjC generation.
121class ObjCTypesHelper : public ObjCCommonTypesHelper {
122private:
123
124 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
125 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
126 *MessageSendSuperFpretFn;
127
128public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000129 /// SymtabTy - LLVM type for struct objc_symtab.
130 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000131 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
132 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000133 /// ModuleTy - LLVM type for struct objc_module.
134 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000135
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000136 /// ProtocolTy - LLVM type for struct objc_protocol.
137 const llvm::StructType *ProtocolTy;
138 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
139 const llvm::Type *ProtocolPtrTy;
140 /// ProtocolExtensionTy - LLVM type for struct
141 /// objc_protocol_extension.
142 const llvm::StructType *ProtocolExtensionTy;
143 /// ProtocolExtensionTy - LLVM type for struct
144 /// objc_protocol_extension *.
145 const llvm::Type *ProtocolExtensionPtrTy;
146 /// MethodDescriptionTy - LLVM type for struct
147 /// objc_method_description.
148 const llvm::StructType *MethodDescriptionTy;
149 /// MethodDescriptionListTy - LLVM type for struct
150 /// objc_method_description_list.
151 const llvm::StructType *MethodDescriptionListTy;
152 /// MethodDescriptionListPtrTy - LLVM type for struct
153 /// objc_method_description_list *.
154 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000155 /// ProtocolListTy - LLVM type for struct objc_property_list.
156 const llvm::Type *ProtocolListTy;
157 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
158 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000159 /// CategoryTy - LLVM type for struct objc_category.
160 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000161 /// ClassTy - LLVM type for struct objc_class.
162 const llvm::StructType *ClassTy;
163 /// ClassPtrTy - LLVM type for struct objc_class *.
164 const llvm::Type *ClassPtrTy;
165 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
166 const llvm::StructType *ClassExtensionTy;
167 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
168 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000169 // IvarTy - LLVM type for struct objc_ivar.
170 const llvm::StructType *IvarTy;
171 /// IvarListTy - LLVM type for struct objc_ivar_list.
172 const llvm::Type *IvarListTy;
173 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
174 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 /// MethodListTy - LLVM type for struct objc_method_list.
176 const llvm::Type *MethodListTy;
177 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
178 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000179
180 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
181 const llvm::Type *ExceptionDataTy;
182
Anders Carlsson124526b2008-09-09 10:10:21 +0000183 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
184 llvm::Function *ExceptionTryEnterFn;
185
186 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
187 llvm::Function *ExceptionTryExitFn;
188
189 /// ExceptionExtractFn - LLVM objc_exception_extract function.
190 llvm::Function *ExceptionExtractFn;
191
192 /// ExceptionMatchFn - LLVM objc_exception_match function.
193 llvm::Function *ExceptionMatchFn;
194
195 /// SetJmpFn - LLVM _setjmp function.
196 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000197
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000198public:
199 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000200 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000201
202
203 llvm::Function *getSendFn(bool IsSuper) {
204 return IsSuper ? MessageSendSuperFn : MessageSendFn;
205 }
206
207 llvm::Function *getSendStretFn(bool IsSuper) {
208 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
209 }
210
211 llvm::Function *getSendFpretFn(bool IsSuper) {
212 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
213 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000214};
215
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000216/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000217/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000218class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000219public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000220 llvm::Function *MessageSendFixupFn, *MessageSendFpretFixupFn,
221 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
222 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
223 *MessageSendSuper2StretFixupFn;
224
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000225 // MethodListnfABITy - LLVM for struct _method_list_t
226 const llvm::StructType *MethodListnfABITy;
227
228 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
229 const llvm::Type *MethodListnfABIPtrTy;
230
231 // ProtocolnfABITy = LLVM for struct _protocol_t
232 const llvm::StructType *ProtocolnfABITy;
233
Daniel Dunbar948e2582009-02-15 07:36:20 +0000234 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
235 const llvm::Type *ProtocolnfABIPtrTy;
236
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000237 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
238 const llvm::StructType *ProtocolListnfABITy;
239
240 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
241 const llvm::Type *ProtocolListnfABIPtrTy;
242
243 // ClassnfABITy - LLVM for struct _class_t
244 const llvm::StructType *ClassnfABITy;
245
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000246 // ClassnfABIPtrTy - LLVM for struct _class_t*
247 const llvm::Type *ClassnfABIPtrTy;
248
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000249 // IvarnfABITy - LLVM for struct _ivar_t
250 const llvm::StructType *IvarnfABITy;
251
252 // IvarListnfABITy - LLVM for struct _ivar_list_t
253 const llvm::StructType *IvarListnfABITy;
254
255 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
256 const llvm::Type *IvarListnfABIPtrTy;
257
258 // ClassRonfABITy - LLVM for struct _class_ro_t
259 const llvm::StructType *ClassRonfABITy;
260
261 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
262 const llvm::Type *ImpnfABITy;
263
264 // CategorynfABITy - LLVM for struct _category_t
265 const llvm::StructType *CategorynfABITy;
266
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000267 // New types for nonfragile abi messaging.
268
269 // MessageRefTy - LLVM for:
270 // struct _message_ref_t {
271 // IMP messenger;
272 // SEL name;
273 // };
274 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000275 // MessageRefCTy - clang type for struct _message_ref_t
276 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000277
278 // MessageRefPtrTy - LLVM for struct _message_ref_t*
279 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000280 // MessageRefCPtrTy - clang type for struct _message_ref_t*
281 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000282
Fariborz Jahanianef163782009-02-05 01:13:09 +0000283 // MessengerTy - Type of the messenger (shown as IMP above)
284 const llvm::FunctionType *MessengerTy;
285
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000286 // SuperMessageRefTy - LLVM for:
287 // struct _super_message_ref_t {
288 // SUPER_IMP messenger;
289 // SEL name;
290 // };
291 const llvm::StructType *SuperMessageRefTy;
292
293 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
294 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000295
296 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
297 /// exception personality function.
298 llvm::Value *EHPersonalityPtr;
299
Daniel Dunbare588b992009-03-01 04:46:24 +0000300 llvm::Function *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
301
302 const llvm::StructType *EHTypeTy;
303 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000304
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000305 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
306 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000307};
308
309class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
310protected:
311 CodeGen::CodeGenModule &CGM;
312 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000313 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000314
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000315 /// LazySymbols - Symbols to generate a lazy reference for. See
316 /// DefinedSymbols and FinishModule().
317 std::set<IdentifierInfo*> LazySymbols;
318
319 /// DefinedSymbols - External symbols which are defined by this
320 /// module. The symbols in this list and LazySymbols are used to add
321 /// special linker symbols which ensure that Objective-C modules are
322 /// linked properly.
323 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000324
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000325 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000326 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000328 /// MethodVarNames - uniqued method variable names.
329 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000330
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000331 /// MethodVarTypes - uniqued method type signatures. We have to use
332 /// a StringMap here because have no other unique reference.
333 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000334
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000335 /// MethodDefinitions - map of methods which have been defined in
336 /// this translation unit.
337 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000338
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000339 /// PropertyNames - uniqued method variable names.
340 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000341
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000342 /// ClassReferences - uniqued class references.
343 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000344
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000345 /// SelectorReferences - uniqued selector references.
346 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000347
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000348 /// Protocols - Protocols for which an objc_protocol structure has
349 /// been emitted. Forward declarations are handled by creating an
350 /// empty structure whose initializer is filled in when/if defined.
351 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000352
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000353 /// DefinedProtocols - Protocols which have actually been
354 /// defined. We should not need this, see FIXME in GenerateProtocol.
355 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000356
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000357 /// DefinedClasses - List of defined classes.
358 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000360 /// DefinedCategories - List of defined categories.
361 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000362
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000363 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000364 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000365 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000366
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000367 /// GetNameForMethod - Return a name for the given method.
368 /// \param[out] NameOut - The return value.
369 void GetNameForMethod(const ObjCMethodDecl *OMD,
370 const ObjCContainerDecl *CD,
371 std::string &NameOut);
372
373 /// GetMethodVarName - Return a unique constant for the given
374 /// selector's name. The return value has type char *.
375 llvm::Constant *GetMethodVarName(Selector Sel);
376 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
377 llvm::Constant *GetMethodVarName(const std::string &Name);
378
379 /// GetMethodVarType - Return a unique constant for the given
380 /// selector's name. The return value has type char *.
381
382 // FIXME: This is a horrible name.
383 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000384 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000385
386 /// GetPropertyName - Return a unique constant for the given
387 /// name. The return value has type char *.
388 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
389
390 // FIXME: This can be dropped once string functions are unified.
391 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
392 const Decl *Container);
393
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000394 /// GetClassName - Return a unique constant for the given selector's
395 /// name. The return value has type char *.
396 llvm::Constant *GetClassName(IdentifierInfo *Ident);
397
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000398 /// BuildIvarLayout - Builds ivar layout bitmap for the class
399 /// implementation for the __strong or __weak case.
400 ///
401 llvm::Constant *BuildIvarLayout(ObjCImplementationDecl *OI,
402 bool ForStrongLayout);
403
404 void BuildAggrIvarLayout(RecordDecl *RD,
405 const std::vector<FieldDecl*>& RecFields,
406 unsigned int BytePos, bool ForStrongLayout,
407 int &Index, int &SkIndex, bool &HasUnion);
408
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000409 /// GetIvarLayoutName - Returns a unique constant for the given
410 /// ivar layout bitmap.
411 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
412 const ObjCCommonTypesHelper &ObjCTypes);
413
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000414 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
415 RecordDecl::field_iterator &FIV,
416 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000417 /// EmitPropertyList - Emit the given property list. The return
418 /// value has type PropertyListPtrTy.
419 llvm::Constant *EmitPropertyList(const std::string &Name,
420 const Decl *Container,
421 const ObjCContainerDecl *OCD,
422 const ObjCCommonTypesHelper &ObjCTypes);
423
Fariborz Jahanianda320092009-01-29 19:24:30 +0000424 /// GetProtocolRef - Return a reference to the internal protocol
425 /// description, creating an empty one if it has not been
426 /// defined. The return value has type ProtocolPtrTy.
427 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
428
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000429public:
430 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
431 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000432
433 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000434
435 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
436 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000437
438 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
439
440 /// GetOrEmitProtocol - Get the protocol object for the given
441 /// declaration, emitting it if necessary. The return value has type
442 /// ProtocolPtrTy.
443 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
444
445 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
446 /// object for the given declaration, emitting it if needed. These
447 /// forward references will be filled in with empty bodies if no
448 /// definition is seen. The return value has type ProtocolPtrTy.
449 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000450};
451
452class CGObjCMac : public CGObjCCommonMac {
453private:
454 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000455 /// EmitImageInfo - Emit the image info marker used to encode some module
456 /// level information.
457 void EmitImageInfo();
458
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000459 /// EmitModuleInfo - Another marker encoding module level
460 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000461 void EmitModuleInfo();
462
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000463 /// EmitModuleSymols - Emit module symbols, the list of defined
464 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000465 llvm::Constant *EmitModuleSymbols();
466
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000467 /// FinishModule - Write out global data structures at the end of
468 /// processing a translation unit.
469 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000470
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000471 /// EmitClassExtension - Generate the class extension structure used
472 /// to store the weak ivar layout and properties. The return value
473 /// has type ClassExtensionPtrTy.
474 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
475
476 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
477 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000478 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000479 const ObjCInterfaceDecl *ID);
480
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000481 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000482 QualType ResultType,
483 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000484 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000485 QualType Arg0Ty,
486 bool IsSuper,
487 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000488
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000489 /// EmitIvarList - Emit the ivar list for the given
490 /// implementation. If ForClass is true the list of class ivars
491 /// (i.e. metaclass ivars) is emitted, otherwise the list of
492 /// interface ivars will be emitted. The return value has type
493 /// IvarListPtrTy.
494 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000495 bool ForClass);
496
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000497 /// EmitMetaClass - Emit a forward reference to the class structure
498 /// for the metaclass of the given interface. The return value has
499 /// type ClassPtrTy.
500 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
501
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000502 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000503 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000504 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
505 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000506 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000507 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000508
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000509 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000510
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000511 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000512
513 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000514 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000515 llvm::Constant *EmitMethodList(const std::string &Name,
516 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000517 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000518
519 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000520 /// method declarations.
521 /// - TypeName: The name for the type containing the methods.
522 /// - IsProtocol: True iff these methods are for a protocol.
523 /// - ClassMethds: True iff these are class methods.
524 /// - Required: When true, only "required" methods are
525 /// listed. Similarly, when false only "optional" methods are
526 /// listed. For classes this should always be true.
527 /// - begin, end: The method list to output.
528 ///
529 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000530 llvm::Constant *EmitMethodDescList(const std::string &Name,
531 const char *Section,
532 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000533
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000534 /// GetOrEmitProtocol - Get the protocol object for the given
535 /// declaration, emitting it if necessary. The return value has type
536 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000537 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000538
539 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
540 /// object for the given declaration, emitting it if needed. These
541 /// forward references will be filled in with empty bodies if no
542 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000543 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000544
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000545 /// EmitProtocolExtension - Generate the protocol extension
546 /// structure used to store optional instance and class methods, and
547 /// protocol properties. The return value has type
548 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000549 llvm::Constant *
550 EmitProtocolExtension(const ObjCProtocolDecl *PD,
551 const ConstantVector &OptInstanceMethods,
552 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000553
554 /// EmitProtocolList - Generate the list of referenced
555 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000556 llvm::Constant *EmitProtocolList(const std::string &Name,
557 ObjCProtocolDecl::protocol_iterator begin,
558 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000559
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000560 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
561 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000562 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000563
Fariborz Jahanianda320092009-01-29 19:24:30 +0000564 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000565 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000566
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000567 virtual llvm::Function *ModuleInitFunction();
568
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000569 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000570 QualType ResultType,
571 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000572 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000573 bool IsClassMessage,
574 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000575
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000576 virtual CodeGen::RValue
577 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000578 QualType ResultType,
579 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000581 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000582 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000583 bool IsClassMessage,
584 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000585
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000586 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000587 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000588
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000589 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000590
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000591 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000592
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000593 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000594
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000595 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000596 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000597
Daniel Dunbar49f66022008-09-24 03:38:44 +0000598 virtual llvm::Function *GetPropertyGetFunction();
599 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000600 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000601
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000602 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
603 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000604 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
605 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000606 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000607 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000608 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
609 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000610 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
611 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000612 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
613 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000614 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
615 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000616
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000617 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
618 QualType ObjectTy,
619 llvm::Value *BaseValue,
620 const ObjCIvarDecl *Ivar,
621 const FieldDecl *Field,
622 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000623 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
624 ObjCInterfaceDecl *Interface,
625 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000626};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000627
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000628class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000629private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000630 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000631 llvm::GlobalVariable* ObjCEmptyCacheVar;
632 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000633
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000634 /// MetaClassReferences - uniqued meta class references.
635 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000636
637 /// EHTypeReferences - uniqued class ehtype references.
638 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000639
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000640 /// FinishNonFragileABIModule - Write out global data structures at the end of
641 /// processing a translation unit.
642 void FinishNonFragileABIModule();
643
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000644 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
645 unsigned InstanceStart,
646 unsigned InstanceSize,
647 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000648 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
649 llvm::Constant *IsAGV,
650 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000651 llvm::Constant *ClassRoGV,
652 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000653
654 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
655
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000656 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
657
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000658 /// EmitMethodList - Emit the method list for the given
659 /// implementation. The return value has type MethodListnfABITy.
660 llvm::Constant *EmitMethodList(const std::string &Name,
661 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000662 const ConstantVector &Methods);
663 /// EmitIvarList - Emit the ivar list for the given
664 /// implementation. If ForClass is true the list of class ivars
665 /// (i.e. metaclass ivars) is emitted, otherwise the list of
666 /// interface ivars will be emitted. The return value has type
667 /// IvarListnfABIPtrTy.
668 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000669
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000670 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000671 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000672 unsigned long int offset);
673
Fariborz Jahanianda320092009-01-29 19:24:30 +0000674 /// GetOrEmitProtocol - Get the protocol object for the given
675 /// declaration, emitting it if necessary. The return value has type
676 /// ProtocolPtrTy.
677 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
678
679 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
680 /// object for the given declaration, emitting it if needed. These
681 /// forward references will be filled in with empty bodies if no
682 /// definition is seen. The return value has type ProtocolPtrTy.
683 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
684
685 /// EmitProtocolList - Generate the list of referenced
686 /// protocols. The return value has type ProtocolListPtrTy.
687 llvm::Constant *EmitProtocolList(const std::string &Name,
688 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000689 ObjCProtocolDecl::protocol_iterator end);
690
691 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
692 QualType ResultType,
693 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000694 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000695 QualType Arg0Ty,
696 bool IsSuper,
697 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000698
699 /// GetClassGlobal - Return the global variable for the Objective-C
700 /// class of the given name.
701 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000702
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000703 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
704 /// for the given class.
705 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000706 const ObjCInterfaceDecl *ID,
707 bool IsSuper = false);
708
709 /// EmitMetaClassRef - Return a Value * of the address of _class_t
710 /// meta-data
711 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
712 const ObjCInterfaceDecl *ID);
713
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000714 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
715 /// the given ivar.
716 ///
717 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000718 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000719 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000720
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000721 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
722 /// for the given selector.
723 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000724
725 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
726 /// interface. The return value has type EHTypePtrTy.
727 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000728
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000729public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000730 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000731 // FIXME. All stubs for now!
732 virtual llvm::Function *ModuleInitFunction();
733
734 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
735 QualType ResultType,
736 Selector Sel,
737 llvm::Value *Receiver,
738 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000739 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000740
741 virtual CodeGen::RValue
742 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
743 QualType ResultType,
744 Selector Sel,
745 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000746 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000747 llvm::Value *Receiver,
748 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000749 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000750
751 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000752 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000753
754 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000755 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000756
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000757 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000758
759 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000760 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000761 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000762
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000763 virtual llvm::Function *GetPropertyGetFunction(){
764 return ObjCTypes.GetPropertyFn;
765 }
766 virtual llvm::Function *GetPropertySetFunction(){
767 return ObjCTypes.SetPropertyFn;
768 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000769 virtual llvm::Function *EnumerationMutationFunction() {
770 return ObjCTypes.EnumerationMutationFn;
771 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000772
773 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000774 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000775 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000776 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000777 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000778 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000779 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000780 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000781 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000782 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000783 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000784 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000785 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000786 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000787 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
788 QualType ObjectTy,
789 llvm::Value *BaseValue,
790 const ObjCIvarDecl *Ivar,
791 const FieldDecl *Field,
792 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000793 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
794 ObjCInterfaceDecl *Interface,
795 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000796};
797
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000798} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000799
800/* *** Helper Functions *** */
801
802/// getConstantGEP() - Help routine to construct simple GEPs.
803static llvm::Constant *getConstantGEP(llvm::Constant *C,
804 unsigned idx0,
805 unsigned idx1) {
806 llvm::Value *Idxs[] = {
807 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
808 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
809 };
810 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
811}
812
813/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000814
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000815CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
816 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000817{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000818 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000819 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000820}
821
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000822/// GetClass - Return a reference to the class for the given interface
823/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000824llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000825 const ObjCInterfaceDecl *ID) {
826 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000827}
828
829/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000830llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000831 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000832}
833
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000834/// Generate a constant CFString object.
835/*
836 struct __builtin_CFString {
837 const int *isa; // point to __CFConstantStringClassReference
838 int flags;
839 const char *str;
840 long length;
841 };
842*/
843
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000844llvm::Constant *CGObjCCommonMac::GenerateConstantString(
845 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000846 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000847}
848
849/// Generates a message send where the super is the receiver. This is
850/// a message send to self with special delivery semantics indicating
851/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000852CodeGen::RValue
853CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000854 QualType ResultType,
855 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000856 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000857 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000858 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000859 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000860 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000861 // Create and init a super structure; this is a (receiver, class)
862 // pair we will pass to objc_msgSendSuper.
863 llvm::Value *ObjCSuper =
864 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
865 llvm::Value *ReceiverAsObject =
866 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
867 CGF.Builder.CreateStore(ReceiverAsObject,
868 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000869
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000870 // If this is a class message the metaclass is passed as the target.
871 llvm::Value *Target;
872 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000873 if (isCategoryImpl) {
874 // Message sent to 'super' in a class method defined in a category
875 // implementation requires an odd treatment.
876 // If we are in a class method, we must retrieve the
877 // _metaclass_ for the current class, pointed at by
878 // the class's "isa" pointer. The following assumes that
879 // isa" is the first ivar in a class (which it must be).
880 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
881 Target = CGF.Builder.CreateStructGEP(Target, 0);
882 Target = CGF.Builder.CreateLoad(Target);
883 }
884 else {
885 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
886 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
887 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
888 Target = Super;
889 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000890 } else {
891 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
892 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000893 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
894 // and ObjCTypes types.
895 const llvm::Type *ClassTy =
896 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000897 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000898 CGF.Builder.CreateStore(Target,
899 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
900
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000901 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000902 ObjCSuper, ObjCTypes.SuperPtrCTy,
903 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000904}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000905
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000906/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000907CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000908 QualType ResultType,
909 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000910 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000911 bool IsClassMessage,
912 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000913 llvm::Value *Arg0 =
914 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000915 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000916 Arg0, CGF.getContext().getObjCIdType(),
917 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000918}
919
920CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000921 QualType ResultType,
922 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000923 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000924 QualType Arg0Ty,
925 bool IsSuper,
926 const CallArgList &CallArgs) {
927 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000928 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
929 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
930 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000931 CGF.getContext().getObjCSelType()));
932 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000933
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000934 CodeGenTypes &Types = CGM.getTypes();
935 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
936 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000937
938 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000939 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000940 Fn = ObjCTypes.getSendStretFn(IsSuper);
941 } else if (ResultType->isFloatingType()) {
942 // FIXME: Sadly, this is wrong. This actually depends on the
943 // architecture. This happens to be right for x86-32 though.
944 Fn = ObjCTypes.getSendFpretFn(IsSuper);
945 } else {
946 Fn = ObjCTypes.getSendFn(IsSuper);
947 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000948 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000949 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000950}
951
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000952llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000953 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000954 // FIXME: I don't understand why gcc generates this, or where it is
955 // resolved. Investigate. Its also wasteful to look this up over and
956 // over.
957 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
958
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000959 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
960 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000961}
962
Fariborz Jahanianda320092009-01-29 19:24:30 +0000963void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000964 // FIXME: We shouldn't need this, the protocol decl should contain
965 // enough information to tell us whether this was a declaration or a
966 // definition.
967 DefinedProtocols.insert(PD->getIdentifier());
968
969 // If we have generated a forward reference to this protocol, emit
970 // it now. Otherwise do nothing, the protocol objects are lazily
971 // emitted.
972 if (Protocols.count(PD->getIdentifier()))
973 GetOrEmitProtocol(PD);
974}
975
Fariborz Jahanianda320092009-01-29 19:24:30 +0000976llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000977 if (DefinedProtocols.count(PD->getIdentifier()))
978 return GetOrEmitProtocol(PD);
979 return GetOrEmitProtocolRef(PD);
980}
981
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000982/*
983 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
984 struct _objc_protocol {
985 struct _objc_protocol_extension *isa;
986 char *protocol_name;
987 struct _objc_protocol_list *protocol_list;
988 struct _objc__method_prototype_list *instance_methods;
989 struct _objc__method_prototype_list *class_methods
990 };
991
992 See EmitProtocolExtension().
993*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000994llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
995 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
996
997 // Early exit if a defining object has already been generated.
998 if (Entry && Entry->hasInitializer())
999 return Entry;
1000
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001001 // FIXME: I don't understand why gcc generates this, or where it is
1002 // resolved. Investigate. Its also wasteful to look this up over and
1003 // over.
1004 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1005
Chris Lattner8ec03f52008-11-24 03:54:41 +00001006 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001007
1008 // Construct method lists.
1009 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1010 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1011 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1012 e = PD->instmeth_end(); i != e; ++i) {
1013 ObjCMethodDecl *MD = *i;
1014 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1015 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1016 OptInstanceMethods.push_back(C);
1017 } else {
1018 InstanceMethods.push_back(C);
1019 }
1020 }
1021
1022 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1023 e = PD->classmeth_end(); i != e; ++i) {
1024 ObjCMethodDecl *MD = *i;
1025 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1026 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1027 OptClassMethods.push_back(C);
1028 } else {
1029 ClassMethods.push_back(C);
1030 }
1031 }
1032
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001033 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001034 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001035 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001036 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001037 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001038 PD->protocol_begin(),
1039 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001040 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001041 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1042 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001043 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1044 InstanceMethods);
1045 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001046 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1047 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001048 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1049 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001050 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1051 Values);
1052
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001053 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001054 // Already created, fix the linkage and update the initializer.
1055 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001056 Entry->setInitializer(Init);
1057 } else {
1058 Entry =
1059 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1060 llvm::GlobalValue::InternalLinkage,
1061 Init,
1062 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1063 &CGM.getModule());
1064 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1065 UsedGlobals.push_back(Entry);
1066 // FIXME: Is this necessary? Why only for protocol?
1067 Entry->setAlignment(4);
1068 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001069
1070 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001071}
1072
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001073llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1075
1076 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001077 // We use the initializer as a marker of whether this is a forward
1078 // reference or not. At module finalization we add the empty
1079 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001080 Entry =
1081 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001082 llvm::GlobalValue::ExternalLinkage,
1083 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001084 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001085 &CGM.getModule());
1086 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1087 UsedGlobals.push_back(Entry);
1088 // FIXME: Is this necessary? Why only for protocol?
1089 Entry->setAlignment(4);
1090 }
1091
1092 return Entry;
1093}
1094
1095/*
1096 struct _objc_protocol_extension {
1097 uint32_t size;
1098 struct objc_method_description_list *optional_instance_methods;
1099 struct objc_method_description_list *optional_class_methods;
1100 struct objc_property_list *instance_properties;
1101 };
1102*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103llvm::Constant *
1104CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1105 const ConstantVector &OptInstanceMethods,
1106 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001107 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001108 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001109 std::vector<llvm::Constant*> Values(4);
1110 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001111 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001112 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1113 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001114 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1115 OptInstanceMethods);
1116 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001117 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1118 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001119 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1120 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001121 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1122 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001123 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001124
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001125 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1127 Values[3]->isNullValue())
1128 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1129
1130 llvm::Constant *Init =
1131 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1132 llvm::GlobalVariable *GV =
1133 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1134 llvm::GlobalValue::InternalLinkage,
1135 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001136 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001137 &CGM.getModule());
1138 // No special section, but goes in llvm.used
1139 UsedGlobals.push_back(GV);
1140
1141 return GV;
1142}
1143
1144/*
1145 struct objc_protocol_list {
1146 struct objc_protocol_list *next;
1147 long count;
1148 Protocol *list[];
1149 };
1150*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001151llvm::Constant *
1152CGObjCMac::EmitProtocolList(const std::string &Name,
1153 ObjCProtocolDecl::protocol_iterator begin,
1154 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001155 std::vector<llvm::Constant*> ProtocolRefs;
1156
Daniel Dunbardbc933702008-08-21 21:57:41 +00001157 for (; begin != end; ++begin)
1158 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001159
1160 // Just return null for empty protocol lists
1161 if (ProtocolRefs.empty())
1162 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1163
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001164 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001165 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1166
1167 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001168 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001169 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1170 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1171 Values[2] =
1172 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1173 ProtocolRefs.size()),
1174 ProtocolRefs);
1175
1176 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1177 llvm::GlobalVariable *GV =
1178 new llvm::GlobalVariable(Init->getType(), false,
1179 llvm::GlobalValue::InternalLinkage,
1180 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001181 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001182 &CGM.getModule());
1183 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1184 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1185}
1186
1187/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001188 struct _objc_property {
1189 const char * const name;
1190 const char * const attributes;
1191 };
1192
1193 struct _objc_property_list {
1194 uint32_t entsize; // sizeof (struct _objc_property)
1195 uint32_t prop_count;
1196 struct _objc_property[prop_count];
1197 };
1198*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001199llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1200 const Decl *Container,
1201 const ObjCContainerDecl *OCD,
1202 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001203 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001204 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1205 E = OCD->prop_end(); I != E; ++I) {
1206 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001207 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001208 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001209 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1210 Prop));
1211 }
1212
1213 // Return null for empty list.
1214 if (Properties.empty())
1215 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1216
1217 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001218 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001219 std::vector<llvm::Constant*> Values(3);
1220 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1221 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1222 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1223 Properties.size());
1224 Values[2] = llvm::ConstantArray::get(AT, Properties);
1225 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1226
1227 llvm::GlobalVariable *GV =
1228 new llvm::GlobalVariable(Init->getType(), false,
1229 llvm::GlobalValue::InternalLinkage,
1230 Init,
1231 Name,
1232 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001233 if (ObjCABI == 2)
1234 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001235 // No special section on property lists?
1236 UsedGlobals.push_back(GV);
1237 return llvm::ConstantExpr::getBitCast(GV,
1238 ObjCTypes.PropertyListPtrTy);
1239
1240}
1241
1242/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 struct objc_method_description_list {
1244 int count;
1245 struct objc_method_description list[];
1246 };
1247*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001248llvm::Constant *
1249CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1250 std::vector<llvm::Constant*> Desc(2);
1251 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1252 ObjCTypes.SelectorPtrTy);
1253 Desc[1] = GetMethodVarType(MD);
1254 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1255 Desc);
1256}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001258llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1259 const char *Section,
1260 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 // Return null for empty list.
1262 if (Methods.empty())
1263 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1264
1265 std::vector<llvm::Constant*> Values(2);
1266 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1267 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1268 Methods.size());
1269 Values[1] = llvm::ConstantArray::get(AT, Methods);
1270 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1271
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001272 llvm::GlobalVariable *GV =
1273 new llvm::GlobalVariable(Init->getType(), false,
1274 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001275 Init, Name, &CGM.getModule());
1276 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001277 UsedGlobals.push_back(GV);
1278 return llvm::ConstantExpr::getBitCast(GV,
1279 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001280}
1281
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001282/*
1283 struct _objc_category {
1284 char *category_name;
1285 char *class_name;
1286 struct _objc_method_list *instance_methods;
1287 struct _objc_method_list *class_methods;
1288 struct _objc_protocol_list *protocols;
1289 uint32_t size; // <rdar://4585769>
1290 struct _objc_property_list *instance_properties;
1291 };
1292 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001293void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001294 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001295
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001296 // FIXME: This is poor design, the OCD should have a pointer to the
1297 // category decl. Additionally, note that Category can be null for
1298 // the @implementation w/o an @interface case. Sema should just
1299 // create one for us as it does for @implementation so everyone else
1300 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001301 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001302 const ObjCCategoryDecl *Category =
1303 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001304 std::string ExtName(Interface->getNameAsString() + "_" +
1305 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001306
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001307 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1308 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1309 e = OCD->instmeth_end(); i != e; ++i) {
1310 // Instance methods should always be defined.
1311 InstanceMethods.push_back(GetMethodConstant(*i));
1312 }
1313 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1314 e = OCD->classmeth_end(); i != e; ++i) {
1315 // Class methods should always be defined.
1316 ClassMethods.push_back(GetMethodConstant(*i));
1317 }
1318
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001319 std::vector<llvm::Constant*> Values(7);
1320 Values[0] = GetClassName(OCD->getIdentifier());
1321 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001322 Values[2] =
1323 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1324 ExtName,
1325 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001326 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001327 Values[3] =
1328 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1329 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001330 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001331 if (Category) {
1332 Values[4] =
1333 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1334 Category->protocol_begin(),
1335 Category->protocol_end());
1336 } else {
1337 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1338 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001339 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001340
1341 // If there is no category @interface then there can be no properties.
1342 if (Category) {
1343 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001344 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001345 } else {
1346 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1347 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001348
1349 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1350 Values);
1351
1352 llvm::GlobalVariable *GV =
1353 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1354 llvm::GlobalValue::InternalLinkage,
1355 Init,
1356 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1357 &CGM.getModule());
1358 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1359 UsedGlobals.push_back(GV);
1360 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001361}
1362
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001363// FIXME: Get from somewhere?
1364enum ClassFlags {
1365 eClassFlags_Factory = 0x00001,
1366 eClassFlags_Meta = 0x00002,
1367 // <rdr://5142207>
1368 eClassFlags_HasCXXStructors = 0x02000,
1369 eClassFlags_Hidden = 0x20000,
1370 eClassFlags_ABI2_Hidden = 0x00010,
1371 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1372};
1373
1374// <rdr://5142207&4705298&4843145>
1375static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1376 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1377 // FIXME: Support -fvisibility
1378 switch (attr->getVisibility()) {
1379 default:
1380 assert(0 && "Unknown visibility");
1381 return false;
1382 case VisibilityAttr::DefaultVisibility:
1383 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1384 return false;
1385 case VisibilityAttr::HiddenVisibility:
1386 return true;
1387 }
1388 } else {
1389 return false; // FIXME: Support -fvisibility
1390 }
1391}
1392
1393/*
1394 struct _objc_class {
1395 Class isa;
1396 Class super_class;
1397 const char *name;
1398 long version;
1399 long info;
1400 long instance_size;
1401 struct _objc_ivar_list *ivars;
1402 struct _objc_method_list *methods;
1403 struct _objc_cache *cache;
1404 struct _objc_protocol_list *protocols;
1405 // Objective-C 1.0 extensions (<rdr://4585769>)
1406 const char *ivar_layout;
1407 struct _objc_class_ext *ext;
1408 };
1409
1410 See EmitClassExtension();
1411 */
1412void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001413 DefinedSymbols.insert(ID->getIdentifier());
1414
Chris Lattner8ec03f52008-11-24 03:54:41 +00001415 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001416 // FIXME: Gross
1417 ObjCInterfaceDecl *Interface =
1418 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001419 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001420 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001421 Interface->protocol_begin(),
1422 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001423 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001424 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001425 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001426 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427
1428 // FIXME: Set CXX-structors flag.
1429 if (IsClassHidden(ID->getClassInterface()))
1430 Flags |= eClassFlags_Hidden;
1431
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001432 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1433 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1434 e = ID->instmeth_end(); i != e; ++i) {
1435 // Instance methods should always be defined.
1436 InstanceMethods.push_back(GetMethodConstant(*i));
1437 }
1438 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1439 e = ID->classmeth_end(); i != e; ++i) {
1440 // Class methods should always be defined.
1441 ClassMethods.push_back(GetMethodConstant(*i));
1442 }
1443
1444 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1445 e = ID->propimpl_end(); i != e; ++i) {
1446 ObjCPropertyImplDecl *PID = *i;
1447
1448 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1449 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1450
1451 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1452 if (llvm::Constant *C = GetMethodConstant(MD))
1453 InstanceMethods.push_back(C);
1454 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1455 if (llvm::Constant *C = GetMethodConstant(MD))
1456 InstanceMethods.push_back(C);
1457 }
1458 }
1459
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001460 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001461 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001462 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001463 // Record a reference to the super class.
1464 LazySymbols.insert(Super->getIdentifier());
1465
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 Values[ 1] =
1467 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1468 ObjCTypes.ClassPtrTy);
1469 } else {
1470 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1471 }
1472 Values[ 2] = GetClassName(ID->getIdentifier());
1473 // Version is always 0.
1474 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1475 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1476 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001477 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001478 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001479 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001480 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001481 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001482 // cache is always NULL.
1483 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1484 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001485 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001486 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001487 Values[11] = EmitClassExtension(ID);
1488 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1489 Values);
1490
1491 llvm::GlobalVariable *GV =
1492 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1493 llvm::GlobalValue::InternalLinkage,
1494 Init,
1495 std::string("\01L_OBJC_CLASS_")+ClassName,
1496 &CGM.getModule());
1497 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1498 UsedGlobals.push_back(GV);
1499 // FIXME: Why?
1500 GV->setAlignment(32);
1501 DefinedClasses.push_back(GV);
1502}
1503
1504llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1505 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001506 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001507 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001509 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001510
1511 if (IsClassHidden(ID->getClassInterface()))
1512 Flags |= eClassFlags_Hidden;
1513
1514 std::vector<llvm::Constant*> Values(12);
1515 // The isa for the metaclass is the root of the hierarchy.
1516 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1517 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1518 Root = Super;
1519 Values[ 0] =
1520 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1521 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001522 // The super class for the metaclass is emitted as the name of the
1523 // super class. The runtime fixes this up to point to the
1524 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001525 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1526 Values[ 1] =
1527 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1528 ObjCTypes.ClassPtrTy);
1529 } else {
1530 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1531 }
1532 Values[ 2] = GetClassName(ID->getIdentifier());
1533 // Version is always 0.
1534 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1535 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1536 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001537 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001538 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001539 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001540 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001541 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001542 // cache is always NULL.
1543 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1544 Values[ 9] = Protocols;
1545 // ivar_layout for metaclass is always NULL.
1546 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1547 // The class extension is always unused for metaclasses.
1548 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1549 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1550 Values);
1551
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001552 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001553 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001554
1555 // Check for a forward reference.
1556 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1557 if (GV) {
1558 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1559 "Forward metaclass reference has incorrect type.");
1560 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1561 GV->setInitializer(Init);
1562 } else {
1563 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1564 llvm::GlobalValue::InternalLinkage,
1565 Init, Name,
1566 &CGM.getModule());
1567 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1569 UsedGlobals.push_back(GV);
1570 // FIXME: Why?
1571 GV->setAlignment(32);
1572
1573 return GV;
1574}
1575
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001576llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001577 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001578
1579 // FIXME: Should we look these up somewhere other than the
1580 // module. Its a bit silly since we only generate these while
1581 // processing an implementation, so exactly one pointer would work
1582 // if know when we entered/exitted an implementation block.
1583
1584 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001585 // Previously, metaclass with internal linkage may have been defined.
1586 // pass 'true' as 2nd argument so it is returned.
1587 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001588 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1589 "Forward metaclass reference has incorrect type.");
1590 return GV;
1591 } else {
1592 // Generate as an external reference to keep a consistent
1593 // module. This will be patched up when we emit the metaclass.
1594 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1595 llvm::GlobalValue::ExternalLinkage,
1596 0,
1597 Name,
1598 &CGM.getModule());
1599 }
1600}
1601
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001602/*
1603 struct objc_class_ext {
1604 uint32_t size;
1605 const char *weak_ivar_layout;
1606 struct _objc_property_list *properties;
1607 };
1608*/
1609llvm::Constant *
1610CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1611 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001612 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613
1614 std::vector<llvm::Constant*> Values(3);
1615 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001616 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001617 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001618 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001619 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001620
1621 // Return null if no extension bits are used.
1622 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1623 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1624
1625 llvm::Constant *Init =
1626 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1627 llvm::GlobalVariable *GV =
1628 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1629 llvm::GlobalValue::InternalLinkage,
1630 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001631 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001632 &CGM.getModule());
1633 // No special section, but goes in llvm.used
1634 UsedGlobals.push_back(GV);
1635
1636 return GV;
1637}
1638
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001639/// countInheritedIvars - count number of ivars in class and its super class(s)
1640///
1641static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1642 int count = 0;
1643 if (!OI)
1644 return 0;
1645 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1646 if (SuperClass)
1647 count += countInheritedIvars(SuperClass);
1648 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1649 E = OI->ivar_end(); I != E; ++I)
1650 ++count;
1651 return count;
1652}
1653
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001654/// getInterfaceDeclForIvar - Get the interface declaration node where
1655/// this ivar is declared in.
1656/// FIXME. Ideally, this info should be in the ivar node. But currently
1657/// it is not and prevailing wisdom is that ASTs should not have more
1658/// info than is absolutely needed, even though this info reflects the
1659/// source language.
1660///
1661static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1662 const ObjCInterfaceDecl *OI,
1663 const ObjCIvarDecl *IVD) {
1664 if (!OI)
1665 return 0;
1666 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1667 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1668 E = OI->ivar_end(); I != E; ++I)
1669 if ((*I)->getIdentifier() == IVD->getIdentifier())
1670 return OI;
1671 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1672}
1673
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001674/*
1675 struct objc_ivar {
1676 char *ivar_name;
1677 char *ivar_type;
1678 int ivar_offset;
1679 };
1680
1681 struct objc_ivar_list {
1682 int ivar_count;
1683 struct objc_ivar list[count];
1684 };
1685 */
1686llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001687 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001688 std::vector<llvm::Constant*> Ivars, Ivar(3);
1689
1690 // When emitting the root class GCC emits ivar entries for the
1691 // actual class structure. It is not clear if we need to follow this
1692 // behavior; for now lets try and get away with not doing it. If so,
1693 // the cleanest solution would be to make up an ObjCInterfaceDecl
1694 // for the class.
1695 if (ForClass)
1696 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001697
1698 ObjCInterfaceDecl *OID =
1699 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1700 const llvm::Type *InterfaceTy =
1701 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001702 const llvm::StructLayout *Layout =
1703 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001704
1705 RecordDecl::field_iterator ifield, pfield;
1706 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001707 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1708 FieldDecl *Field = *ifield;
1709 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1710 getLLVMFieldNo(Field));
1711 if (Field->getIdentifier())
1712 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1713 else
1714 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001715 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001716 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001717 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001718 }
1719
1720 // Return null for empty list.
1721 if (Ivars.empty())
1722 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1723
1724 std::vector<llvm::Constant*> Values(2);
1725 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1726 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1727 Ivars.size());
1728 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1729 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1730
1731 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1732 "\01L_OBJC_INSTANCE_VARIABLES_");
1733 llvm::GlobalVariable *GV =
1734 new llvm::GlobalVariable(Init->getType(), false,
1735 llvm::GlobalValue::InternalLinkage,
1736 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001737 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001738 &CGM.getModule());
1739 if (ForClass) {
1740 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1741 // FIXME: Why is this only here?
1742 GV->setAlignment(32);
1743 } else {
1744 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1745 }
1746 UsedGlobals.push_back(GV);
1747 return llvm::ConstantExpr::getBitCast(GV,
1748 ObjCTypes.IvarListPtrTy);
1749}
1750
1751/*
1752 struct objc_method {
1753 SEL method_name;
1754 char *method_types;
1755 void *method;
1756 };
1757
1758 struct objc_method_list {
1759 struct objc_method_list *obsolete;
1760 int count;
1761 struct objc_method methods_list[count];
1762 };
1763*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001764
1765/// GetMethodConstant - Return a struct objc_method constant for the
1766/// given method if it has been defined. The result is null if the
1767/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001768llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001769 // FIXME: Use DenseMap::lookup
1770 llvm::Function *Fn = MethodDefinitions[MD];
1771 if (!Fn)
1772 return 0;
1773
1774 std::vector<llvm::Constant*> Method(3);
1775 Method[0] =
1776 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1777 ObjCTypes.SelectorPtrTy);
1778 Method[1] = GetMethodVarType(MD);
1779 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1780 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1781}
1782
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001783llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1784 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001785 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001786 // Return null for empty list.
1787 if (Methods.empty())
1788 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1789
1790 std::vector<llvm::Constant*> Values(3);
1791 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1792 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1793 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1794 Methods.size());
1795 Values[2] = llvm::ConstantArray::get(AT, Methods);
1796 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1797
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001798 llvm::GlobalVariable *GV =
1799 new llvm::GlobalVariable(Init->getType(), false,
1800 llvm::GlobalValue::InternalLinkage,
1801 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001802 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001803 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001804 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001805 UsedGlobals.push_back(GV);
1806 return llvm::ConstantExpr::getBitCast(GV,
1807 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001808}
1809
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001810llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001811 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001812 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001813 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001814
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001815 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001816 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001817 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001818 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001819 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001820 llvm::GlobalValue::InternalLinkage,
1821 Name,
1822 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001823 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001824
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001825 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001826}
1827
1828llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001829 // Abuse this interface function as a place to finalize.
1830 FinishModule();
1831
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001832 return NULL;
1833}
1834
Daniel Dunbar49f66022008-09-24 03:38:44 +00001835llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1836 return ObjCTypes.GetPropertyFn;
1837}
1838
1839llvm::Function *CGObjCMac::GetPropertySetFunction() {
1840 return ObjCTypes.SetPropertyFn;
1841}
1842
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001843llvm::Function *CGObjCMac::EnumerationMutationFunction()
1844{
1845 return ObjCTypes.EnumerationMutationFn;
1846}
1847
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001848/*
1849
1850Objective-C setjmp-longjmp (sjlj) Exception Handling
1851--
1852
1853The basic framework for a @try-catch-finally is as follows:
1854{
1855 objc_exception_data d;
1856 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001857 bool _call_try_exit = true;
1858
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001859 objc_exception_try_enter(&d);
1860 if (!setjmp(d.jmp_buf)) {
1861 ... try body ...
1862 } else {
1863 // exception path
1864 id _caught = objc_exception_extract(&d);
1865
1866 // enter new try scope for handlers
1867 if (!setjmp(d.jmp_buf)) {
1868 ... match exception and execute catch blocks ...
1869
1870 // fell off end, rethrow.
1871 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001872 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001873 } else {
1874 // exception in catch block
1875 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001876 _call_try_exit = false;
1877 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001878 }
1879 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001880 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001881
1882finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001883 if (_call_try_exit)
1884 objc_exception_try_exit(&d);
1885
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001886 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001887 ... dispatch to finally destination ...
1888
1889finally_rethrow:
1890 objc_exception_throw(_rethrow);
1891
1892finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001893}
1894
1895This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001896uses _rethrow to determine if objc_exception_try_exit should be called
1897and if the object should be rethrown. This breaks in the face of
1898throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001899
1900We specialize this framework for a few particular circumstances:
1901
1902 - If there are no catch blocks, then we avoid emitting the second
1903 exception handling context.
1904
1905 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1906 e)) we avoid emitting the code to rethrow an uncaught exception.
1907
1908 - FIXME: If there is no @finally block we can do a few more
1909 simplifications.
1910
1911Rethrows and Jumps-Through-Finally
1912--
1913
1914Support for implicit rethrows and jumping through the finally block is
1915handled by storing the current exception-handling context in
1916ObjCEHStack.
1917
Daniel Dunbar898d5082008-09-30 01:06:03 +00001918In order to implement proper @finally semantics, we support one basic
1919mechanism for jumping through the finally block to an arbitrary
1920destination. Constructs which generate exits from a @try or @catch
1921block use this mechanism to implement the proper semantics by chaining
1922jumps, as necessary.
1923
1924This mechanism works like the one used for indirect goto: we
1925arbitrarily assign an ID to each destination and store the ID for the
1926destination in a variable prior to entering the finally block. At the
1927end of the finally block we simply create a switch to the proper
1928destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001929
1930Code gen for @synchronized(expr) stmt;
1931Effectively generating code for:
1932objc_sync_enter(expr);
1933@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001934*/
1935
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001936void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1937 const Stmt &S) {
1938 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001939 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001940 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001941 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001942 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1943 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1944 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001945
1946 // For @synchronized, call objc_sync_enter(sync.expr). The
1947 // evaluation of the expression must occur before we enter the
1948 // @synchronized. We can safely avoid a temp here because jumps into
1949 // @synchronized are illegal & this will dominate uses.
1950 llvm::Value *SyncArg = 0;
1951 if (!isTry) {
1952 SyncArg =
1953 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1954 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1955 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1956 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001957
1958 // Push an EH context entry, used for handling rethrows and jumps
1959 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001960 CGF.PushCleanupBlock(FinallyBlock);
1961
Anders Carlsson273558f2009-02-07 21:37:21 +00001962 CGF.ObjCEHValueStack.push_back(0);
1963
Daniel Dunbar898d5082008-09-30 01:06:03 +00001964 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001965 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1966 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001967 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1968 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001969 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1970 "_call_try_exit");
1971 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1972
Anders Carlsson80f25672008-09-09 17:59:25 +00001973 // Enter a new try block and call setjmp.
1974 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1975 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1976 "jmpbufarray");
1977 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1978 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1979 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001980
Daniel Dunbar55e87422008-11-11 02:29:29 +00001981 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1982 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001983 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001984 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001985
1986 // Emit the @try block.
1987 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001988 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1989 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001990 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001991
1992 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001993 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001994
1995 // Retrieve the exception object. We may emit multiple blocks but
1996 // nothing can cross this so the value is already in SSA form.
1997 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1998 ExceptionData,
1999 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002000 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002001 if (!isTry)
2002 {
2003 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002004 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002005 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002006 }
2007 else if (const ObjCAtCatchStmt* CatchStmt =
2008 cast<ObjCAtTryStmt>(S).getCatchStmts())
2009 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002010 // Enter a new exception try block (in case a @catch block throws
2011 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002012 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002013
Anders Carlsson80f25672008-09-09 17:59:25 +00002014 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2015 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002016 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002017
Daniel Dunbar55e87422008-11-11 02:29:29 +00002018 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2019 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002020 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002021
2022 CGF.EmitBlock(CatchBlock);
2023
Daniel Dunbar55e40722008-09-27 07:03:52 +00002024 // Handle catch list. As a special case we check if everything is
2025 // matched and avoid generating code for falling off the end if
2026 // so.
2027 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002028 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002029 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002030
Steve Naroff7ba138a2009-03-03 19:52:17 +00002031 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002032 const PointerType *PT = 0;
2033
Anders Carlsson80f25672008-09-09 17:59:25 +00002034 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002035 if (!CatchParam) {
2036 AllMatched = true;
2037 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002038 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002039
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002040 // catch(id e) always matches.
2041 // FIXME: For the time being we also match id<X>; this should
2042 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002043 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002044 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002045 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002046 }
2047
Daniel Dunbar55e40722008-09-27 07:03:52 +00002048 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002049 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002050 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002051 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002052 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002053 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002054
Anders Carlssondde0a942008-09-11 09:15:33 +00002055 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002056 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002057 break;
2058 }
2059
Daniel Dunbar129271a2008-09-27 07:36:24 +00002060 assert(PT && "Unexpected non-pointer type in @catch");
2061 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002062 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002063 assert(ObjCType && "Catch parameter must have Objective-C type!");
2064
2065 // Check if the @catch block matches the exception object.
2066 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2067
Anders Carlsson80f25672008-09-09 17:59:25 +00002068 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2069 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002070
Daniel Dunbar55e87422008-11-11 02:29:29 +00002071 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002072
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002073 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002074 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002075
2076 // Emit the @catch block.
2077 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002078 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002079 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002080
2081 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002082 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002083 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002084 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002085
2086 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002087 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002088
2089 CGF.EmitBlock(NextCatchBlock);
2090 }
2091
Daniel Dunbar55e40722008-09-27 07:03:52 +00002092 if (!AllMatched) {
2093 // None of the handlers caught the exception, so store it to be
2094 // rethrown at the end of the @finally block.
2095 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002096 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002097 }
2098
2099 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002100 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002101 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2102 ExceptionData),
2103 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002104 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002105 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002107 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002108 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002109 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 }
2111
Daniel Dunbar898d5082008-09-30 01:06:03 +00002112 // Pop the exception-handling stack entry. It is important to do
2113 // this now, because the code in the @finally block is not in this
2114 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002115 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2116
Anders Carlsson273558f2009-02-07 21:37:21 +00002117 CGF.ObjCEHValueStack.pop_back();
2118
Anders Carlsson80f25672008-09-09 17:59:25 +00002119 // Emit the @finally block.
2120 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002121 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2122
2123 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2124
2125 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002127
2128 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002129 if (isTry) {
2130 if (const ObjCAtFinallyStmt* FinallyStmt =
2131 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2132 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002133 } else {
2134 // Emit objc_sync_exit(expr); as finally's sole statement for
2135 // @synchronized.
2136 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002137 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002138
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002139 // Emit the switch block
2140 if (Info.SwitchBlock)
2141 CGF.EmitBlock(Info.SwitchBlock);
2142 if (Info.EndBlock)
2143 CGF.EmitBlock(Info.EndBlock);
2144
Daniel Dunbar898d5082008-09-30 01:06:03 +00002145 CGF.EmitBlock(FinallyRethrow);
2146 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2147 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002148 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002149
2150 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002151}
2152
2153void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002154 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002155 llvm::Value *ExceptionAsObject;
2156
2157 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2158 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2159 ExceptionAsObject =
2160 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2161 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002162 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002163 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002164 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002165 }
2166
2167 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002168 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002169
2170 // Clear the insertion point to indicate we are in unreachable code.
2171 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002172}
2173
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002174/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002175/// object: objc_read_weak (id *src)
2176///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002177llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002178 llvm::Value *AddrWeakObj)
2179{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002180 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002181 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002182 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002183 return read_weak;
2184}
2185
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002186/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2187/// objc_assign_weak (id src, id *dst)
2188///
2189void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2190 llvm::Value *src, llvm::Value *dst)
2191{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002192 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2193 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002194 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2195 src, dst, "weakassign");
2196 return;
2197}
2198
Fariborz Jahanian58626502008-11-19 00:59:10 +00002199/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2200/// objc_assign_global (id src, id *dst)
2201///
2202void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2203 llvm::Value *src, llvm::Value *dst)
2204{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002205 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2206 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002207 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2208 src, dst, "globalassign");
2209 return;
2210}
2211
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002212/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2213/// objc_assign_ivar (id src, id *dst)
2214///
2215void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2216 llvm::Value *src, llvm::Value *dst)
2217{
2218 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2219 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2220 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2221 src, dst, "assignivar");
2222 return;
2223}
2224
Fariborz Jahanian58626502008-11-19 00:59:10 +00002225/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2226/// objc_assign_strongCast (id src, id *dst)
2227///
2228void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2229 llvm::Value *src, llvm::Value *dst)
2230{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002231 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2232 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002233 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2234 src, dst, "weakassign");
2235 return;
2236}
2237
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002238/// EmitObjCValueForIvar - Code Gen for ivar reference.
2239///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002240LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2241 QualType ObjectTy,
2242 llvm::Value *BaseValue,
2243 const ObjCIvarDecl *Ivar,
2244 const FieldDecl *Field,
2245 unsigned CVRQualifiers) {
2246 if (Ivar->isBitField())
2247 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2248 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002249 // TODO: Add a special case for isa (index 0)
2250 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2251 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002252 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002253 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2254 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002255 LValue::SetObjCIvar(LV, true);
2256 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002257}
2258
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002259llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2260 ObjCInterfaceDecl *Interface,
2261 const ObjCIvarDecl *Ivar) {
2262 const llvm::Type *InterfaceLTy =
2263 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2264 const llvm::StructLayout *Layout =
2265 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2266 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2267 uint64_t Offset =
2268 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2269
2270 return llvm::ConstantInt::get(
2271 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2272 Offset);
2273}
2274
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002275/* *** Private Interface *** */
2276
2277/// EmitImageInfo - Emit the image info marker used to encode some module
2278/// level information.
2279///
2280/// See: <rdr://4810609&4810587&4810587>
2281/// struct IMAGE_INFO {
2282/// unsigned version;
2283/// unsigned flags;
2284/// };
2285enum ImageInfoFlags {
2286 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2287 eImageInfo_GarbageCollected = (1 << 1),
2288 eImageInfo_GCOnly = (1 << 2)
2289};
2290
2291void CGObjCMac::EmitImageInfo() {
2292 unsigned version = 0; // Version is unused?
2293 unsigned flags = 0;
2294
2295 // FIXME: Fix and continue?
2296 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2297 flags |= eImageInfo_GarbageCollected;
2298 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2299 flags |= eImageInfo_GCOnly;
2300
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002301 // Emitted as int[2];
2302 llvm::Constant *values[2] = {
2303 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2304 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2305 };
2306 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002307 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002308 new llvm::GlobalVariable(AT, true,
2309 llvm::GlobalValue::InternalLinkage,
2310 llvm::ConstantArray::get(AT, values, 2),
2311 "\01L_OBJC_IMAGE_INFO",
2312 &CGM.getModule());
2313
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002314 if (ObjCABI == 1) {
2315 GV->setSection("__OBJC, __image_info,regular");
2316 } else {
2317 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2318 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002319
2320 UsedGlobals.push_back(GV);
2321}
2322
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002323
2324// struct objc_module {
2325// unsigned long version;
2326// unsigned long size;
2327// const char *name;
2328// Symtab symtab;
2329// };
2330
2331// FIXME: Get from somewhere
2332static const int ModuleVersion = 7;
2333
2334void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002335 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002336
2337 std::vector<llvm::Constant*> Values(4);
2338 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2339 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002340 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002341 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002342 Values[3] = EmitModuleSymbols();
2343
2344 llvm::GlobalVariable *GV =
2345 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2346 llvm::GlobalValue::InternalLinkage,
2347 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2348 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002349 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002350 &CGM.getModule());
2351 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2352 UsedGlobals.push_back(GV);
2353}
2354
2355llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002356 unsigned NumClasses = DefinedClasses.size();
2357 unsigned NumCategories = DefinedCategories.size();
2358
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002359 // Return null if no symbols were defined.
2360 if (!NumClasses && !NumCategories)
2361 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2362
2363 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002364 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2365 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2366 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2367 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2368
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002369 // The runtime expects exactly the list of defined classes followed
2370 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002371 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002372 for (unsigned i=0; i<NumClasses; i++)
2373 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2374 ObjCTypes.Int8PtrTy);
2375 for (unsigned i=0; i<NumCategories; i++)
2376 Symbols[NumClasses + i] =
2377 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2378 ObjCTypes.Int8PtrTy);
2379
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002380 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002381 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002382 NumClasses + NumCategories),
2383 Symbols);
2384
2385 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2386
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002387 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002388 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002389 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002390 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002391 "\01L_OBJC_SYMBOLS",
2392 &CGM.getModule());
2393 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2394 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002395 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2396}
2397
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002398llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002399 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002400 LazySymbols.insert(ID->getIdentifier());
2401
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002402 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2403
2404 if (!Entry) {
2405 llvm::Constant *Casted =
2406 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2407 ObjCTypes.ClassPtrTy);
2408 Entry =
2409 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2410 llvm::GlobalValue::InternalLinkage,
2411 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2412 &CGM.getModule());
2413 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2414 UsedGlobals.push_back(Entry);
2415 }
2416
2417 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002418}
2419
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002420llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002421 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2422
2423 if (!Entry) {
2424 llvm::Constant *Casted =
2425 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2426 ObjCTypes.SelectorPtrTy);
2427 Entry =
2428 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2429 llvm::GlobalValue::InternalLinkage,
2430 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2431 &CGM.getModule());
2432 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2433 UsedGlobals.push_back(Entry);
2434 }
2435
2436 return Builder.CreateLoad(Entry, false, "tmp");
2437}
2438
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002439llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002440 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002441
2442 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002443 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002444 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002445 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002446 llvm::GlobalValue::InternalLinkage,
2447 C, "\01L_OBJC_CLASS_NAME_",
2448 &CGM.getModule());
2449 Entry->setSection("__TEXT,__cstring,cstring_literals");
2450 UsedGlobals.push_back(Entry);
2451 }
2452
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002453 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002454}
2455
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002456/// GetIvarLayoutName - Returns a unique constant for the given
2457/// ivar layout bitmap.
2458llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2459 const ObjCCommonTypesHelper &ObjCTypes) {
2460 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2461}
2462
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002463void CGObjCCommonMac::BuildAggrIvarLayout(RecordDecl *RD,
2464 const std::vector<FieldDecl*>& RecFields,
2465 unsigned int BytePos, bool ForStrongLayout,
2466 int &Index, int &SkIndex, bool &HasUnion) {
2467 return;
2468}
2469
2470/// BuildIvarLayout - Builds ivar layout bitmap for the class
2471/// implementation for the __strong or __weak case.
2472/// The layout map displays which words in ivar list must be skipped
2473/// and which must be scanned by GC (see below). String is built of bytes.
2474/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2475/// of words to skip and right nibble is count of words to scan. So, each
2476/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2477/// represented by a 0x00 byte which also ends the string.
2478/// 1. when ForStrongLayout is true, following ivars are scanned:
2479/// - id, Class
2480/// - object *
2481/// - __strong anything
2482///
2483/// 2. When ForStrongLayout is false, following ivars are scanned:
2484/// - __weak anything
2485///
2486llvm::Constant *CGObjCCommonMac::BuildIvarLayout(ObjCImplementationDecl *OMD,
2487 bool ForStrongLayout) {
2488 int iIndex = -1;
2489 int iSkIndex = -1;
2490 bool hasUnion = false;
2491
2492 std::vector<FieldDecl*> RecFields;
2493 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2494 CGM.getContext().CollectObjCIvars(OI, RecFields);
2495 if (RecFields.empty())
2496 return 0;
2497 BuildAggrIvarLayout (0, RecFields, 0, ForStrongLayout,
2498 iIndex, iSkIndex, hasUnion);
2499 return 0;
2500}
2501
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002502llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002503 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2504
2505 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002506 // FIXME: Avoid std::string copying.
2507 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002508 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002509 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002510 llvm::GlobalValue::InternalLinkage,
2511 C, "\01L_OBJC_METH_VAR_NAME_",
2512 &CGM.getModule());
2513 Entry->setSection("__TEXT,__cstring,cstring_literals");
2514 UsedGlobals.push_back(Entry);
2515 }
2516
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002517 return getConstantGEP(Entry, 0, 0);
2518}
2519
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002520// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002521llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002522 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2523}
2524
2525// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002526llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002527 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2528}
2529
Devang Patel7794bb82009-03-04 18:21:39 +00002530llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2531 std::string TypeStr;
2532 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2533
2534 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002535
2536 if (!Entry) {
Devang Patel7794bb82009-03-04 18:21:39 +00002537 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002538 Entry =
2539 new llvm::GlobalVariable(C->getType(), false,
2540 llvm::GlobalValue::InternalLinkage,
2541 C, "\01L_OBJC_METH_VAR_TYPE_",
2542 &CGM.getModule());
2543 Entry->setSection("__TEXT,__cstring,cstring_literals");
2544 UsedGlobals.push_back(Entry);
2545 }
2546
2547 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002548}
2549
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002550llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002551 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002552 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2553 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002554
2555 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2556
2557 if (!Entry) {
2558 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2559 Entry =
2560 new llvm::GlobalVariable(C->getType(), false,
2561 llvm::GlobalValue::InternalLinkage,
2562 C, "\01L_OBJC_METH_VAR_TYPE_",
2563 &CGM.getModule());
2564 Entry->setSection("__TEXT,__cstring,cstring_literals");
2565 UsedGlobals.push_back(Entry);
2566 }
2567
2568 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002569}
2570
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002571// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002572llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002573 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2574
2575 if (!Entry) {
2576 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2577 Entry =
2578 new llvm::GlobalVariable(C->getType(), false,
2579 llvm::GlobalValue::InternalLinkage,
2580 C, "\01L_OBJC_PROP_NAME_ATTR_",
2581 &CGM.getModule());
2582 Entry->setSection("__TEXT,__cstring,cstring_literals");
2583 UsedGlobals.push_back(Entry);
2584 }
2585
2586 return getConstantGEP(Entry, 0, 0);
2587}
2588
2589// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002590// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002591llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002592 const Decl *Container) {
2593 std::string TypeStr;
2594 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002595 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2596}
2597
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002598void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2599 const ObjCContainerDecl *CD,
2600 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002601 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002602 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002603 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002604 assert (CD && "Missing container decl in GetNameForMethod");
2605 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002606 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2607 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002608 NameOut += ' ';
2609 NameOut += D->getSelector().getAsString();
2610 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002611}
2612
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002613/// GetFirstIvarInRecord - This routine returns the record for the
2614/// implementation of the fiven class OID. It also returns field
2615/// corresponding to the first ivar in the class in FIV. It also
2616/// returns the one before the first ivar.
2617///
2618const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2619 const ObjCInterfaceDecl *OID,
2620 RecordDecl::field_iterator &FIV,
2621 RecordDecl::field_iterator &PIV) {
2622 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2623 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2624 RecordDecl::field_iterator ifield = RD->field_begin();
2625 RecordDecl::field_iterator pfield = RD->field_end();
2626 while (countSuperClassIvars-- > 0) {
2627 pfield = ifield;
2628 ++ifield;
2629 }
2630 FIV = ifield;
2631 PIV = pfield;
2632 return RD;
2633}
2634
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002635void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002636 EmitModuleInfo();
2637
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002638 // Emit the dummy bodies for any protocols which were referenced but
2639 // never defined.
2640 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2641 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2642 if (i->second->hasInitializer())
2643 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002644
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002645 std::vector<llvm::Constant*> Values(5);
2646 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2647 Values[1] = GetClassName(i->first);
2648 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2649 Values[3] = Values[4] =
2650 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2651 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2652 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2653 Values));
2654 }
2655
2656 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002657 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002658 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002659 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002660 }
2661
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002662 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002663 llvm::GlobalValue *GV =
2664 new llvm::GlobalVariable(AT, false,
2665 llvm::GlobalValue::AppendingLinkage,
2666 llvm::ConstantArray::get(AT, Used),
2667 "llvm.used",
2668 &CGM.getModule());
2669
2670 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002671
2672 // Add assembler directives to add lazy undefined symbol references
2673 // for classes which are referenced but not defined. This is
2674 // important for correct linker interaction.
2675
2676 // FIXME: Uh, this isn't particularly portable.
2677 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002678
2679 if (!CGM.getModule().getModuleInlineAsm().empty())
2680 s << "\n";
2681
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002682 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2683 e = LazySymbols.end(); i != e; ++i) {
2684 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2685 }
2686 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2687 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002688 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002689 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2690 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002691
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002692 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002693}
2694
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002695CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002696 : CGObjCCommonMac(cgm),
2697 ObjCTypes(cgm)
2698{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002699 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002700 ObjCABI = 2;
2701}
2702
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002703/* *** */
2704
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002705ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2706: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002707{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002708 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2709 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002710
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002711 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002712 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002713 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002714 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2715
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002716 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002717 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002718 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002719
2720 // FIXME: It would be nice to unify this with the opaque type, so
2721 // that the IR comes out a bit cleaner.
2722 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2723 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002724
2725 // I'm not sure I like this. The implicit coordination is a bit
2726 // gross. We should solve this in a reasonable fashion because this
2727 // is a pretty common task (match some runtime data structure with
2728 // an LLVM data structure).
2729
2730 // FIXME: This is leaked.
2731 // FIXME: Merge with rewriter code?
2732
2733 // struct _objc_super {
2734 // id self;
2735 // Class cls;
2736 // }
2737 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2738 SourceLocation(),
2739 &Ctx.Idents.get("_objc_super"));
2740 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2741 Ctx.getObjCIdType(), 0, false));
2742 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2743 Ctx.getObjCClassType(), 0, false));
2744 RD->completeDefinition(Ctx);
2745
2746 SuperCTy = Ctx.getTagDeclType(RD);
2747 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2748
2749 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002750 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2751
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002752 // struct _prop_t {
2753 // char *name;
2754 // char *attributes;
2755 // }
2756 PropertyTy = llvm::StructType::get(Int8PtrTy,
2757 Int8PtrTy,
2758 NULL);
2759 CGM.getModule().addTypeName("struct._prop_t",
2760 PropertyTy);
2761
2762 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002763 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002764 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002765 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002766 // }
2767 PropertyListTy = llvm::StructType::get(IntTy,
2768 IntTy,
2769 llvm::ArrayType::get(PropertyTy, 0),
2770 NULL);
2771 CGM.getModule().addTypeName("struct._prop_list_t",
2772 PropertyListTy);
2773 // struct _prop_list_t *
2774 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2775
2776 // struct _objc_method {
2777 // SEL _cmd;
2778 // char *method_type;
2779 // char *_imp;
2780 // }
2781 MethodTy = llvm::StructType::get(SelectorPtrTy,
2782 Int8PtrTy,
2783 Int8PtrTy,
2784 NULL);
2785 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002786
2787 // struct _objc_cache *
2788 CacheTy = llvm::OpaqueType::get();
2789 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2790 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002791
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002792 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002793
2794 QualType IdType = Ctx.getObjCIdType();
2795 QualType SelType = Ctx.getObjCSelType();
2796 llvm::SmallVector<QualType,16> Params;
2797 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002798
2799 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002800 Params.push_back(IdType);
2801 Params.push_back(SelType);
2802 Params.push_back(Ctx.LongTy);
2803 Params.push_back(Ctx.BoolTy);
2804 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2805 false);
2806 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002807
2808 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2809 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002810 Params.push_back(IdType);
2811 Params.push_back(SelType);
2812 Params.push_back(Ctx.LongTy);
2813 Params.push_back(IdType);
2814 Params.push_back(Ctx.BoolTy);
2815 Params.push_back(Ctx.BoolTy);
2816 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2817 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2818
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002819 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002820
2821 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002822 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002823 Params.push_back(IdType);
2824 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2825 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2826 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002827
2828 // gc's API
2829 // id objc_read_weak (id *)
2830 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002831 Params.push_back(Ctx.getPointerType(IdType));
2832 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2833 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2834
2835 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002836 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002837 Params.push_back(IdType);
2838 Params.push_back(Ctx.getPointerType(IdType));
2839
2840 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2841 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2842 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2843 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2844 GcAssignStrongCastFn =
2845 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002846
2847 // void objc_exception_throw(id)
2848 Params.clear();
2849 Params.push_back(IdType);
2850
2851 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002852 ExceptionThrowFn =
2853 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002854
2855 // synchronized APIs
2856 // void objc_sync_enter (id)
2857 // void objc_sync_exit (id)
2858 Params.clear();
2859 Params.push_back(IdType);
2860
2861 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2862 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2863 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002864}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002865
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002866ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2867 : ObjCCommonTypesHelper(cgm)
2868{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002869 // struct _objc_method_description {
2870 // SEL name;
2871 // char *types;
2872 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002873 MethodDescriptionTy =
2874 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002875 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002876 NULL);
2877 CGM.getModule().addTypeName("struct._objc_method_description",
2878 MethodDescriptionTy);
2879
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002880 // struct _objc_method_description_list {
2881 // int count;
2882 // struct _objc_method_description[1];
2883 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002884 MethodDescriptionListTy =
2885 llvm::StructType::get(IntTy,
2886 llvm::ArrayType::get(MethodDescriptionTy, 0),
2887 NULL);
2888 CGM.getModule().addTypeName("struct._objc_method_description_list",
2889 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002890
2891 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002892 MethodDescriptionListPtrTy =
2893 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2894
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002895 // Protocol description structures
2896
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002897 // struct _objc_protocol_extension {
2898 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2899 // struct _objc_method_description_list *optional_instance_methods;
2900 // struct _objc_method_description_list *optional_class_methods;
2901 // struct _objc_property_list *instance_properties;
2902 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002903 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002904 llvm::StructType::get(IntTy,
2905 MethodDescriptionListPtrTy,
2906 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002907 PropertyListPtrTy,
2908 NULL);
2909 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2910 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002911
2912 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002913 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2914
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002915 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002916
2917 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2918 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2919
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002920 const llvm::Type *T =
2921 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2922 LongTy,
2923 llvm::ArrayType::get(ProtocolTyHolder, 0),
2924 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002925 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2926
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002927 // struct _objc_protocol {
2928 // struct _objc_protocol_extension *isa;
2929 // char *protocol_name;
2930 // struct _objc_protocol **_objc_protocol_list;
2931 // struct _objc_method_description_list *instance_methods;
2932 // struct _objc_method_description_list *class_methods;
2933 // }
2934 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002935 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002936 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2937 MethodDescriptionListPtrTy,
2938 MethodDescriptionListPtrTy,
2939 NULL);
2940 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2941
2942 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2943 CGM.getModule().addTypeName("struct._objc_protocol_list",
2944 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002945 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002946 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2947
2948 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002949 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002950 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002951
2952 // Class description structures
2953
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002954 // struct _objc_ivar {
2955 // char *ivar_name;
2956 // char *ivar_type;
2957 // int ivar_offset;
2958 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002959 IvarTy = llvm::StructType::get(Int8PtrTy,
2960 Int8PtrTy,
2961 IntTy,
2962 NULL);
2963 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2964
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002965 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002966 IvarListTy = llvm::OpaqueType::get();
2967 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2968 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2969
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002970 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002971 MethodListTy = llvm::OpaqueType::get();
2972 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2973 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2974
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002975 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002976 ClassExtensionTy =
2977 llvm::StructType::get(IntTy,
2978 Int8PtrTy,
2979 PropertyListPtrTy,
2980 NULL);
2981 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2982 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2983
2984 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2985
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002986 // struct _objc_class {
2987 // Class isa;
2988 // Class super_class;
2989 // char *name;
2990 // long version;
2991 // long info;
2992 // long instance_size;
2993 // struct _objc_ivar_list *ivars;
2994 // struct _objc_method_list *methods;
2995 // struct _objc_cache *cache;
2996 // struct _objc_protocol_list *protocols;
2997 // char *ivar_layout;
2998 // struct _objc_class_ext *ext;
2999 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003000 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3001 llvm::PointerType::getUnqual(ClassTyHolder),
3002 Int8PtrTy,
3003 LongTy,
3004 LongTy,
3005 LongTy,
3006 IvarListPtrTy,
3007 MethodListPtrTy,
3008 CachePtrTy,
3009 ProtocolListPtrTy,
3010 Int8PtrTy,
3011 ClassExtensionPtrTy,
3012 NULL);
3013 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3014
3015 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3016 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3017 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3018
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003019 // struct _objc_category {
3020 // char *category_name;
3021 // char *class_name;
3022 // struct _objc_method_list *instance_method;
3023 // struct _objc_method_list *class_method;
3024 // uint32_t size; // sizeof(struct _objc_category)
3025 // struct _objc_property_list *instance_properties;// category's @property
3026 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003027 CategoryTy = llvm::StructType::get(Int8PtrTy,
3028 Int8PtrTy,
3029 MethodListPtrTy,
3030 MethodListPtrTy,
3031 ProtocolListPtrTy,
3032 IntTy,
3033 PropertyListPtrTy,
3034 NULL);
3035 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3036
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003037 // Global metadata structures
3038
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003039 // struct _objc_symtab {
3040 // long sel_ref_cnt;
3041 // SEL *refs;
3042 // short cls_def_cnt;
3043 // short cat_def_cnt;
3044 // char *defs[cls_def_cnt + cat_def_cnt];
3045 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003046 SymtabTy = llvm::StructType::get(LongTy,
3047 SelectorPtrTy,
3048 ShortTy,
3049 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003050 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003051 NULL);
3052 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3053 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3054
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003055 // struct _objc_module {
3056 // long version;
3057 // long size; // sizeof(struct _objc_module)
3058 // char *name;
3059 // struct _objc_symtab* symtab;
3060 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003061 ModuleTy =
3062 llvm::StructType::get(LongTy,
3063 LongTy,
3064 Int8PtrTy,
3065 SymtabPtrTy,
3066 NULL);
3067 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003068
Daniel Dunbar49f66022008-09-24 03:38:44 +00003069 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003070
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003071 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003072 std::vector<const llvm::Type*> Params;
3073 Params.push_back(ObjectPtrTy);
3074 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003075 MessageSendFn =
3076 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3077 Params,
3078 true),
3079 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003080
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003081 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003082 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003083 Params.push_back(ObjectPtrTy);
3084 Params.push_back(SelectorPtrTy);
3085 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003086 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3087 Params,
3088 true),
3089 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003090
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003091 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003092 Params.clear();
3093 Params.push_back(ObjectPtrTy);
3094 Params.push_back(SelectorPtrTy);
3095 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003096 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003097 MessageSendFpretFn =
3098 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3099 Params,
3100 true),
3101 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003102
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003103 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003104 Params.clear();
3105 Params.push_back(SuperPtrTy);
3106 Params.push_back(SelectorPtrTy);
3107 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003108 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3109 Params,
3110 true),
3111 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003112
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003113 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3114 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003115 Params.clear();
3116 Params.push_back(Int8PtrTy);
3117 Params.push_back(SuperPtrTy);
3118 Params.push_back(SelectorPtrTy);
3119 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003120 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3121 Params,
3122 true),
3123 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003124
3125 // There is no objc_msgSendSuper_fpret? How can that work?
3126 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003127
Anders Carlsson124526b2008-09-09 10:10:21 +00003128 // FIXME: This is the size of the setjmp buffer and should be
3129 // target specific. 18 is what's used on 32-bit X86.
3130 uint64_t SetJmpBufferSize = 18;
3131
3132 // Exceptions
3133 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003134 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003135
3136 ExceptionDataTy =
3137 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3138 SetJmpBufferSize),
3139 StackPtrTy, NULL);
3140 CGM.getModule().addTypeName("struct._objc_exception_data",
3141 ExceptionDataTy);
3142
3143 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003144 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3145 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003146 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3147 Params,
3148 false),
3149 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003150 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003151 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3152 Params,
3153 false),
3154 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003155 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003156 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3157 Params,
3158 false),
3159 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003160
3161 Params.clear();
3162 Params.push_back(ClassPtrTy);
3163 Params.push_back(ObjectPtrTy);
3164 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003165 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3166 Params,
3167 false),
3168 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003169
Anders Carlsson124526b2008-09-09 10:10:21 +00003170 Params.clear();
3171 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3172 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003173 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3174 Params,
3175 false),
3176 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003177
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003178}
3179
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003180ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003181: ObjCCommonTypesHelper(cgm)
3182{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003183 // struct _method_list_t {
3184 // uint32_t entsize; // sizeof(struct _objc_method)
3185 // uint32_t method_count;
3186 // struct _objc_method method_list[method_count];
3187 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003188 MethodListnfABITy = llvm::StructType::get(IntTy,
3189 IntTy,
3190 llvm::ArrayType::get(MethodTy, 0),
3191 NULL);
3192 CGM.getModule().addTypeName("struct.__method_list_t",
3193 MethodListnfABITy);
3194 // struct method_list_t *
3195 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003196
3197 // struct _protocol_t {
3198 // id isa; // NULL
3199 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003200 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003201 // const struct method_list_t * const instance_methods;
3202 // const struct method_list_t * const class_methods;
3203 // const struct method_list_t *optionalInstanceMethods;
3204 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003205 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003206 // const uint32_t size; // sizeof(struct _protocol_t)
3207 // const uint32_t flags; // = 0
3208 // }
3209
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003210 // Holder for struct _protocol_list_t *
3211 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3212
3213 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3214 Int8PtrTy,
3215 llvm::PointerType::getUnqual(
3216 ProtocolListTyHolder),
3217 MethodListnfABIPtrTy,
3218 MethodListnfABIPtrTy,
3219 MethodListnfABIPtrTy,
3220 MethodListnfABIPtrTy,
3221 PropertyListPtrTy,
3222 IntTy,
3223 IntTy,
3224 NULL);
3225 CGM.getModule().addTypeName("struct._protocol_t",
3226 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003227
3228 // struct _protocol_t*
3229 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003230
Fariborz Jahanianda320092009-01-29 19:24:30 +00003231 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003232 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003233 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003234 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003235 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3236 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003237 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003238 NULL);
3239 CGM.getModule().addTypeName("struct._objc_protocol_list",
3240 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003241 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3242 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003243
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003244 // struct _objc_protocol_list*
3245 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003246
3247 // struct _ivar_t {
3248 // unsigned long int *offset; // pointer to ivar offset location
3249 // char *name;
3250 // char *type;
3251 // uint32_t alignment;
3252 // uint32_t size;
3253 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003254 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3255 Int8PtrTy,
3256 Int8PtrTy,
3257 IntTy,
3258 IntTy,
3259 NULL);
3260 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3261
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003262 // struct _ivar_list_t {
3263 // uint32 entsize; // sizeof(struct _ivar_t)
3264 // uint32 count;
3265 // struct _iver_t list[count];
3266 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003267 IvarListnfABITy = llvm::StructType::get(IntTy,
3268 IntTy,
3269 llvm::ArrayType::get(
3270 IvarnfABITy, 0),
3271 NULL);
3272 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3273
3274 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003275
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003276 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003277 // uint32_t const flags;
3278 // uint32_t const instanceStart;
3279 // uint32_t const instanceSize;
3280 // uint32_t const reserved; // only when building for 64bit targets
3281 // const uint8_t * const ivarLayout;
3282 // const char *const name;
3283 // const struct _method_list_t * const baseMethods;
3284 // const struct _objc_protocol_list *const baseProtocols;
3285 // const struct _ivar_list_t *const ivars;
3286 // const uint8_t * const weakIvarLayout;
3287 // const struct _prop_list_t * const properties;
3288 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003289
3290 // FIXME. Add 'reserved' field in 64bit abi mode!
3291 ClassRonfABITy = llvm::StructType::get(IntTy,
3292 IntTy,
3293 IntTy,
3294 Int8PtrTy,
3295 Int8PtrTy,
3296 MethodListnfABIPtrTy,
3297 ProtocolListnfABIPtrTy,
3298 IvarListnfABIPtrTy,
3299 Int8PtrTy,
3300 PropertyListPtrTy,
3301 NULL);
3302 CGM.getModule().addTypeName("struct._class_ro_t",
3303 ClassRonfABITy);
3304
3305 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3306 std::vector<const llvm::Type*> Params;
3307 Params.push_back(ObjectPtrTy);
3308 Params.push_back(SelectorPtrTy);
3309 ImpnfABITy = llvm::PointerType::getUnqual(
3310 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3311
3312 // struct _class_t {
3313 // struct _class_t *isa;
3314 // struct _class_t * const superclass;
3315 // void *cache;
3316 // IMP *vtable;
3317 // struct class_ro_t *ro;
3318 // }
3319
3320 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3321 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3322 llvm::PointerType::getUnqual(ClassTyHolder),
3323 CachePtrTy,
3324 llvm::PointerType::getUnqual(ImpnfABITy),
3325 llvm::PointerType::getUnqual(
3326 ClassRonfABITy),
3327 NULL);
3328 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3329
3330 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3331 ClassnfABITy);
3332
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003333 // LLVM for struct _class_t *
3334 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3335
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003336 // struct _category_t {
3337 // const char * const name;
3338 // struct _class_t *const cls;
3339 // const struct _method_list_t * const instance_methods;
3340 // const struct _method_list_t * const class_methods;
3341 // const struct _protocol_list_t * const protocols;
3342 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003343 // }
3344 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003345 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003346 MethodListnfABIPtrTy,
3347 MethodListnfABIPtrTy,
3348 ProtocolListnfABIPtrTy,
3349 PropertyListPtrTy,
3350 NULL);
3351 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003352
3353 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003354 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3355 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003356
3357 // MessageRefTy - LLVM for:
3358 // struct _message_ref_t {
3359 // IMP messenger;
3360 // SEL name;
3361 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003362
3363 // First the clang type for struct _message_ref_t
3364 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3365 SourceLocation(),
3366 &Ctx.Idents.get("_message_ref_t"));
3367 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3368 Ctx.VoidPtrTy, 0, false));
3369 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3370 Ctx.getObjCSelType(), 0, false));
3371 RD->completeDefinition(Ctx);
3372
3373 MessageRefCTy = Ctx.getTagDeclType(RD);
3374 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3375 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003376
3377 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3378 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3379
3380 // SuperMessageRefTy - LLVM for:
3381 // struct _super_message_ref_t {
3382 // SUPER_IMP messenger;
3383 // SEL name;
3384 // };
3385 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3386 SelectorPtrTy,
3387 NULL);
3388 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3389
3390 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3391 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3392
3393 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3394 Params.clear();
3395 Params.push_back(ObjectPtrTy);
3396 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003397 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3398 Params,
3399 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003400 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003401 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003402 "objc_msgSend_fixup");
3403
3404 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3405 MessageSendFpretFixupFn =
3406 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3407 Params,
3408 true),
3409 "objc_msgSend_fpret_fixup");
3410
3411 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3412 MessageSendStretFixupFn =
3413 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3414 Params,
3415 true),
3416 "objc_msgSend_stret_fixup");
3417
3418 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3419 MessageSendIdFixupFn =
3420 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3421 Params,
3422 true),
3423 "objc_msgSendId_fixup");
3424
3425
3426 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3427 MessageSendIdStretFixupFn =
3428 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3429 Params,
3430 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003431 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003432
3433 // id objc_msgSendSuper2_fixup (struct objc_super *,
3434 // struct _super_message_ref_t*, ...)
3435 Params.clear();
3436 Params.push_back(SuperPtrTy);
3437 Params.push_back(SuperMessageRefPtrTy);
3438 MessageSendSuper2FixupFn =
3439 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3440 Params,
3441 true),
3442 "objc_msgSendSuper2_fixup");
3443
3444
3445 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3446 // struct _super_message_ref_t*, ...)
3447 MessageSendSuper2StretFixupFn =
3448 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3449 Params,
3450 true),
3451 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003452
3453 Params.clear();
3454 llvm::Constant *Personality =
3455 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3456 Params,
3457 true),
3458 "__objc_personality_v0");
3459 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3460
3461 Params.clear();
3462 Params.push_back(Int8PtrTy);
3463 UnwindResumeOrRethrowFn =
3464 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3465 Params,
3466 false),
3467 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003468 ObjCBeginCatchFn =
3469 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3470 Params,
3471 false),
3472 "objc_begin_catch");
3473
3474 Params.clear();
3475 ObjCEndCatchFn =
3476 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3477 Params,
3478 false),
3479 "objc_end_catch");
3480
3481 // struct objc_typeinfo {
3482 // const void** vtable; // objc_ehtype_vtable + 2
3483 // const char* name; // c++ typeinfo string
3484 // Class cls;
3485 // };
3486 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3487 Int8PtrTy,
3488 ClassnfABIPtrTy,
3489 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003490 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003491 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003492}
3493
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003494llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3495 FinishNonFragileABIModule();
3496
3497 return NULL;
3498}
3499
3500void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3501 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003502
3503 // Build list of all implemented classe addresses in array
3504 // L_OBJC_LABEL_CLASS_$.
3505 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3506 // list of 'nonlazy' implementations (defined as those with a +load{}
3507 // method!!).
3508 unsigned NumClasses = DefinedClasses.size();
3509 if (NumClasses) {
3510 std::vector<llvm::Constant*> Symbols(NumClasses);
3511 for (unsigned i=0; i<NumClasses; i++)
3512 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3513 ObjCTypes.Int8PtrTy);
3514 llvm::Constant* Init =
3515 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3516 NumClasses),
3517 Symbols);
3518
3519 llvm::GlobalVariable *GV =
3520 new llvm::GlobalVariable(Init->getType(), false,
3521 llvm::GlobalValue::InternalLinkage,
3522 Init,
3523 "\01L_OBJC_LABEL_CLASS_$",
3524 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003525 GV->setAlignment(
3526 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003527 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3528 UsedGlobals.push_back(GV);
3529 }
3530
3531 // Build list of all implemented category addresses in array
3532 // L_OBJC_LABEL_CATEGORY_$.
3533 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3534 // list of 'nonlazy' category implementations (defined as those with a +load{}
3535 // method!!).
3536 unsigned NumCategory = DefinedCategories.size();
3537 if (NumCategory) {
3538 std::vector<llvm::Constant*> Symbols(NumCategory);
3539 for (unsigned i=0; i<NumCategory; i++)
3540 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3541 ObjCTypes.Int8PtrTy);
3542 llvm::Constant* Init =
3543 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3544 NumCategory),
3545 Symbols);
3546
3547 llvm::GlobalVariable *GV =
3548 new llvm::GlobalVariable(Init->getType(), false,
3549 llvm::GlobalValue::InternalLinkage,
3550 Init,
3551 "\01L_OBJC_LABEL_CATEGORY_$",
3552 &CGM.getModule());
3553 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3554 UsedGlobals.push_back(GV);
3555 }
3556
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003557 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3558 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3559 std::vector<llvm::Constant*> Values(2);
3560 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003561 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003562 // FIXME: Fix and continue?
3563 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3564 flags |= eImageInfo_GarbageCollected;
3565 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3566 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003567 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003568 llvm::Constant* Init = llvm::ConstantArray::get(
3569 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3570 Values);
3571 llvm::GlobalVariable *IMGV =
3572 new llvm::GlobalVariable(Init->getType(), false,
3573 llvm::GlobalValue::InternalLinkage,
3574 Init,
3575 "\01L_OBJC_IMAGE_INFO",
3576 &CGM.getModule());
3577 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3578 UsedGlobals.push_back(IMGV);
3579
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003580 std::vector<llvm::Constant*> Used;
3581 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3582 e = UsedGlobals.end(); i != e; ++i) {
3583 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3584 }
3585
3586 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3587 llvm::GlobalValue *GV =
3588 new llvm::GlobalVariable(AT, false,
3589 llvm::GlobalValue::AppendingLinkage,
3590 llvm::ConstantArray::get(AT, Used),
3591 "llvm.used",
3592 &CGM.getModule());
3593
3594 GV->setSection("llvm.metadata");
3595
3596}
3597
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003598// Metadata flags
3599enum MetaDataDlags {
3600 CLS = 0x0,
3601 CLS_META = 0x1,
3602 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003603 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003604 CLS_EXCEPTION = 0x20
3605};
3606/// BuildClassRoTInitializer - generate meta-data for:
3607/// struct _class_ro_t {
3608/// uint32_t const flags;
3609/// uint32_t const instanceStart;
3610/// uint32_t const instanceSize;
3611/// uint32_t const reserved; // only when building for 64bit targets
3612/// const uint8_t * const ivarLayout;
3613/// const char *const name;
3614/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003615/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003616/// const struct _ivar_list_t *const ivars;
3617/// const uint8_t * const weakIvarLayout;
3618/// const struct _prop_list_t * const properties;
3619/// }
3620///
3621llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3622 unsigned flags,
3623 unsigned InstanceStart,
3624 unsigned InstanceSize,
3625 const ObjCImplementationDecl *ID) {
3626 std::string ClassName = ID->getNameAsString();
3627 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3628 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3629 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3630 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3631 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003632 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003633 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003634 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003635 // const struct _method_list_t * const baseMethods;
3636 std::vector<llvm::Constant*> Methods;
3637 std::string MethodListName("\01l_OBJC_$_");
3638 if (flags & CLS_META) {
3639 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3640 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3641 e = ID->classmeth_end(); i != e; ++i) {
3642 // Class methods should always be defined.
3643 Methods.push_back(GetMethodConstant(*i));
3644 }
3645 } else {
3646 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3647 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3648 e = ID->instmeth_end(); i != e; ++i) {
3649 // Instance methods should always be defined.
3650 Methods.push_back(GetMethodConstant(*i));
3651 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003652 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3653 e = ID->propimpl_end(); i != e; ++i) {
3654 ObjCPropertyImplDecl *PID = *i;
3655
3656 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3657 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3658
3659 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3660 if (llvm::Constant *C = GetMethodConstant(MD))
3661 Methods.push_back(C);
3662 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3663 if (llvm::Constant *C = GetMethodConstant(MD))
3664 Methods.push_back(C);
3665 }
3666 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003667 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003668 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003669 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003670
3671 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3672 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3673 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3674 + OID->getNameAsString(),
3675 OID->protocol_begin(),
3676 OID->protocol_end());
3677
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003678 if (flags & CLS_META)
3679 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3680 else
3681 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003682 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003683 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003684 if (flags & CLS_META)
3685 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3686 else
3687 Values[ 9] =
3688 EmitPropertyList(
3689 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3690 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003691 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3692 Values);
3693 llvm::GlobalVariable *CLASS_RO_GV =
3694 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3695 llvm::GlobalValue::InternalLinkage,
3696 Init,
3697 (flags & CLS_META) ?
3698 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3699 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3700 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003701 CLASS_RO_GV->setAlignment(
3702 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003703 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003704 UsedGlobals.push_back(CLASS_RO_GV);
3705 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003706
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003707}
3708
3709/// BuildClassMetaData - This routine defines that to-level meta-data
3710/// for the given ClassName for:
3711/// struct _class_t {
3712/// struct _class_t *isa;
3713/// struct _class_t * const superclass;
3714/// void *cache;
3715/// IMP *vtable;
3716/// struct class_ro_t *ro;
3717/// }
3718///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003719llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3720 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003721 llvm::Constant *IsAGV,
3722 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003723 llvm::Constant *ClassRoGV,
3724 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003725 std::vector<llvm::Constant*> Values(5);
3726 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003727 Values[1] = SuperClassGV
3728 ? SuperClassGV
3729 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003730 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3731 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3732 Values[4] = ClassRoGV; // &CLASS_RO_GV
3733 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3734 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003735 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3736 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003737 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003738 GV->setAlignment(
3739 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003740 if (HiddenVisibility)
3741 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003742 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003743 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003744}
3745
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003746void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3747 std::string ClassName = ID->getNameAsString();
3748 if (!ObjCEmptyCacheVar) {
3749 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003750 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003751 false,
3752 llvm::GlobalValue::ExternalLinkage,
3753 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003754 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003755 &CGM.getModule());
3756 UsedGlobals.push_back(ObjCEmptyCacheVar);
3757
3758 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003759 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003760 false,
3761 llvm::GlobalValue::ExternalLinkage,
3762 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003763 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003764 &CGM.getModule());
3765 UsedGlobals.push_back(ObjCEmptyVtableVar);
3766 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003767 assert(ID->getClassInterface() &&
3768 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003769 uint32_t InstanceStart =
3770 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3771 uint32_t InstanceSize = InstanceStart;
3772 uint32_t flags = CLS_META;
3773 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3774 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003775
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003776 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003777
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003778 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3779 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003780 flags |= OBJC2_CLS_HIDDEN;
3781 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003782 // class is root
3783 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003784 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3785 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003786 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003787 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003788 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3789 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3790 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003791 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003792 // work on super class metadata symbol.
3793 std::string SuperClassName =
3794 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003795 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003796 }
3797 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3798 InstanceStart,
3799 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003800 std::string TClassName = ObjCMetaClassName + ClassName;
3801 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003802 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3803 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003804
3805 // Metadata for the class
3806 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003807 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003808 flags |= OBJC2_CLS_HIDDEN;
3809 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003810 flags |= CLS_ROOT;
3811 SuperClassGV = 0;
3812 }
3813 else {
3814 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003815 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003816 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003817 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003818 }
3819
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003820 InstanceStart = InstanceSize = 0;
3821 if (ObjCInterfaceDecl *OID =
3822 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3823 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003824 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003825 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003826 const llvm::StructLayout *Layout =
3827 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003828
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003829 RecordDecl::field_iterator firstField, lastField;
3830 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003831
3832 for (RecordDecl::field_iterator e = RD->field_end(),
3833 ifield = firstField; ifield != e; ++ifield)
3834 lastField = ifield;
3835
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003836 if (lastField != RD->field_end()) {
3837 FieldDecl *Field = *lastField;
3838 const llvm::Type *FieldTy =
3839 CGM.getTypes().ConvertTypeForMem(Field->getType());
3840 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3841 InstanceSize = Layout->getElementOffset(
3842 CGM.getTypes().getLLVMFieldNo(Field)) +
3843 Size;
3844 if (firstField == RD->field_end())
3845 InstanceStart = InstanceSize;
3846 else
3847 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3848 getLLVMFieldNo(*firstField));
3849 }
3850 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003851 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003852 InstanceStart,
3853 InstanceSize,
3854 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003855
3856 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003857 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003858 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3859 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003860 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003861}
3862
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003863/// GenerateProtocolRef - This routine is called to generate code for
3864/// a protocol reference expression; as in:
3865/// @code
3866/// @protocol(Proto1);
3867/// @endcode
3868/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3869/// which will hold address of the protocol meta-data.
3870///
3871llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3872 const ObjCProtocolDecl *PD) {
3873
3874 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3875 ObjCTypes.ExternalProtocolPtrTy);
3876
3877 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3878 ProtocolName += PD->getNameAsCString();
3879
3880 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3881 if (PTGV)
3882 return Builder.CreateLoad(PTGV, false, "tmp");
3883 PTGV = new llvm::GlobalVariable(
3884 Init->getType(), false,
3885 llvm::GlobalValue::WeakLinkage,
3886 Init,
3887 ProtocolName,
3888 &CGM.getModule());
3889 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3890 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3891 UsedGlobals.push_back(PTGV);
3892 return Builder.CreateLoad(PTGV, false, "tmp");
3893}
3894
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003895/// GenerateCategory - Build metadata for a category implementation.
3896/// struct _category_t {
3897/// const char * const name;
3898/// struct _class_t *const cls;
3899/// const struct _method_list_t * const instance_methods;
3900/// const struct _method_list_t * const class_methods;
3901/// const struct _protocol_list_t * const protocols;
3902/// const struct _prop_list_t * const properties;
3903/// }
3904///
3905void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3906{
3907 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003908 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3909 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003910 "_$_" + OCD->getNameAsString());
3911 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3912
3913 std::vector<llvm::Constant*> Values(6);
3914 Values[0] = GetClassName(OCD->getIdentifier());
3915 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003916 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003917 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003918 std::vector<llvm::Constant*> Methods;
3919 std::string MethodListName(Prefix);
3920 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3921 "_$_" + OCD->getNameAsString();
3922
3923 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3924 e = OCD->instmeth_end(); i != e; ++i) {
3925 // Instance methods should always be defined.
3926 Methods.push_back(GetMethodConstant(*i));
3927 }
3928
3929 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003930 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003931 Methods);
3932
3933 MethodListName = Prefix;
3934 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3935 OCD->getNameAsString();
3936 Methods.clear();
3937 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3938 e = OCD->classmeth_end(); i != e; ++i) {
3939 // Class methods should always be defined.
3940 Methods.push_back(GetMethodConstant(*i));
3941 }
3942
3943 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003944 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003945 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003946 const ObjCCategoryDecl *Category =
3947 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003948 if (Category) {
3949 std::string ExtName(Interface->getNameAsString() + "_$_" +
3950 OCD->getNameAsString());
3951 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3952 + Interface->getNameAsString() + "_$_"
3953 + Category->getNameAsString(),
3954 Category->protocol_begin(),
3955 Category->protocol_end());
3956 Values[5] =
3957 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3958 OCD, Category, ObjCTypes);
3959 }
3960 else {
3961 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3962 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3963 }
3964
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003965 llvm::Constant *Init =
3966 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3967 Values);
3968 llvm::GlobalVariable *GCATV
3969 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3970 false,
3971 llvm::GlobalValue::InternalLinkage,
3972 Init,
3973 ExtCatName,
3974 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003975 GCATV->setAlignment(
3976 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003977 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003978 UsedGlobals.push_back(GCATV);
3979 DefinedCategories.push_back(GCATV);
3980}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003981
3982/// GetMethodConstant - Return a struct objc_method constant for the
3983/// given method if it has been defined. The result is null if the
3984/// method has not been defined. The return value has type MethodPtrTy.
3985llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3986 const ObjCMethodDecl *MD) {
3987 // FIXME: Use DenseMap::lookup
3988 llvm::Function *Fn = MethodDefinitions[MD];
3989 if (!Fn)
3990 return 0;
3991
3992 std::vector<llvm::Constant*> Method(3);
3993 Method[0] =
3994 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3995 ObjCTypes.SelectorPtrTy);
3996 Method[1] = GetMethodVarType(MD);
3997 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3998 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3999}
4000
4001/// EmitMethodList - Build meta-data for method declarations
4002/// struct _method_list_t {
4003/// uint32_t entsize; // sizeof(struct _objc_method)
4004/// uint32_t method_count;
4005/// struct _objc_method method_list[method_count];
4006/// }
4007///
4008llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4009 const std::string &Name,
4010 const char *Section,
4011 const ConstantVector &Methods) {
4012 // Return null for empty list.
4013 if (Methods.empty())
4014 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4015
4016 std::vector<llvm::Constant*> Values(3);
4017 // sizeof(struct _objc_method)
4018 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4019 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4020 // method_count
4021 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4022 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4023 Methods.size());
4024 Values[2] = llvm::ConstantArray::get(AT, Methods);
4025 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4026
4027 llvm::GlobalVariable *GV =
4028 new llvm::GlobalVariable(Init->getType(), false,
4029 llvm::GlobalValue::InternalLinkage,
4030 Init,
4031 Name,
4032 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004033 GV->setAlignment(
4034 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004035 GV->setSection(Section);
4036 UsedGlobals.push_back(GV);
4037 return llvm::ConstantExpr::getBitCast(GV,
4038 ObjCTypes.MethodListnfABIPtrTy);
4039}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004040
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004041/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4042/// the given ivar.
4043///
4044llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4045 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004046 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004047 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004048 Name += "\01_OBJC_IVAR_$_" +
4049 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004050 + Ivar->getNameAsString();
4051 llvm::GlobalVariable *IvarOffsetGV =
4052 CGM.getModule().getGlobalVariable(Name);
4053 if (!IvarOffsetGV)
4054 IvarOffsetGV =
4055 new llvm::GlobalVariable(ObjCTypes.LongTy,
4056 false,
4057 llvm::GlobalValue::ExternalLinkage,
4058 0,
4059 Name,
4060 &CGM.getModule());
4061 return IvarOffsetGV;
4062}
4063
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004064llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004065 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004066 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004067 unsigned long int Offset) {
4068
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004069 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004070 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004071 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004072 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004073
4074 llvm::GlobalVariable *IvarOffsetGV =
4075 CGM.getModule().getGlobalVariable(ExternalName);
4076 if (IvarOffsetGV) {
4077 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004078 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004079 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004080 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004081 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004082 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004083 return IvarOffsetGV;
4084 }
4085
4086 IvarOffsetGV =
4087 new llvm::GlobalVariable(Init->getType(),
4088 false,
4089 llvm::GlobalValue::ExternalLinkage,
4090 Init,
4091 ExternalName,
4092 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004093 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004094 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004095 // @private and @package have hidden visibility.
4096 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4097 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4098 if (!globalVisibility)
4099 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004100 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004101 if (IsClassHidden(ID))
4102 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004103
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004104 IvarOffsetGV->setSection("__DATA, __objc_const");
4105 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004106 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004107}
4108
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004109/// EmitIvarList - Emit the ivar list for the given
4110/// implementation. If ForClass is true the list of class ivars
4111/// (i.e. metaclass ivars) is emitted, otherwise the list of
4112/// interface ivars will be emitted. The return value has type
4113/// IvarListnfABIPtrTy.
4114/// struct _ivar_t {
4115/// unsigned long int *offset; // pointer to ivar offset location
4116/// char *name;
4117/// char *type;
4118/// uint32_t alignment;
4119/// uint32_t size;
4120/// }
4121/// struct _ivar_list_t {
4122/// uint32 entsize; // sizeof(struct _ivar_t)
4123/// uint32 count;
4124/// struct _iver_t list[count];
4125/// }
4126///
4127llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4128 const ObjCImplementationDecl *ID) {
4129
4130 std::vector<llvm::Constant*> Ivars, Ivar(5);
4131
4132 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4133 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4134
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004135 // FIXME. Consolidate this with similar code in GenerateClass.
4136 const llvm::Type *InterfaceTy =
4137 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4138 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004139 const llvm::StructLayout *Layout =
4140 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004141
4142 RecordDecl::field_iterator i,p;
4143 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004144 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4145
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004146 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004147 FieldDecl *Field = *i;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004148 unsigned long offset = Layout->getElementOffset(CGM.getTypes().
4149 getLLVMFieldNo(Field));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004150 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004151 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004152 if (Field->getIdentifier())
4153 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4154 else
4155 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004156 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004157 const llvm::Type *FieldTy =
4158 CGM.getTypes().ConvertTypeForMem(Field->getType());
4159 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4160 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4161 Field->getType().getTypePtr()) >> 3;
4162 Align = llvm::Log2_32(Align);
4163 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004164 // NOTE. Size of a bitfield does not match gcc's, because of the way
4165 // bitfields are treated special in each. But I am told that 'size'
4166 // for bitfield ivars is ignored by the runtime so it does not matter.
4167 // (even if it matters, some day, there is enough info. to get the bitfield
4168 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004169 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4170 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4171 }
4172 // Return null for empty list.
4173 if (Ivars.empty())
4174 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4175 std::vector<llvm::Constant*> Values(3);
4176 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4177 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4178 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4179 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4180 Ivars.size());
4181 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4182 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4183 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4184 llvm::GlobalVariable *GV =
4185 new llvm::GlobalVariable(Init->getType(), false,
4186 llvm::GlobalValue::InternalLinkage,
4187 Init,
4188 Prefix + OID->getNameAsString(),
4189 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004190 GV->setAlignment(
4191 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004192 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004193
4194 UsedGlobals.push_back(GV);
4195 return llvm::ConstantExpr::getBitCast(GV,
4196 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004197}
4198
4199llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4200 const ObjCProtocolDecl *PD) {
4201 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4202
4203 if (!Entry) {
4204 // We use the initializer as a marker of whether this is a forward
4205 // reference or not. At module finalization we add the empty
4206 // contents for protocols which were referenced but never defined.
4207 Entry =
4208 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4209 llvm::GlobalValue::ExternalLinkage,
4210 0,
4211 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4212 &CGM.getModule());
4213 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4214 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004215 }
4216
4217 return Entry;
4218}
4219
4220/// GetOrEmitProtocol - Generate the protocol meta-data:
4221/// @code
4222/// struct _protocol_t {
4223/// id isa; // NULL
4224/// const char * const protocol_name;
4225/// const struct _protocol_list_t * protocol_list; // super protocols
4226/// const struct method_list_t * const instance_methods;
4227/// const struct method_list_t * const class_methods;
4228/// const struct method_list_t *optionalInstanceMethods;
4229/// const struct method_list_t *optionalClassMethods;
4230/// const struct _prop_list_t * properties;
4231/// const uint32_t size; // sizeof(struct _protocol_t)
4232/// const uint32_t flags; // = 0
4233/// }
4234/// @endcode
4235///
4236
4237llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4238 const ObjCProtocolDecl *PD) {
4239 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4240
4241 // Early exit if a defining object has already been generated.
4242 if (Entry && Entry->hasInitializer())
4243 return Entry;
4244
4245 const char *ProtocolName = PD->getNameAsCString();
4246
4247 // Construct method lists.
4248 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4249 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4250 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4251 e = PD->instmeth_end(); i != e; ++i) {
4252 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004253 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004254 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4255 OptInstanceMethods.push_back(C);
4256 } else {
4257 InstanceMethods.push_back(C);
4258 }
4259 }
4260
4261 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4262 e = PD->classmeth_end(); i != e; ++i) {
4263 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004264 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004265 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4266 OptClassMethods.push_back(C);
4267 } else {
4268 ClassMethods.push_back(C);
4269 }
4270 }
4271
4272 std::vector<llvm::Constant*> Values(10);
4273 // isa is NULL
4274 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4275 Values[1] = GetClassName(PD->getIdentifier());
4276 Values[2] = EmitProtocolList(
4277 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4278 PD->protocol_begin(),
4279 PD->protocol_end());
4280
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004281 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004282 + PD->getNameAsString(),
4283 "__DATA, __objc_const",
4284 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004285 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004286 + PD->getNameAsString(),
4287 "__DATA, __objc_const",
4288 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004289 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004290 + PD->getNameAsString(),
4291 "__DATA, __objc_const",
4292 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004293 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004294 + PD->getNameAsString(),
4295 "__DATA, __objc_const",
4296 OptClassMethods);
4297 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4298 0, PD, ObjCTypes);
4299 uint32_t Size =
4300 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4301 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4302 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4303 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4304 Values);
4305
4306 if (Entry) {
4307 // Already created, fix the linkage and update the initializer.
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004308 Entry->setLinkage(llvm::GlobalValue::WeakLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004309 Entry->setInitializer(Init);
4310 } else {
4311 Entry =
4312 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004313 llvm::GlobalValue::WeakLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004314 Init,
4315 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4316 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004317 Entry->setAlignment(
4318 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004319 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004320 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004321 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4322
4323 // Use this protocol meta-data to build protocol list table in section
4324 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004325 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004326 ObjCTypes.ProtocolnfABIPtrTy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004327 llvm::GlobalValue::WeakLinkage,
4328 Entry,
4329 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4330 +ProtocolName,
4331 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004332 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004333 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004334 PTGV->setSection("__DATA, __objc_protolist");
4335 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4336 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004337 return Entry;
4338}
4339
4340/// EmitProtocolList - Generate protocol list meta-data:
4341/// @code
4342/// struct _protocol_list_t {
4343/// long protocol_count; // Note, this is 32/64 bit
4344/// struct _protocol_t[protocol_count];
4345/// }
4346/// @endcode
4347///
4348llvm::Constant *
4349CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4350 ObjCProtocolDecl::protocol_iterator begin,
4351 ObjCProtocolDecl::protocol_iterator end) {
4352 std::vector<llvm::Constant*> ProtocolRefs;
4353
Fariborz Jahanianda320092009-01-29 19:24:30 +00004354 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004355 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004356 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4357
Daniel Dunbar948e2582009-02-15 07:36:20 +00004358 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004359 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4360 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004361 return llvm::ConstantExpr::getBitCast(GV,
4362 ObjCTypes.ProtocolListnfABIPtrTy);
4363
4364 for (; begin != end; ++begin)
4365 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4366
Fariborz Jahanianda320092009-01-29 19:24:30 +00004367 // This list is null terminated.
4368 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004369 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004370
4371 std::vector<llvm::Constant*> Values(2);
4372 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4373 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004374 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004375 ProtocolRefs.size()),
4376 ProtocolRefs);
4377
4378 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4379 GV = new llvm::GlobalVariable(Init->getType(), false,
4380 llvm::GlobalValue::InternalLinkage,
4381 Init,
4382 Name,
4383 &CGM.getModule());
4384 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004385 GV->setAlignment(
4386 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004387 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004388 return llvm::ConstantExpr::getBitCast(GV,
4389 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004390}
4391
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004392/// GetMethodDescriptionConstant - This routine build following meta-data:
4393/// struct _objc_method {
4394/// SEL _cmd;
4395/// char *method_type;
4396/// char *_imp;
4397/// }
4398
4399llvm::Constant *
4400CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4401 std::vector<llvm::Constant*> Desc(3);
4402 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4403 ObjCTypes.SelectorPtrTy);
4404 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004405 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004406 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4407 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4408}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004409
4410/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4411/// This code gen. amounts to generating code for:
4412/// @code
4413/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4414/// @encode
4415///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004416LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004417 CodeGen::CodeGenFunction &CGF,
4418 QualType ObjectTy,
4419 llvm::Value *BaseValue,
4420 const ObjCIvarDecl *Ivar,
4421 const FieldDecl *Field,
4422 unsigned CVRQualifiers) {
4423 assert(ObjectTy->isObjCInterfaceType() &&
4424 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004425 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004426 std::string ExternalName;
4427 llvm::GlobalVariable *IvarOffsetGV =
4428 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004429
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004430 // (char *) BaseValue
4431 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4432 ObjCTypes.Int8PtrTy);
4433 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4434 // (char*)BaseValue + Offset_symbol
4435 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4436 // (type *)((char*)BaseValue + Offset_symbol)
4437 const llvm::Type *IvarTy =
4438 CGM.getTypes().ConvertType(Ivar->getType());
4439 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4440 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004441
4442 if (Ivar->isBitField())
4443 return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4444 CVRQualifiers);
4445
4446 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004447 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4448 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004449 LValue::SetObjCIvar(LV, true);
4450 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004451}
4452
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004453llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4454 CodeGen::CodeGenFunction &CGF,
4455 ObjCInterfaceDecl *Interface,
4456 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004457 std::string ExternalName;
4458 llvm::GlobalVariable *IvarOffsetGV =
4459 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4460
4461 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004462}
4463
Fariborz Jahanian46551122009-02-04 00:22:57 +00004464CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4465 CodeGen::CodeGenFunction &CGF,
4466 QualType ResultType,
4467 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004468 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004469 QualType Arg0Ty,
4470 bool IsSuper,
4471 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004472 // FIXME. Even though IsSuper is passes. This function doese not
4473 // handle calls to 'super' receivers.
4474 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004475 llvm::Value *Arg0 = Receiver;
4476 if (!IsSuper)
4477 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004478
4479 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004480 // FIXME. This is too much work to get the ABI-specific result type
4481 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004482 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4483 llvm::SmallVector<QualType, 16>());
4484 llvm::Constant *Fn;
4485 std::string Name("\01l_");
4486 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004487#if 0
4488 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004489 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4490 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4491 // FIXME. Is there a better way of getting these names.
4492 // They are available in RuntimeFunctions vector pair.
4493 Name += "objc_msgSendId_stret_fixup";
4494 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004495 else
4496#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004497 if (IsSuper) {
4498 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4499 Name += "objc_msgSendSuper2_stret_fixup";
4500 }
4501 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004502 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004503 Fn = ObjCTypes.MessageSendStretFixupFn;
4504 Name += "objc_msgSend_stret_fixup";
4505 }
4506 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004507 else if (ResultType->isFloatingType() &&
4508 // Selection of frret API only happens in 32bit nonfragile ABI.
4509 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004510 Fn = ObjCTypes.MessageSendFpretFixupFn;
4511 Name += "objc_msgSend_fpret_fixup";
4512 }
4513 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004514#if 0
4515// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004516 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4517 Fn = ObjCTypes.MessageSendIdFixupFn;
4518 Name += "objc_msgSendId_fixup";
4519 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004520 else
4521#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004522 if (IsSuper) {
4523 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4524 Name += "objc_msgSendSuper2_fixup";
4525 }
4526 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004527 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004528 Fn = ObjCTypes.MessageSendFixupFn;
4529 Name += "objc_msgSend_fixup";
4530 }
4531 }
4532 Name += '_';
4533 std::string SelName(Sel.getAsString());
4534 // Replace all ':' in selector name with '_' ouch!
4535 for(unsigned i = 0; i < SelName.size(); i++)
4536 if (SelName[i] == ':')
4537 SelName[i] = '_';
4538 Name += SelName;
4539 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4540 if (!GV) {
4541 // Build messafe ref table entry.
4542 std::vector<llvm::Constant*> Values(2);
4543 Values[0] = Fn;
4544 Values[1] = GetMethodVarName(Sel);
4545 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4546 GV = new llvm::GlobalVariable(Init->getType(), false,
4547 llvm::GlobalValue::WeakLinkage,
4548 Init,
4549 Name,
4550 &CGM.getModule());
4551 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4552 GV->setAlignment(
4553 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4554 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4555 UsedGlobals.push_back(GV);
4556 }
4557 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004558
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004559 CallArgList ActualArgs;
4560 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4561 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4562 ObjCTypes.MessageRefCPtrTy));
4563 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004564 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4565 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4566 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004567 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004568 Callee = CGF.Builder.CreateBitCast(Callee,
4569 llvm::PointerType::getUnqual(FTy));
4570 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004571}
4572
4573/// Generate code for a message send expression in the nonfragile abi.
4574CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4575 CodeGen::CodeGenFunction &CGF,
4576 QualType ResultType,
4577 Selector Sel,
4578 llvm::Value *Receiver,
4579 bool IsClassMessage,
4580 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004581 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004582 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004583 false, CallArgs);
4584}
4585
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004586llvm::GlobalVariable *
4587CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4588 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4589
Daniel Dunbardfff2302009-03-02 05:18:14 +00004590 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004591 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4592 llvm::GlobalValue::ExternalLinkage,
4593 0, Name, &CGM.getModule());
4594 UsedGlobals.push_back(GV);
4595 }
4596
4597 return GV;
4598}
4599
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004600llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004601 const ObjCInterfaceDecl *ID,
4602 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004603
4604 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4605
4606 if (!Entry) {
4607 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004608 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004609 Entry =
4610 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4611 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004612 ClassGV,
4613 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4614 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004615 &CGM.getModule());
4616 Entry->setAlignment(
4617 CGM.getTargetData().getPrefTypeAlignment(
4618 ObjCTypes.ClassnfABIPtrTy));
4619
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004620 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004621 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004622 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004623 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004624 UsedGlobals.push_back(Entry);
4625 }
4626
4627 return Builder.CreateLoad(Entry, false, "tmp");
4628}
4629
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004630/// EmitMetaClassRef - Return a Value * of the address of _class_t
4631/// meta-data
4632///
4633llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4634 const ObjCInterfaceDecl *ID) {
4635 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4636 if (Entry)
4637 return Builder.CreateLoad(Entry, false, "tmp");
4638
4639 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004640 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004641 Entry =
4642 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4643 llvm::GlobalValue::InternalLinkage,
4644 MetaClassGV,
4645 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4646 &CGM.getModule());
4647 Entry->setAlignment(
4648 CGM.getTargetData().getPrefTypeAlignment(
4649 ObjCTypes.ClassnfABIPtrTy));
4650
4651 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4652 UsedGlobals.push_back(Entry);
4653
4654 return Builder.CreateLoad(Entry, false, "tmp");
4655}
4656
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004657/// GetClass - Return a reference to the class for the given interface
4658/// decl.
4659llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4660 const ObjCInterfaceDecl *ID) {
4661 return EmitClassRef(Builder, ID);
4662}
4663
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004664/// Generates a message send where the super is the receiver. This is
4665/// a message send to self with special delivery semantics indicating
4666/// which class's method should be called.
4667CodeGen::RValue
4668CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4669 QualType ResultType,
4670 Selector Sel,
4671 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004672 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004673 llvm::Value *Receiver,
4674 bool IsClassMessage,
4675 const CodeGen::CallArgList &CallArgs) {
4676 // ...
4677 // Create and init a super structure; this is a (receiver, class)
4678 // pair we will pass to objc_msgSendSuper.
4679 llvm::Value *ObjCSuper =
4680 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4681
4682 llvm::Value *ReceiverAsObject =
4683 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4684 CGF.Builder.CreateStore(ReceiverAsObject,
4685 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4686
4687 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004688 llvm::Value *Target;
4689 if (IsClassMessage) {
4690 if (isCategoryImpl) {
4691 // Message sent to "super' in a class method defined in
4692 // a category implementation.
4693 Target = EmitClassRef(CGF.Builder, Class, false);
4694 Target = CGF.Builder.CreateStructGEP(Target, 0);
4695 Target = CGF.Builder.CreateLoad(Target);
4696 }
4697 else
4698 Target = EmitMetaClassRef(CGF.Builder, Class);
4699 }
4700 else
4701 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004702
4703 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4704 // and ObjCTypes types.
4705 const llvm::Type *ClassTy =
4706 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4707 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4708 CGF.Builder.CreateStore(Target,
4709 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4710
4711 return EmitMessageSend(CGF, ResultType, Sel,
4712 ObjCSuper, ObjCTypes.SuperPtrCTy,
4713 true, CallArgs);
4714}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004715
4716llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4717 Selector Sel) {
4718 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4719
4720 if (!Entry) {
4721 llvm::Constant *Casted =
4722 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4723 ObjCTypes.SelectorPtrTy);
4724 Entry =
4725 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4726 llvm::GlobalValue::InternalLinkage,
4727 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4728 &CGM.getModule());
4729 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4730 UsedGlobals.push_back(Entry);
4731 }
4732
4733 return Builder.CreateLoad(Entry, false, "tmp");
4734}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004735/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4736/// objc_assign_ivar (id src, id *dst)
4737///
4738void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4739 llvm::Value *src, llvm::Value *dst)
4740{
4741 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4742 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4743 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4744 src, dst, "assignivar");
4745 return;
4746}
4747
4748/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4749/// objc_assign_strongCast (id src, id *dst)
4750///
4751void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4752 CodeGen::CodeGenFunction &CGF,
4753 llvm::Value *src, llvm::Value *dst)
4754{
4755 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4756 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4757 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4758 src, dst, "weakassign");
4759 return;
4760}
4761
4762/// EmitObjCWeakRead - Code gen for loading value of a __weak
4763/// object: objc_read_weak (id *src)
4764///
4765llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4766 CodeGen::CodeGenFunction &CGF,
4767 llvm::Value *AddrWeakObj)
4768{
4769 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4770 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4771 AddrWeakObj, "weakread");
4772 return read_weak;
4773}
4774
4775/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4776/// objc_assign_weak (id src, id *dst)
4777///
4778void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4779 llvm::Value *src, llvm::Value *dst)
4780{
4781 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4782 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4783 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4784 src, dst, "weakassign");
4785 return;
4786}
4787
4788/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4789/// objc_assign_global (id src, id *dst)
4790///
4791void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4792 llvm::Value *src, llvm::Value *dst)
4793{
4794 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4795 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4796 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4797 src, dst, "globalassign");
4798 return;
4799}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004800
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004801void
4802CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4803 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004804 bool isTry = isa<ObjCAtTryStmt>(S);
4805 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4806 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004807 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004808 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004809 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004810 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4811
4812 // For @synchronized, call objc_sync_enter(sync.expr). The
4813 // evaluation of the expression must occur before we enter the
4814 // @synchronized. We can safely avoid a temp here because jumps into
4815 // @synchronized are illegal & this will dominate uses.
4816 llvm::Value *SyncArg = 0;
4817 if (!isTry) {
4818 SyncArg =
4819 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4820 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4821 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4822 }
4823
4824 // Push an EH context entry, used for handling rethrows and jumps
4825 // through finally.
4826 CGF.PushCleanupBlock(FinallyBlock);
4827
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004828 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004829
4830 CGF.EmitBlock(TryBlock);
4831 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4832 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4833 CGF.EmitBranchThroughCleanup(FinallyEnd);
4834
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004835 // Emit the exception handler.
4836
4837 CGF.EmitBlock(TryHandler);
4838
4839 llvm::Value *llvm_eh_exception =
4840 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4841 llvm::Value *llvm_eh_selector_i64 =
4842 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4843 llvm::Value *llvm_eh_typeid_for_i64 =
4844 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4845 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4846 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4847
4848 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4849 SelectorArgs.push_back(Exc);
4850 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4851
4852 // Construct the lists of (type, catch body) to handle.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004853 llvm::SmallVector<std::pair<const Decl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004854 bool HasCatchAll = false;
4855 if (isTry) {
4856 if (const ObjCAtCatchStmt* CatchStmt =
4857 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4858 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004859 const Decl *CatchDecl = CatchStmt->getCatchParamDecl();
4860 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004861
4862 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004863 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004864 // Use i8* null here to signal this is a catch all, not a cleanup.
4865 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4866 SelectorArgs.push_back(Null);
4867 HasCatchAll = true;
4868 break;
4869 }
4870
Steve Naroff7ba138a2009-03-03 19:52:17 +00004871 const VarDecl *VD = cast<VarDecl>(CatchDecl);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004872 if (CGF.getContext().isObjCIdType(VD->getType()) ||
4873 VD->getType()->isObjCQualifiedIdType()) {
4874 llvm::Value *IDEHType =
4875 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4876 if (!IDEHType)
4877 IDEHType =
4878 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4879 llvm::GlobalValue::ExternalLinkage,
4880 0, "OBJC_EHTYPE_id", &CGM.getModule());
4881 SelectorArgs.push_back(IDEHType);
4882 HasCatchAll = true;
4883 break;
4884 }
4885
4886 // All other types should be Objective-C interface pointer types.
4887 const PointerType *PT = VD->getType()->getAsPointerType();
4888 assert(PT && "Invalid @catch type.");
4889 const ObjCInterfaceType *IT =
4890 PT->getPointeeType()->getAsObjCInterfaceType();
4891 assert(IT && "Invalid @catch type.");
4892 llvm::Value *EHType = GetInterfaceEHType(IT);
4893 SelectorArgs.push_back(EHType);
4894 }
4895 }
4896 }
4897
4898 // We use a cleanup unless there was already a catch all.
4899 if (!HasCatchAll) {
4900 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004901 Handlers.push_back(std::make_pair((const Decl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004902 }
4903
4904 llvm::Value *Selector =
4905 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4906 SelectorArgs.begin(), SelectorArgs.end(),
4907 "selector");
4908 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004909 const Decl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004910 const Stmt *CatchBody = Handlers[i].second;
4911
4912 llvm::BasicBlock *Next = 0;
4913
4914 // The last handler always matches.
4915 if (i + 1 != e) {
4916 assert(CatchParam && "Only last handler can be a catch all.");
4917
4918 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4919 Next = CGF.createBasicBlock("catch.next");
4920 llvm::Value *Id =
4921 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4922 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4923 ObjCTypes.Int8PtrTy));
4924 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4925 Match, Next);
4926
4927 CGF.EmitBlock(Match);
4928 }
4929
4930 if (CatchBody) {
4931 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4932 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4933
4934 // Cleanups must call objc_end_catch.
4935 //
4936 // FIXME: It seems incorrect for objc_begin_catch to be inside
4937 // this context, but this matches gcc.
4938 CGF.PushCleanupBlock(MatchEnd);
4939 CGF.setInvokeDest(MatchHandler);
4940
4941 llvm::Value *ExcObject =
4942 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4943
4944 // Bind the catch parameter if it exists.
4945 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004946 const VarDecl *VD = dyn_cast<VarDecl>(CatchParam);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004947 ExcObject = CGF.Builder.CreateBitCast(ExcObject,
4948 CGF.ConvertType(VD->getType()));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004949 CGF.EmitLocalBlockVarDecl(*VD);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004950 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(VD));
4951 }
4952
4953 CGF.ObjCEHValueStack.push_back(ExcObject);
4954 CGF.EmitStmt(CatchBody);
4955 CGF.ObjCEHValueStack.pop_back();
4956
4957 CGF.EmitBranchThroughCleanup(FinallyEnd);
4958
4959 CGF.EmitBlock(MatchHandler);
4960
4961 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4962 // We are required to emit this call to satisfy LLVM, even
4963 // though we don't use the result.
4964 llvm::SmallVector<llvm::Value*, 8> Args;
4965 Args.push_back(Exc);
4966 Args.push_back(ObjCTypes.EHPersonalityPtr);
4967 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4968 0));
4969 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4970 CGF.Builder.CreateStore(Exc, RethrowPtr);
4971 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4972
4973 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4974
4975 CGF.EmitBlock(MatchEnd);
4976
4977 // Unfortunately, we also have to generate another EH frame here
4978 // in case this throws.
4979 llvm::BasicBlock *MatchEndHandler =
4980 CGF.createBasicBlock("match.end.handler");
4981 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4982 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
4983 Cont, MatchEndHandler,
4984 Args.begin(), Args.begin());
4985
4986 CGF.EmitBlock(Cont);
4987 if (Info.SwitchBlock)
4988 CGF.EmitBlock(Info.SwitchBlock);
4989 if (Info.EndBlock)
4990 CGF.EmitBlock(Info.EndBlock);
4991
4992 CGF.EmitBlock(MatchEndHandler);
4993 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4994 // We are required to emit this call to satisfy LLVM, even
4995 // though we don't use the result.
4996 Args.clear();
4997 Args.push_back(Exc);
4998 Args.push_back(ObjCTypes.EHPersonalityPtr);
4999 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5000 0));
5001 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5002 CGF.Builder.CreateStore(Exc, RethrowPtr);
5003 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5004
5005 if (Next)
5006 CGF.EmitBlock(Next);
5007 } else {
5008 assert(!Next && "catchup should be last handler.");
5009
5010 CGF.Builder.CreateStore(Exc, RethrowPtr);
5011 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5012 }
5013 }
5014
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005015 // Pop the cleanup entry, the @finally is outside this cleanup
5016 // scope.
5017 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5018 CGF.setInvokeDest(PrevLandingPad);
5019
5020 CGF.EmitBlock(FinallyBlock);
5021
5022 if (isTry) {
5023 if (const ObjCAtFinallyStmt* FinallyStmt =
5024 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5025 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5026 } else {
5027 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5028 // @synchronized.
5029 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005030 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005031
5032 if (Info.SwitchBlock)
5033 CGF.EmitBlock(Info.SwitchBlock);
5034 if (Info.EndBlock)
5035 CGF.EmitBlock(Info.EndBlock);
5036
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005037 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005038 CGF.EmitBranch(FinallyEnd);
5039
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005040 CGF.EmitBlock(FinallyRethrow);
5041 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5042 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005043 CGF.Builder.CreateUnreachable();
5044
5045 CGF.EmitBlock(FinallyEnd);
5046}
5047
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005048/// EmitThrowStmt - Generate code for a throw statement.
5049void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5050 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005051 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005052 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005053 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005054 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005055 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5056 "Unexpected rethrow outside @catch block.");
5057 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005058 }
5059
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005060 llvm::Value *ExceptionAsObject =
5061 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5062 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5063 if (InvokeDest) {
5064 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5065 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5066 Cont, InvokeDest,
5067 &ExceptionAsObject, &ExceptionAsObject + 1);
5068 CGF.EmitBlock(Cont);
5069 } else
5070 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5071 CGF.Builder.CreateUnreachable();
5072
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005073 // Clear the insertion point to indicate we are in unreachable code.
5074 CGF.Builder.ClearInsertionPoint();
5075}
Daniel Dunbare588b992009-03-01 04:46:24 +00005076
5077llvm::Value *
5078CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5079 const ObjCInterfaceDecl *ID = IT->getDecl();
5080 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5081 if (Entry)
5082 return Entry;
5083
5084 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5085 std::string VTableName = "objc_ehtype_vtable";
5086 llvm::GlobalVariable *VTableGV =
5087 CGM.getModule().getGlobalVariable(VTableName);
5088 if (!VTableGV)
5089 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5090 llvm::GlobalValue::ExternalLinkage,
5091 0, VTableName, &CGM.getModule());
5092
5093 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5094
5095 std::vector<llvm::Constant*> Values(3);
5096 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5097 Values[1] = GetClassName(ID->getIdentifier());
5098 Values[2] = GetClassGlobal(ClassName);
5099 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5100
5101 Entry =
5102 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5103 llvm::GlobalValue::WeakLinkage,
5104 Init,
5105 (std::string("OBJC_EHTYPE_$_") +
5106 ID->getIdentifier()->getName()),
5107 &CGM.getModule());
5108
5109 return Entry;
5110}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005111
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005112/* *** */
5113
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005114CodeGen::CGObjCRuntime *
5115CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005116 return new CGObjCMac(CGM);
5117}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005118
5119CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005120CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005121 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005122}