blob: 9f3e3035d3a8fa003e15f1f4440eaf8e28a09967 [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 {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000310 class GC_IVAR {
311 unsigned int ivar_bytepos;
312 unsigned int ivar_size;
313 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
314 };
315
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000316protected:
317 CodeGen::CodeGenModule &CGM;
318 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000319 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000320
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000321 llvm::SmallVector<GC_IVAR, 8> SkipIvars;
322 llvm::SmallVector<GC_IVAR, 8> IvarsInfo;
323
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000324 /// LazySymbols - Symbols to generate a lazy reference for. See
325 /// DefinedSymbols and FinishModule().
326 std::set<IdentifierInfo*> LazySymbols;
327
328 /// DefinedSymbols - External symbols which are defined by this
329 /// module. The symbols in this list and LazySymbols are used to add
330 /// special linker symbols which ensure that Objective-C modules are
331 /// linked properly.
332 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000333
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000334 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000335 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000336
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000337 /// MethodVarNames - uniqued method variable names.
338 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000339
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000340 /// MethodVarTypes - uniqued method type signatures. We have to use
341 /// a StringMap here because have no other unique reference.
342 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000343
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000344 /// MethodDefinitions - map of methods which have been defined in
345 /// this translation unit.
346 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000347
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000348 /// PropertyNames - uniqued method variable names.
349 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000350
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000351 /// ClassReferences - uniqued class references.
352 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000353
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000354 /// SelectorReferences - uniqued selector references.
355 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000356
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000357 /// Protocols - Protocols for which an objc_protocol structure has
358 /// been emitted. Forward declarations are handled by creating an
359 /// empty structure whose initializer is filled in when/if defined.
360 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000361
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000362 /// DefinedProtocols - Protocols which have actually been
363 /// defined. We should not need this, see FIXME in GenerateProtocol.
364 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000366 /// DefinedClasses - List of defined classes.
367 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000369 /// DefinedCategories - List of defined categories.
370 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000371
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000373 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000374 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000375
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000376 /// GetNameForMethod - Return a name for the given method.
377 /// \param[out] NameOut - The return value.
378 void GetNameForMethod(const ObjCMethodDecl *OMD,
379 const ObjCContainerDecl *CD,
380 std::string &NameOut);
381
382 /// GetMethodVarName - Return a unique constant for the given
383 /// selector's name. The return value has type char *.
384 llvm::Constant *GetMethodVarName(Selector Sel);
385 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
386 llvm::Constant *GetMethodVarName(const std::string &Name);
387
388 /// GetMethodVarType - Return a unique constant for the given
389 /// selector's name. The return value has type char *.
390
391 // FIXME: This is a horrible name.
392 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000393 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000394
395 /// GetPropertyName - Return a unique constant for the given
396 /// name. The return value has type char *.
397 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
398
399 // FIXME: This can be dropped once string functions are unified.
400 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
401 const Decl *Container);
402
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000403 /// GetClassName - Return a unique constant for the given selector's
404 /// name. The return value has type char *.
405 llvm::Constant *GetClassName(IdentifierInfo *Ident);
406
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000407 /// BuildIvarLayout - Builds ivar layout bitmap for the class
408 /// implementation for the __strong or __weak case.
409 ///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000410 llvm::Constant *BuildIvarLayout(const llvm::StructLayout *Layout,
411 ObjCImplementationDecl *OI,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000412 bool ForStrongLayout);
413
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000414 void BuildAggrIvarLayout(const llvm::StructLayout *Layout,
415 const RecordDecl *RD,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000416 const std::vector<FieldDecl*>& RecFields,
417 unsigned int BytePos, bool ForStrongLayout,
418 int &Index, int &SkIndex, bool &HasUnion);
419
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000420 /// GetIvarLayoutName - Returns a unique constant for the given
421 /// ivar layout bitmap.
422 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
423 const ObjCCommonTypesHelper &ObjCTypes);
424
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000425 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
426 RecordDecl::field_iterator &FIV,
427 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000428 /// EmitPropertyList - Emit the given property list. The return
429 /// value has type PropertyListPtrTy.
430 llvm::Constant *EmitPropertyList(const std::string &Name,
431 const Decl *Container,
432 const ObjCContainerDecl *OCD,
433 const ObjCCommonTypesHelper &ObjCTypes);
434
Fariborz Jahanianda320092009-01-29 19:24:30 +0000435 /// GetProtocolRef - Return a reference to the internal protocol
436 /// description, creating an empty one if it has not been
437 /// defined. The return value has type ProtocolPtrTy.
438 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000439
440 /// GetIvarBaseOffset - returns ivars byte offset.
441 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
442 FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000443
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000444 /// CreateMetadataVar - Create a global variable with internal
445 /// linkage for use by the Objective-C runtime.
446 ///
447 /// This is a convenience wrapper which not only creates the
448 /// variable, but also sets the section and alignment and adds the
449 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000450 ///
451 /// \param Name - The variable name.
452 /// \param Init - The variable initializer; this is also used to
453 /// define the type of the variable.
454 /// \param Section - The section the variable should go into, or 0.
455 /// \param Align - The alignment for the variable, or 0.
456 /// \param AddToUsed - Whether the variable should be added to
457 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000458 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
459 llvm::Constant *Init,
460 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000461 unsigned Align,
462 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000463
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000464public:
465 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
466 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000467
468 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000469
470 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
471 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000472
473 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
474
475 /// GetOrEmitProtocol - Get the protocol object for the given
476 /// declaration, emitting it if necessary. The return value has type
477 /// ProtocolPtrTy.
478 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
479
480 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
481 /// object for the given declaration, emitting it if needed. These
482 /// forward references will be filled in with empty bodies if no
483 /// definition is seen. The return value has type ProtocolPtrTy.
484 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000485};
486
487class CGObjCMac : public CGObjCCommonMac {
488private:
489 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000490 /// EmitImageInfo - Emit the image info marker used to encode some module
491 /// level information.
492 void EmitImageInfo();
493
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000494 /// EmitModuleInfo - Another marker encoding module level
495 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000496 void EmitModuleInfo();
497
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000498 /// EmitModuleSymols - Emit module symbols, the list of defined
499 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000500 llvm::Constant *EmitModuleSymbols();
501
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000502 /// FinishModule - Write out global data structures at the end of
503 /// processing a translation unit.
504 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000505
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000506 /// EmitClassExtension - Generate the class extension structure used
507 /// to store the weak ivar layout and properties. The return value
508 /// has type ClassExtensionPtrTy.
509 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
510
511 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
512 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000513 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000514 const ObjCInterfaceDecl *ID);
515
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000516 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000517 QualType ResultType,
518 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000519 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000520 QualType Arg0Ty,
521 bool IsSuper,
522 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000523
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000524 /// EmitIvarList - Emit the ivar list for the given
525 /// implementation. If ForClass is true the list of class ivars
526 /// (i.e. metaclass ivars) is emitted, otherwise the list of
527 /// interface ivars will be emitted. The return value has type
528 /// IvarListPtrTy.
529 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000530 bool ForClass);
531
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000532 /// EmitMetaClass - Emit a forward reference to the class structure
533 /// for the metaclass of the given interface. The return value has
534 /// type ClassPtrTy.
535 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
536
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000537 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000538 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000539 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
540 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000541 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000542 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000543
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000544 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000545
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000546 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000547
548 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000549 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000550 llvm::Constant *EmitMethodList(const std::string &Name,
551 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000552 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000553
554 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000555 /// method declarations.
556 /// - TypeName: The name for the type containing the methods.
557 /// - IsProtocol: True iff these methods are for a protocol.
558 /// - ClassMethds: True iff these are class methods.
559 /// - Required: When true, only "required" methods are
560 /// listed. Similarly, when false only "optional" methods are
561 /// listed. For classes this should always be true.
562 /// - begin, end: The method list to output.
563 ///
564 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000565 llvm::Constant *EmitMethodDescList(const std::string &Name,
566 const char *Section,
567 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000568
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000569 /// GetOrEmitProtocol - Get the protocol object for the given
570 /// declaration, emitting it if necessary. The return value has type
571 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000572 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000573
574 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
575 /// object for the given declaration, emitting it if needed. These
576 /// forward references will be filled in with empty bodies if no
577 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000578 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000579
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000580 /// EmitProtocolExtension - Generate the protocol extension
581 /// structure used to store optional instance and class methods, and
582 /// protocol properties. The return value has type
583 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000584 llvm::Constant *
585 EmitProtocolExtension(const ObjCProtocolDecl *PD,
586 const ConstantVector &OptInstanceMethods,
587 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000588
589 /// EmitProtocolList - Generate the list of referenced
590 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000591 llvm::Constant *EmitProtocolList(const std::string &Name,
592 ObjCProtocolDecl::protocol_iterator begin,
593 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000594
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000595 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
596 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000597 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000598
Fariborz Jahanianda320092009-01-29 19:24:30 +0000599 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000600 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000601
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000602 virtual llvm::Function *ModuleInitFunction();
603
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000604 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000605 QualType ResultType,
606 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000607 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000608 bool IsClassMessage,
609 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000610
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000611 virtual CodeGen::RValue
612 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000613 QualType ResultType,
614 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000615 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000616 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000617 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000618 bool IsClassMessage,
619 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000620
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000621 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000622 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000623
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000624 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000625
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000626 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000627
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000628 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000629
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000630 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000631 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000632
Daniel Dunbar49f66022008-09-24 03:38:44 +0000633 virtual llvm::Function *GetPropertyGetFunction();
634 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000635 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000636
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000637 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
638 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000639 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
640 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000641 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000642 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000643 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
644 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000645 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
646 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000647 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
648 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000649 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
650 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000651
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000652 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
653 QualType ObjectTy,
654 llvm::Value *BaseValue,
655 const ObjCIvarDecl *Ivar,
656 const FieldDecl *Field,
657 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000658 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
659 ObjCInterfaceDecl *Interface,
660 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000661};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000662
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000663class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000664private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000665 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000666 llvm::GlobalVariable* ObjCEmptyCacheVar;
667 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000668
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000669 /// MetaClassReferences - uniqued meta class references.
670 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000671
672 /// EHTypeReferences - uniqued class ehtype references.
673 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000674
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000675 /// FinishNonFragileABIModule - Write out global data structures at the end of
676 /// processing a translation unit.
677 void FinishNonFragileABIModule();
678
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000679 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
680 unsigned InstanceStart,
681 unsigned InstanceSize,
682 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000683 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
684 llvm::Constant *IsAGV,
685 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000686 llvm::Constant *ClassRoGV,
687 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000688
689 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
690
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000691 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
692
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000693 /// EmitMethodList - Emit the method list for the given
694 /// implementation. The return value has type MethodListnfABITy.
695 llvm::Constant *EmitMethodList(const std::string &Name,
696 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000697 const ConstantVector &Methods);
698 /// EmitIvarList - Emit the ivar list for the given
699 /// implementation. If ForClass is true the list of class ivars
700 /// (i.e. metaclass ivars) is emitted, otherwise the list of
701 /// interface ivars will be emitted. The return value has type
702 /// IvarListnfABIPtrTy.
703 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000704
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000705 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000706 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000707 unsigned long int offset);
708
Fariborz Jahanianda320092009-01-29 19:24:30 +0000709 /// GetOrEmitProtocol - Get the protocol object for the given
710 /// declaration, emitting it if necessary. The return value has type
711 /// ProtocolPtrTy.
712 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
713
714 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
715 /// object for the given declaration, emitting it if needed. These
716 /// forward references will be filled in with empty bodies if no
717 /// definition is seen. The return value has type ProtocolPtrTy.
718 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
719
720 /// EmitProtocolList - Generate the list of referenced
721 /// protocols. The return value has type ProtocolListPtrTy.
722 llvm::Constant *EmitProtocolList(const std::string &Name,
723 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000724 ObjCProtocolDecl::protocol_iterator end);
725
726 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
727 QualType ResultType,
728 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000729 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000730 QualType Arg0Ty,
731 bool IsSuper,
732 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000733
734 /// GetClassGlobal - Return the global variable for the Objective-C
735 /// class of the given name.
736 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000737
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000738 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
739 /// for the given class.
740 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000741 const ObjCInterfaceDecl *ID,
742 bool IsSuper = false);
743
744 /// EmitMetaClassRef - Return a Value * of the address of _class_t
745 /// meta-data
746 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
747 const ObjCInterfaceDecl *ID);
748
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000749 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
750 /// the given ivar.
751 ///
752 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000753 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000754 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000755
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000756 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
757 /// for the given selector.
758 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000759
760 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
761 /// interface. The return value has type EHTypePtrTy.
762 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000763
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000764public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000765 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000766 // FIXME. All stubs for now!
767 virtual llvm::Function *ModuleInitFunction();
768
769 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
770 QualType ResultType,
771 Selector Sel,
772 llvm::Value *Receiver,
773 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000774 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000775
776 virtual CodeGen::RValue
777 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
778 QualType ResultType,
779 Selector Sel,
780 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000781 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000782 llvm::Value *Receiver,
783 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000784 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000785
786 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000787 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000788
789 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000790 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000791
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000792 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000793
794 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000795 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000796 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000797
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000798 virtual llvm::Function *GetPropertyGetFunction(){
799 return ObjCTypes.GetPropertyFn;
800 }
801 virtual llvm::Function *GetPropertySetFunction(){
802 return ObjCTypes.SetPropertyFn;
803 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000804 virtual llvm::Function *EnumerationMutationFunction() {
805 return ObjCTypes.EnumerationMutationFn;
806 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000807
808 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000809 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000811 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000812 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000813 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000814 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000815 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000816 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000817 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000818 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000819 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000820 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000821 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000822 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
823 QualType ObjectTy,
824 llvm::Value *BaseValue,
825 const ObjCIvarDecl *Ivar,
826 const FieldDecl *Field,
827 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000828 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
829 ObjCInterfaceDecl *Interface,
830 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000831};
832
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000833} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000834
835/* *** Helper Functions *** */
836
837/// getConstantGEP() - Help routine to construct simple GEPs.
838static llvm::Constant *getConstantGEP(llvm::Constant *C,
839 unsigned idx0,
840 unsigned idx1) {
841 llvm::Value *Idxs[] = {
842 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
843 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
844 };
845 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
846}
847
848/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000849
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000850CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
851 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000852{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000853 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000854 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000855}
856
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000857/// GetClass - Return a reference to the class for the given interface
858/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000859llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000860 const ObjCInterfaceDecl *ID) {
861 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000862}
863
864/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000865llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000866 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000867}
868
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000869/// Generate a constant CFString object.
870/*
871 struct __builtin_CFString {
872 const int *isa; // point to __CFConstantStringClassReference
873 int flags;
874 const char *str;
875 long length;
876 };
877*/
878
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000879llvm::Constant *CGObjCCommonMac::GenerateConstantString(
880 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000881 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000882}
883
884/// Generates a message send where the super is the receiver. This is
885/// a message send to self with special delivery semantics indicating
886/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000887CodeGen::RValue
888CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000889 QualType ResultType,
890 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000891 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000892 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000893 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000894 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000895 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000896 // Create and init a super structure; this is a (receiver, class)
897 // pair we will pass to objc_msgSendSuper.
898 llvm::Value *ObjCSuper =
899 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
900 llvm::Value *ReceiverAsObject =
901 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
902 CGF.Builder.CreateStore(ReceiverAsObject,
903 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000904
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000905 // If this is a class message the metaclass is passed as the target.
906 llvm::Value *Target;
907 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000908 if (isCategoryImpl) {
909 // Message sent to 'super' in a class method defined in a category
910 // implementation requires an odd treatment.
911 // If we are in a class method, we must retrieve the
912 // _metaclass_ for the current class, pointed at by
913 // the class's "isa" pointer. The following assumes that
914 // isa" is the first ivar in a class (which it must be).
915 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
916 Target = CGF.Builder.CreateStructGEP(Target, 0);
917 Target = CGF.Builder.CreateLoad(Target);
918 }
919 else {
920 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
921 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
922 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
923 Target = Super;
924 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000925 } else {
926 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
927 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000928 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
929 // and ObjCTypes types.
930 const llvm::Type *ClassTy =
931 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000932 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000933 CGF.Builder.CreateStore(Target,
934 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
935
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000936 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000937 ObjCSuper, ObjCTypes.SuperPtrCTy,
938 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000939}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000940
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000941/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000942CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000943 QualType ResultType,
944 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000945 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000946 bool IsClassMessage,
947 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000948 llvm::Value *Arg0 =
949 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000950 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000951 Arg0, CGF.getContext().getObjCIdType(),
952 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000953}
954
955CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000956 QualType ResultType,
957 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000958 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000959 QualType Arg0Ty,
960 bool IsSuper,
961 const CallArgList &CallArgs) {
962 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000963 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
964 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
965 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000966 CGF.getContext().getObjCSelType()));
967 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000968
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000969 CodeGenTypes &Types = CGM.getTypes();
970 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
971 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000972
973 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000974 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000975 Fn = ObjCTypes.getSendStretFn(IsSuper);
976 } else if (ResultType->isFloatingType()) {
977 // FIXME: Sadly, this is wrong. This actually depends on the
978 // architecture. This happens to be right for x86-32 though.
979 Fn = ObjCTypes.getSendFpretFn(IsSuper);
980 } else {
981 Fn = ObjCTypes.getSendFn(IsSuper);
982 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000983 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000984 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000985}
986
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000987llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000988 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000989 // FIXME: I don't understand why gcc generates this, or where it is
990 // resolved. Investigate. Its also wasteful to look this up over and
991 // over.
992 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
993
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000994 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
995 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000996}
997
Fariborz Jahanianda320092009-01-29 19:24:30 +0000998void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000999 // FIXME: We shouldn't need this, the protocol decl should contain
1000 // enough information to tell us whether this was a declaration or a
1001 // definition.
1002 DefinedProtocols.insert(PD->getIdentifier());
1003
1004 // If we have generated a forward reference to this protocol, emit
1005 // it now. Otherwise do nothing, the protocol objects are lazily
1006 // emitted.
1007 if (Protocols.count(PD->getIdentifier()))
1008 GetOrEmitProtocol(PD);
1009}
1010
Fariborz Jahanianda320092009-01-29 19:24:30 +00001011llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001012 if (DefinedProtocols.count(PD->getIdentifier()))
1013 return GetOrEmitProtocol(PD);
1014 return GetOrEmitProtocolRef(PD);
1015}
1016
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001017/*
1018 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1019 struct _objc_protocol {
1020 struct _objc_protocol_extension *isa;
1021 char *protocol_name;
1022 struct _objc_protocol_list *protocol_list;
1023 struct _objc__method_prototype_list *instance_methods;
1024 struct _objc__method_prototype_list *class_methods
1025 };
1026
1027 See EmitProtocolExtension().
1028*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001029llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1030 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1031
1032 // Early exit if a defining object has already been generated.
1033 if (Entry && Entry->hasInitializer())
1034 return Entry;
1035
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001036 // FIXME: I don't understand why gcc generates this, or where it is
1037 // resolved. Investigate. Its also wasteful to look this up over and
1038 // over.
1039 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1040
Chris Lattner8ec03f52008-11-24 03:54:41 +00001041 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001042
1043 // Construct method lists.
1044 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1045 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1046 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1047 e = PD->instmeth_end(); i != e; ++i) {
1048 ObjCMethodDecl *MD = *i;
1049 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1050 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1051 OptInstanceMethods.push_back(C);
1052 } else {
1053 InstanceMethods.push_back(C);
1054 }
1055 }
1056
1057 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1058 e = PD->classmeth_end(); i != e; ++i) {
1059 ObjCMethodDecl *MD = *i;
1060 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1061 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1062 OptClassMethods.push_back(C);
1063 } else {
1064 ClassMethods.push_back(C);
1065 }
1066 }
1067
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001068 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001069 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001070 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001071 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001072 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001073 PD->protocol_begin(),
1074 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001075 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001076 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1077 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001078 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1079 InstanceMethods);
1080 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001081 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1082 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001083 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1084 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001085 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1086 Values);
1087
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001088 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001089 // Already created, fix the linkage and update the initializer.
1090 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001091 Entry->setInitializer(Init);
1092 } else {
1093 Entry =
1094 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1095 llvm::GlobalValue::InternalLinkage,
1096 Init,
1097 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1098 &CGM.getModule());
1099 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001100 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001101 UsedGlobals.push_back(Entry);
1102 // FIXME: Is this necessary? Why only for protocol?
1103 Entry->setAlignment(4);
1104 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001105
1106 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001107}
1108
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001109llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001110 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1111
1112 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001113 // We use the initializer as a marker of whether this is a forward
1114 // reference or not. At module finalization we add the empty
1115 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001116 Entry =
1117 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001118 llvm::GlobalValue::ExternalLinkage,
1119 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001121 &CGM.getModule());
1122 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001123 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001124 UsedGlobals.push_back(Entry);
1125 // FIXME: Is this necessary? Why only for protocol?
1126 Entry->setAlignment(4);
1127 }
1128
1129 return Entry;
1130}
1131
1132/*
1133 struct _objc_protocol_extension {
1134 uint32_t size;
1135 struct objc_method_description_list *optional_instance_methods;
1136 struct objc_method_description_list *optional_class_methods;
1137 struct objc_property_list *instance_properties;
1138 };
1139*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001140llvm::Constant *
1141CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1142 const ConstantVector &OptInstanceMethods,
1143 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001145 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001146 std::vector<llvm::Constant*> Values(4);
1147 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001148 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001149 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1150 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001151 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1152 OptInstanceMethods);
1153 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001154 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1155 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001156 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1157 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001158 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1159 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001160 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001161
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001162 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001163 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1164 Values[3]->isNullValue())
1165 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1166
1167 llvm::Constant *Init =
1168 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001169
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001170 // No special section, but goes in llvm.used
1171 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1172 Init,
1173 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001174}
1175
1176/*
1177 struct objc_protocol_list {
1178 struct objc_protocol_list *next;
1179 long count;
1180 Protocol *list[];
1181 };
1182*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001183llvm::Constant *
1184CGObjCMac::EmitProtocolList(const std::string &Name,
1185 ObjCProtocolDecl::protocol_iterator begin,
1186 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001187 std::vector<llvm::Constant*> ProtocolRefs;
1188
Daniel Dunbardbc933702008-08-21 21:57:41 +00001189 for (; begin != end; ++begin)
1190 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001191
1192 // Just return null for empty protocol lists
1193 if (ProtocolRefs.empty())
1194 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1195
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001196 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001197 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1198
1199 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001200 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001201 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1202 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1203 Values[2] =
1204 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1205 ProtocolRefs.size()),
1206 ProtocolRefs);
1207
1208 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1209 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001210 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001211 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001212 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1213}
1214
1215/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001216 struct _objc_property {
1217 const char * const name;
1218 const char * const attributes;
1219 };
1220
1221 struct _objc_property_list {
1222 uint32_t entsize; // sizeof (struct _objc_property)
1223 uint32_t prop_count;
1224 struct _objc_property[prop_count];
1225 };
1226*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001227llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1228 const Decl *Container,
1229 const ObjCContainerDecl *OCD,
1230 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001231 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001232 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1233 E = OCD->prop_end(); I != E; ++I) {
1234 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001235 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001236 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001237 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1238 Prop));
1239 }
1240
1241 // Return null for empty list.
1242 if (Properties.empty())
1243 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1244
1245 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001246 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001247 std::vector<llvm::Constant*> Values(3);
1248 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1249 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1250 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1251 Properties.size());
1252 Values[2] = llvm::ConstantArray::get(AT, Properties);
1253 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1254
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001255 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001256 llvm::GlobalVariable *GV =
1257 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1258 0, true);
1259 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001260}
1261
1262/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001263 struct objc_method_description_list {
1264 int count;
1265 struct objc_method_description list[];
1266 };
1267*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001268llvm::Constant *
1269CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1270 std::vector<llvm::Constant*> Desc(2);
1271 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1272 ObjCTypes.SelectorPtrTy);
1273 Desc[1] = GetMethodVarType(MD);
1274 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1275 Desc);
1276}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001277
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001278llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1279 const char *Section,
1280 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001281 // Return null for empty list.
1282 if (Methods.empty())
1283 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1284
1285 std::vector<llvm::Constant*> Values(2);
1286 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1287 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1288 Methods.size());
1289 Values[1] = llvm::ConstantArray::get(AT, Methods);
1290 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1291
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001292 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001293 return llvm::ConstantExpr::getBitCast(GV,
1294 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001295}
1296
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001297/*
1298 struct _objc_category {
1299 char *category_name;
1300 char *class_name;
1301 struct _objc_method_list *instance_methods;
1302 struct _objc_method_list *class_methods;
1303 struct _objc_protocol_list *protocols;
1304 uint32_t size; // <rdar://4585769>
1305 struct _objc_property_list *instance_properties;
1306 };
1307 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001308void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001309 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001310
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001311 // FIXME: This is poor design, the OCD should have a pointer to the
1312 // category decl. Additionally, note that Category can be null for
1313 // the @implementation w/o an @interface case. Sema should just
1314 // create one for us as it does for @implementation so everyone else
1315 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001316 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001317 const ObjCCategoryDecl *Category =
1318 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001319 std::string ExtName(Interface->getNameAsString() + "_" +
1320 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001321
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001322 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1323 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1324 e = OCD->instmeth_end(); i != e; ++i) {
1325 // Instance methods should always be defined.
1326 InstanceMethods.push_back(GetMethodConstant(*i));
1327 }
1328 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1329 e = OCD->classmeth_end(); i != e; ++i) {
1330 // Class methods should always be defined.
1331 ClassMethods.push_back(GetMethodConstant(*i));
1332 }
1333
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001334 std::vector<llvm::Constant*> Values(7);
1335 Values[0] = GetClassName(OCD->getIdentifier());
1336 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001337 Values[2] =
1338 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1339 ExtName,
1340 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001341 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001342 Values[3] =
1343 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1344 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001345 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001346 if (Category) {
1347 Values[4] =
1348 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1349 Category->protocol_begin(),
1350 Category->protocol_end());
1351 } else {
1352 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1353 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001354 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001355
1356 // If there is no category @interface then there can be no properties.
1357 if (Category) {
1358 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001359 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001360 } else {
1361 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1362 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001363
1364 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1365 Values);
1366
1367 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001368 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1369 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001370 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001371 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001372}
1373
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001374// FIXME: Get from somewhere?
1375enum ClassFlags {
1376 eClassFlags_Factory = 0x00001,
1377 eClassFlags_Meta = 0x00002,
1378 // <rdr://5142207>
1379 eClassFlags_HasCXXStructors = 0x02000,
1380 eClassFlags_Hidden = 0x20000,
1381 eClassFlags_ABI2_Hidden = 0x00010,
1382 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1383};
1384
1385// <rdr://5142207&4705298&4843145>
1386static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1387 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1388 // FIXME: Support -fvisibility
1389 switch (attr->getVisibility()) {
1390 default:
1391 assert(0 && "Unknown visibility");
1392 return false;
1393 case VisibilityAttr::DefaultVisibility:
1394 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1395 return false;
1396 case VisibilityAttr::HiddenVisibility:
1397 return true;
1398 }
1399 } else {
1400 return false; // FIXME: Support -fvisibility
1401 }
1402}
1403
1404/*
1405 struct _objc_class {
1406 Class isa;
1407 Class super_class;
1408 const char *name;
1409 long version;
1410 long info;
1411 long instance_size;
1412 struct _objc_ivar_list *ivars;
1413 struct _objc_method_list *methods;
1414 struct _objc_cache *cache;
1415 struct _objc_protocol_list *protocols;
1416 // Objective-C 1.0 extensions (<rdr://4585769>)
1417 const char *ivar_layout;
1418 struct _objc_class_ext *ext;
1419 };
1420
1421 See EmitClassExtension();
1422 */
1423void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001424 DefinedSymbols.insert(ID->getIdentifier());
1425
Chris Lattner8ec03f52008-11-24 03:54:41 +00001426 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427 // FIXME: Gross
1428 ObjCInterfaceDecl *Interface =
1429 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001430 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001431 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001432 Interface->protocol_begin(),
1433 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001434 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001435 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001436 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001437 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001438
1439 // FIXME: Set CXX-structors flag.
1440 if (IsClassHidden(ID->getClassInterface()))
1441 Flags |= eClassFlags_Hidden;
1442
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001443 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1444 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1445 e = ID->instmeth_end(); i != e; ++i) {
1446 // Instance methods should always be defined.
1447 InstanceMethods.push_back(GetMethodConstant(*i));
1448 }
1449 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1450 e = ID->classmeth_end(); i != e; ++i) {
1451 // Class methods should always be defined.
1452 ClassMethods.push_back(GetMethodConstant(*i));
1453 }
1454
1455 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1456 e = ID->propimpl_end(); i != e; ++i) {
1457 ObjCPropertyImplDecl *PID = *i;
1458
1459 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1460 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1461
1462 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1463 if (llvm::Constant *C = GetMethodConstant(MD))
1464 InstanceMethods.push_back(C);
1465 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1466 if (llvm::Constant *C = GetMethodConstant(MD))
1467 InstanceMethods.push_back(C);
1468 }
1469 }
1470
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001472 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001473 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001474 // Record a reference to the super class.
1475 LazySymbols.insert(Super->getIdentifier());
1476
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001477 Values[ 1] =
1478 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1479 ObjCTypes.ClassPtrTy);
1480 } else {
1481 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1482 }
1483 Values[ 2] = GetClassName(ID->getIdentifier());
1484 // Version is always 0.
1485 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1486 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1487 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001488 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001489 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001490 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001491 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001492 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493 // cache is always NULL.
1494 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1495 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001496 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001497 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001498 Values[11] = EmitClassExtension(ID);
1499 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1500 Values);
1501
1502 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001503 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1504 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001505 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 DefinedClasses.push_back(GV);
1507}
1508
1509llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1510 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001511 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001512 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001513 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001514 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001515
1516 if (IsClassHidden(ID->getClassInterface()))
1517 Flags |= eClassFlags_Hidden;
1518
1519 std::vector<llvm::Constant*> Values(12);
1520 // The isa for the metaclass is the root of the hierarchy.
1521 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1522 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1523 Root = Super;
1524 Values[ 0] =
1525 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1526 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001527 // The super class for the metaclass is emitted as the name of the
1528 // super class. The runtime fixes this up to point to the
1529 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1531 Values[ 1] =
1532 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1533 ObjCTypes.ClassPtrTy);
1534 } else {
1535 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1536 }
1537 Values[ 2] = GetClassName(ID->getIdentifier());
1538 // Version is always 0.
1539 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1540 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1541 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001542 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001543 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001544 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001545 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001546 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001547 // cache is always NULL.
1548 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1549 Values[ 9] = Protocols;
1550 // ivar_layout for metaclass is always NULL.
1551 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1552 // The class extension is always unused for metaclasses.
1553 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1554 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1555 Values);
1556
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001557 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001558 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001559
1560 // Check for a forward reference.
1561 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1562 if (GV) {
1563 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1564 "Forward metaclass reference has incorrect type.");
1565 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1566 GV->setInitializer(Init);
1567 } else {
1568 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1569 llvm::GlobalValue::InternalLinkage,
1570 Init, Name,
1571 &CGM.getModule());
1572 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001573 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001574 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001575 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001576
1577 return GV;
1578}
1579
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001580llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001581 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001582
1583 // FIXME: Should we look these up somewhere other than the
1584 // module. Its a bit silly since we only generate these while
1585 // processing an implementation, so exactly one pointer would work
1586 // if know when we entered/exitted an implementation block.
1587
1588 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001589 // Previously, metaclass with internal linkage may have been defined.
1590 // pass 'true' as 2nd argument so it is returned.
1591 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001592 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1593 "Forward metaclass reference has incorrect type.");
1594 return GV;
1595 } else {
1596 // Generate as an external reference to keep a consistent
1597 // module. This will be patched up when we emit the metaclass.
1598 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1599 llvm::GlobalValue::ExternalLinkage,
1600 0,
1601 Name,
1602 &CGM.getModule());
1603 }
1604}
1605
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001606/*
1607 struct objc_class_ext {
1608 uint32_t size;
1609 const char *weak_ivar_layout;
1610 struct _objc_property_list *properties;
1611 };
1612*/
1613llvm::Constant *
1614CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1615 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001616 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001617
1618 std::vector<llvm::Constant*> Values(3);
1619 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001620 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001621 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001622 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001623 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001624
1625 // Return null if no extension bits are used.
1626 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1627 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1628
1629 llvm::Constant *Init =
1630 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001631 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1632 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001633}
1634
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001635/// countInheritedIvars - count number of ivars in class and its super class(s)
1636///
1637static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1638 int count = 0;
1639 if (!OI)
1640 return 0;
1641 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1642 if (SuperClass)
1643 count += countInheritedIvars(SuperClass);
1644 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1645 E = OI->ivar_end(); I != E; ++I)
1646 ++count;
1647 return count;
1648}
1649
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001650/// getInterfaceDeclForIvar - Get the interface declaration node where
1651/// this ivar is declared in.
1652/// FIXME. Ideally, this info should be in the ivar node. But currently
1653/// it is not and prevailing wisdom is that ASTs should not have more
1654/// info than is absolutely needed, even though this info reflects the
1655/// source language.
1656///
1657static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1658 const ObjCInterfaceDecl *OI,
1659 const ObjCIvarDecl *IVD) {
1660 if (!OI)
1661 return 0;
1662 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1663 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1664 E = OI->ivar_end(); I != E; ++I)
1665 if ((*I)->getIdentifier() == IVD->getIdentifier())
1666 return OI;
1667 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1668}
1669
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001670/*
1671 struct objc_ivar {
1672 char *ivar_name;
1673 char *ivar_type;
1674 int ivar_offset;
1675 };
1676
1677 struct objc_ivar_list {
1678 int ivar_count;
1679 struct objc_ivar list[count];
1680 };
1681 */
1682llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001683 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001684 std::vector<llvm::Constant*> Ivars, Ivar(3);
1685
1686 // When emitting the root class GCC emits ivar entries for the
1687 // actual class structure. It is not clear if we need to follow this
1688 // behavior; for now lets try and get away with not doing it. If so,
1689 // the cleanest solution would be to make up an ObjCInterfaceDecl
1690 // for the class.
1691 if (ForClass)
1692 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001693
1694 ObjCInterfaceDecl *OID =
1695 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1696 const llvm::Type *InterfaceTy =
1697 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001698 const llvm::StructLayout *Layout =
1699 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001700
1701 RecordDecl::field_iterator ifield, pfield;
1702 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001703 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1704 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001705 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001706 if (Field->getIdentifier())
1707 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1708 else
1709 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001710 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001711 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001712 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001713 }
1714
1715 // Return null for empty list.
1716 if (Ivars.empty())
1717 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1718
1719 std::vector<llvm::Constant*> Values(2);
1720 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1721 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1722 Ivars.size());
1723 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1724 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1725
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001726 llvm::GlobalVariable *GV;
1727 if (ForClass)
1728 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001729 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1730 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001731 else
1732 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1733 + ID->getNameAsString(),
1734 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1735 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001736 return llvm::ConstantExpr::getBitCast(GV,
1737 ObjCTypes.IvarListPtrTy);
1738}
1739
1740/*
1741 struct objc_method {
1742 SEL method_name;
1743 char *method_types;
1744 void *method;
1745 };
1746
1747 struct objc_method_list {
1748 struct objc_method_list *obsolete;
1749 int count;
1750 struct objc_method methods_list[count];
1751 };
1752*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001753
1754/// GetMethodConstant - Return a struct objc_method constant for the
1755/// given method if it has been defined. The result is null if the
1756/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001757llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001758 // FIXME: Use DenseMap::lookup
1759 llvm::Function *Fn = MethodDefinitions[MD];
1760 if (!Fn)
1761 return 0;
1762
1763 std::vector<llvm::Constant*> Method(3);
1764 Method[0] =
1765 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1766 ObjCTypes.SelectorPtrTy);
1767 Method[1] = GetMethodVarType(MD);
1768 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1769 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1770}
1771
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001772llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1773 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001774 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001775 // Return null for empty list.
1776 if (Methods.empty())
1777 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1778
1779 std::vector<llvm::Constant*> Values(3);
1780 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1781 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1782 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1783 Methods.size());
1784 Values[2] = llvm::ConstantArray::get(AT, Methods);
1785 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1786
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001787 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001788 return llvm::ConstantExpr::getBitCast(GV,
1789 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001790}
1791
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001792llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001793 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001794 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001795 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001796
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001797 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001798 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001799 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001800 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001801 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001802 llvm::GlobalValue::InternalLinkage,
1803 Name,
1804 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001805 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001806
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001807 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001808}
1809
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001810uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
1811 FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001812 if (!Field->isBitField())
1813 return Layout->getElementOffset(
1814 CGM.getTypes().getLLVMFieldNo(Field));
1815 // FIXME. Must be a better way of getting a bitfield base offset.
1816 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1817 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1818 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1819 offset = (offset*size)/8;
1820 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001821}
1822
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001823llvm::GlobalVariable *
1824CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1825 llvm::Constant *Init,
1826 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001827 unsigned Align,
1828 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001829 const llvm::Type *Ty = Init->getType();
1830 llvm::GlobalVariable *GV =
1831 new llvm::GlobalVariable(Ty, false,
1832 llvm::GlobalValue::InternalLinkage,
1833 Init,
1834 Name,
1835 &CGM.getModule());
1836 if (Section)
1837 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001838 if (Align)
1839 GV->setAlignment(Align);
1840 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001841 UsedGlobals.push_back(GV);
1842 return GV;
1843}
1844
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001845llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001846 // Abuse this interface function as a place to finalize.
1847 FinishModule();
1848
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001849 return NULL;
1850}
1851
Daniel Dunbar49f66022008-09-24 03:38:44 +00001852llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1853 return ObjCTypes.GetPropertyFn;
1854}
1855
1856llvm::Function *CGObjCMac::GetPropertySetFunction() {
1857 return ObjCTypes.SetPropertyFn;
1858}
1859
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001860llvm::Function *CGObjCMac::EnumerationMutationFunction()
1861{
1862 return ObjCTypes.EnumerationMutationFn;
1863}
1864
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001865/*
1866
1867Objective-C setjmp-longjmp (sjlj) Exception Handling
1868--
1869
1870The basic framework for a @try-catch-finally is as follows:
1871{
1872 objc_exception_data d;
1873 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001874 bool _call_try_exit = true;
1875
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001876 objc_exception_try_enter(&d);
1877 if (!setjmp(d.jmp_buf)) {
1878 ... try body ...
1879 } else {
1880 // exception path
1881 id _caught = objc_exception_extract(&d);
1882
1883 // enter new try scope for handlers
1884 if (!setjmp(d.jmp_buf)) {
1885 ... match exception and execute catch blocks ...
1886
1887 // fell off end, rethrow.
1888 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001889 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001890 } else {
1891 // exception in catch block
1892 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001893 _call_try_exit = false;
1894 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001895 }
1896 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001897 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001898
1899finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001900 if (_call_try_exit)
1901 objc_exception_try_exit(&d);
1902
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001903 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001904 ... dispatch to finally destination ...
1905
1906finally_rethrow:
1907 objc_exception_throw(_rethrow);
1908
1909finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001910}
1911
1912This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001913uses _rethrow to determine if objc_exception_try_exit should be called
1914and if the object should be rethrown. This breaks in the face of
1915throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001916
1917We specialize this framework for a few particular circumstances:
1918
1919 - If there are no catch blocks, then we avoid emitting the second
1920 exception handling context.
1921
1922 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1923 e)) we avoid emitting the code to rethrow an uncaught exception.
1924
1925 - FIXME: If there is no @finally block we can do a few more
1926 simplifications.
1927
1928Rethrows and Jumps-Through-Finally
1929--
1930
1931Support for implicit rethrows and jumping through the finally block is
1932handled by storing the current exception-handling context in
1933ObjCEHStack.
1934
Daniel Dunbar898d5082008-09-30 01:06:03 +00001935In order to implement proper @finally semantics, we support one basic
1936mechanism for jumping through the finally block to an arbitrary
1937destination. Constructs which generate exits from a @try or @catch
1938block use this mechanism to implement the proper semantics by chaining
1939jumps, as necessary.
1940
1941This mechanism works like the one used for indirect goto: we
1942arbitrarily assign an ID to each destination and store the ID for the
1943destination in a variable prior to entering the finally block. At the
1944end of the finally block we simply create a switch to the proper
1945destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001946
1947Code gen for @synchronized(expr) stmt;
1948Effectively generating code for:
1949objc_sync_enter(expr);
1950@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001951*/
1952
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001953void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1954 const Stmt &S) {
1955 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001956 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001957 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001958 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001959 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1960 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1961 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001962
1963 // For @synchronized, call objc_sync_enter(sync.expr). The
1964 // evaluation of the expression must occur before we enter the
1965 // @synchronized. We can safely avoid a temp here because jumps into
1966 // @synchronized are illegal & this will dominate uses.
1967 llvm::Value *SyncArg = 0;
1968 if (!isTry) {
1969 SyncArg =
1970 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1971 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1972 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1973 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001974
1975 // Push an EH context entry, used for handling rethrows and jumps
1976 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001977 CGF.PushCleanupBlock(FinallyBlock);
1978
Anders Carlsson273558f2009-02-07 21:37:21 +00001979 CGF.ObjCEHValueStack.push_back(0);
1980
Daniel Dunbar898d5082008-09-30 01:06:03 +00001981 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001982 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1983 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001984 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1985 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001986 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1987 "_call_try_exit");
1988 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1989
Anders Carlsson80f25672008-09-09 17:59:25 +00001990 // Enter a new try block and call setjmp.
1991 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1992 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1993 "jmpbufarray");
1994 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1995 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1996 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001997
Daniel Dunbar55e87422008-11-11 02:29:29 +00001998 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1999 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002000 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002001 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002002
2003 // Emit the @try block.
2004 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002005 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2006 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002007 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002008
2009 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002010 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002011
2012 // Retrieve the exception object. We may emit multiple blocks but
2013 // nothing can cross this so the value is already in SSA form.
2014 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2015 ExceptionData,
2016 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002017 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002018 if (!isTry)
2019 {
2020 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002021 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002022 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002023 }
2024 else if (const ObjCAtCatchStmt* CatchStmt =
2025 cast<ObjCAtTryStmt>(S).getCatchStmts())
2026 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002027 // Enter a new exception try block (in case a @catch block throws
2028 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002029 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002030
Anders Carlsson80f25672008-09-09 17:59:25 +00002031 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2032 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002033 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002034
Daniel Dunbar55e87422008-11-11 02:29:29 +00002035 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2036 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002037 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002038
2039 CGF.EmitBlock(CatchBlock);
2040
Daniel Dunbar55e40722008-09-27 07:03:52 +00002041 // Handle catch list. As a special case we check if everything is
2042 // matched and avoid generating code for falling off the end if
2043 // so.
2044 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002045 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002046 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002047
Steve Naroff7ba138a2009-03-03 19:52:17 +00002048 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002049 const PointerType *PT = 0;
2050
Anders Carlsson80f25672008-09-09 17:59:25 +00002051 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002052 if (!CatchParam) {
2053 AllMatched = true;
2054 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002055 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002056
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002057 // catch(id e) always matches.
2058 // FIXME: For the time being we also match id<X>; this should
2059 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002060 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002061 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002062 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002063 }
2064
Daniel Dunbar55e40722008-09-27 07:03:52 +00002065 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002066 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002067 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002068 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002069 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002070 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002071
Anders Carlssondde0a942008-09-11 09:15:33 +00002072 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002073 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002074 break;
2075 }
2076
Daniel Dunbar129271a2008-09-27 07:36:24 +00002077 assert(PT && "Unexpected non-pointer type in @catch");
2078 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002079 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002080 assert(ObjCType && "Catch parameter must have Objective-C type!");
2081
2082 // Check if the @catch block matches the exception object.
2083 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2084
Anders Carlsson80f25672008-09-09 17:59:25 +00002085 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2086 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002087
Daniel Dunbar55e87422008-11-11 02:29:29 +00002088 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002089
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002090 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002091 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002092
2093 // Emit the @catch block.
2094 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002095 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002096 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002097
2098 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002099 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002100 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002101 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002102
2103 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002104 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002105
2106 CGF.EmitBlock(NextCatchBlock);
2107 }
2108
Daniel Dunbar55e40722008-09-27 07:03:52 +00002109 if (!AllMatched) {
2110 // None of the handlers caught the exception, so store it to be
2111 // rethrown at the end of the @finally block.
2112 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002113 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002114 }
2115
2116 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002117 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002118 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2119 ExceptionData),
2120 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002121 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002122 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002123 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002124 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002125 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002126 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002127 }
2128
Daniel Dunbar898d5082008-09-30 01:06:03 +00002129 // Pop the exception-handling stack entry. It is important to do
2130 // this now, because the code in the @finally block is not in this
2131 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002132 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2133
Anders Carlsson273558f2009-02-07 21:37:21 +00002134 CGF.ObjCEHValueStack.pop_back();
2135
Anders Carlsson80f25672008-09-09 17:59:25 +00002136 // Emit the @finally block.
2137 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002138 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2139
2140 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2141
2142 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002143 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002144
2145 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002146 if (isTry) {
2147 if (const ObjCAtFinallyStmt* FinallyStmt =
2148 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2149 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002150 } else {
2151 // Emit objc_sync_exit(expr); as finally's sole statement for
2152 // @synchronized.
2153 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002154 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002155
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002156 // Emit the switch block
2157 if (Info.SwitchBlock)
2158 CGF.EmitBlock(Info.SwitchBlock);
2159 if (Info.EndBlock)
2160 CGF.EmitBlock(Info.EndBlock);
2161
Daniel Dunbar898d5082008-09-30 01:06:03 +00002162 CGF.EmitBlock(FinallyRethrow);
2163 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2164 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002165 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002166
2167 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002168}
2169
2170void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002171 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002172 llvm::Value *ExceptionAsObject;
2173
2174 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2175 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2176 ExceptionAsObject =
2177 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2178 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002179 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002180 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002181 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002182 }
2183
2184 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002185 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002186
2187 // Clear the insertion point to indicate we are in unreachable code.
2188 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002189}
2190
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002191/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002192/// object: objc_read_weak (id *src)
2193///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002194llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002195 llvm::Value *AddrWeakObj)
2196{
Eli Friedman8339b352009-03-07 03:57:15 +00002197 const llvm::Type* DestTy =
2198 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002199 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002200 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002201 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002202 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002203 return read_weak;
2204}
2205
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002206/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2207/// objc_assign_weak (id src, id *dst)
2208///
2209void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2210 llvm::Value *src, llvm::Value *dst)
2211{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002212 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2213 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002214 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2215 src, dst, "weakassign");
2216 return;
2217}
2218
Fariborz Jahanian58626502008-11-19 00:59:10 +00002219/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2220/// objc_assign_global (id src, id *dst)
2221///
2222void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2223 llvm::Value *src, llvm::Value *dst)
2224{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002225 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2226 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002227 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2228 src, dst, "globalassign");
2229 return;
2230}
2231
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002232/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2233/// objc_assign_ivar (id src, id *dst)
2234///
2235void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2236 llvm::Value *src, llvm::Value *dst)
2237{
2238 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2239 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2240 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2241 src, dst, "assignivar");
2242 return;
2243}
2244
Fariborz Jahanian58626502008-11-19 00:59:10 +00002245/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2246/// objc_assign_strongCast (id src, id *dst)
2247///
2248void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2249 llvm::Value *src, llvm::Value *dst)
2250{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002251 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2252 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002253 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2254 src, dst, "weakassign");
2255 return;
2256}
2257
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002258/// EmitObjCValueForIvar - Code Gen for ivar reference.
2259///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002260LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2261 QualType ObjectTy,
2262 llvm::Value *BaseValue,
2263 const ObjCIvarDecl *Ivar,
2264 const FieldDecl *Field,
2265 unsigned CVRQualifiers) {
2266 if (Ivar->isBitField())
2267 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2268 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002269 // TODO: Add a special case for isa (index 0)
2270 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2271 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002272 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002273 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2274 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002275 LValue::SetObjCIvar(LV, true);
2276 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002277}
2278
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002279llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2280 ObjCInterfaceDecl *Interface,
2281 const ObjCIvarDecl *Ivar) {
2282 const llvm::Type *InterfaceLTy =
2283 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2284 const llvm::StructLayout *Layout =
2285 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2286 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002287 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002288 return llvm::ConstantInt::get(
2289 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2290 Offset);
2291}
2292
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002293/* *** Private Interface *** */
2294
2295/// EmitImageInfo - Emit the image info marker used to encode some module
2296/// level information.
2297///
2298/// See: <rdr://4810609&4810587&4810587>
2299/// struct IMAGE_INFO {
2300/// unsigned version;
2301/// unsigned flags;
2302/// };
2303enum ImageInfoFlags {
2304 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2305 eImageInfo_GarbageCollected = (1 << 1),
2306 eImageInfo_GCOnly = (1 << 2)
2307};
2308
2309void CGObjCMac::EmitImageInfo() {
2310 unsigned version = 0; // Version is unused?
2311 unsigned flags = 0;
2312
2313 // FIXME: Fix and continue?
2314 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2315 flags |= eImageInfo_GarbageCollected;
2316 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2317 flags |= eImageInfo_GCOnly;
2318
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002319 // Emitted as int[2];
2320 llvm::Constant *values[2] = {
2321 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2322 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2323 };
2324 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002325
2326 const char *Section;
2327 if (ObjCABI == 1)
2328 Section = "__OBJC, __image_info,regular";
2329 else
2330 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002331 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002332 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2333 llvm::ConstantArray::get(AT, values, 2),
2334 Section,
2335 0,
2336 true);
2337 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002338}
2339
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002340
2341// struct objc_module {
2342// unsigned long version;
2343// unsigned long size;
2344// const char *name;
2345// Symtab symtab;
2346// };
2347
2348// FIXME: Get from somewhere
2349static const int ModuleVersion = 7;
2350
2351void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002352 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002353
2354 std::vector<llvm::Constant*> Values(4);
2355 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2356 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002357 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002358 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002359 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002360 CreateMetadataVar("\01L_OBJC_MODULES",
2361 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2362 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002363 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002364}
2365
2366llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002367 unsigned NumClasses = DefinedClasses.size();
2368 unsigned NumCategories = DefinedCategories.size();
2369
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002370 // Return null if no symbols were defined.
2371 if (!NumClasses && !NumCategories)
2372 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2373
2374 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002375 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2376 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2377 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2378 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2379
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002380 // The runtime expects exactly the list of defined classes followed
2381 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002382 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002383 for (unsigned i=0; i<NumClasses; i++)
2384 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2385 ObjCTypes.Int8PtrTy);
2386 for (unsigned i=0; i<NumCategories; i++)
2387 Symbols[NumClasses + i] =
2388 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2389 ObjCTypes.Int8PtrTy);
2390
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002391 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002392 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002393 NumClasses + NumCategories),
2394 Symbols);
2395
2396 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2397
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002398 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002399 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2400 "__OBJC,__symbols,regular,no_dead_strip",
2401 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002402 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2403}
2404
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002405llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002406 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002407 LazySymbols.insert(ID->getIdentifier());
2408
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002409 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2410
2411 if (!Entry) {
2412 llvm::Constant *Casted =
2413 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2414 ObjCTypes.ClassPtrTy);
2415 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002416 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2417 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2418 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002419 }
2420
2421 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002422}
2423
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002424llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002425 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2426
2427 if (!Entry) {
2428 llvm::Constant *Casted =
2429 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2430 ObjCTypes.SelectorPtrTy);
2431 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002432 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2433 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2434 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002435 }
2436
2437 return Builder.CreateLoad(Entry, false, "tmp");
2438}
2439
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002440llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002441 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002442
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002443 if (!Entry)
2444 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2445 llvm::ConstantArray::get(Ident->getName()),
2446 "__TEXT,__cstring,cstring_literals",
2447 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002448
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002449 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002450}
2451
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002452/// GetIvarLayoutName - Returns a unique constant for the given
2453/// ivar layout bitmap.
2454llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2455 const ObjCCommonTypesHelper &ObjCTypes) {
2456 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2457}
2458
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002459void CGObjCCommonMac::BuildAggrIvarLayout(const llvm::StructLayout *Layout,
2460 const RecordDecl *RD,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002461 const std::vector<FieldDecl*>& RecFields,
2462 unsigned int BytePos, bool ForStrongLayout,
2463 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002464 bool is_union = (RD && RD->isUnion());
2465 unsigned int base = 0;
2466 if (RecFields.empty())
2467 return;
2468 if (is_union)
2469 base = BytePos + GetIvarBaseOffset(Layout, RecFields[0]);
2470
2471 for (unsigned i = 0; i < RecFields.size(); i++) {
2472 FieldDecl *Field = RecFields[i];
2473 // Skip over unnamed or bitfields
2474 if (!Field->getIdentifier() || Field->isBitField())
2475 continue;
2476 QualType FQT = Field->getType();
2477 if (FQT->isAggregateType()) {
2478 std::vector<FieldDecl*> NestedRecFields;
2479 if (FQT->isUnionType())
2480 HasUnion = true;
2481 const RecordType *RT = FQT->getAsRecordType();
2482 const RecordDecl *RD = RT->getDecl();
2483 // FIXME - Find a more efficiant way of passing records down.
2484 unsigned j = 0;
2485 for (RecordDecl::field_iterator i = RD->field_begin(),
2486 e = RD->field_end(); i != e; ++i)
2487 NestedRecFields[j++] = (*i);
2488 // FIXME - Is Layout correct?
2489 BuildAggrIvarLayout(Layout, RD, NestedRecFields,
2490 BytePos + GetIvarBaseOffset(Layout, Field),
2491 ForStrongLayout, Index, SkIndex,
2492 HasUnion);
2493 continue;
2494 }
2495 else if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2496 FQT = Array->getElementType();
2497 }
2498 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002499 return;
2500}
2501
2502/// BuildIvarLayout - Builds ivar layout bitmap for the class
2503/// implementation for the __strong or __weak case.
2504/// The layout map displays which words in ivar list must be skipped
2505/// and which must be scanned by GC (see below). String is built of bytes.
2506/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2507/// of words to skip and right nibble is count of words to scan. So, each
2508/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2509/// represented by a 0x00 byte which also ends the string.
2510/// 1. when ForStrongLayout is true, following ivars are scanned:
2511/// - id, Class
2512/// - object *
2513/// - __strong anything
2514///
2515/// 2. When ForStrongLayout is false, following ivars are scanned:
2516/// - __weak anything
2517///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002518llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
2519 const llvm::StructLayout *Layout,
2520 ObjCImplementationDecl *OMD,
2521 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002522 int iIndex = -1;
2523 int iSkIndex = -1;
2524 bool hasUnion = false;
2525
2526 std::vector<FieldDecl*> RecFields;
2527 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2528 CGM.getContext().CollectObjCIvars(OI, RecFields);
2529 if (RecFields.empty())
2530 return 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002531 BuildAggrIvarLayout (Layout, 0, RecFields, 0, ForStrongLayout,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002532 iIndex, iSkIndex, hasUnion);
2533 return 0;
2534}
2535
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002536llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002537 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2538
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002539 // FIXME: Avoid std::string copying.
2540 if (!Entry)
2541 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2542 llvm::ConstantArray::get(Sel.getAsString()),
2543 "__TEXT,__cstring,cstring_literals",
2544 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002545
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002546 return getConstantGEP(Entry, 0, 0);
2547}
2548
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002549// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002550llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002551 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2552}
2553
2554// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002555llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002556 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2557}
2558
Devang Patel7794bb82009-03-04 18:21:39 +00002559llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2560 std::string TypeStr;
2561 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2562
2563 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002564
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002565 if (!Entry)
2566 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2567 llvm::ConstantArray::get(TypeStr),
2568 "__TEXT,__cstring,cstring_literals",
2569 0, true);
2570
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002571 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002572}
2573
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002574llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002575 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002576 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2577 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002578
2579 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2580
2581 if (!Entry) {
2582 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2583 Entry =
2584 new llvm::GlobalVariable(C->getType(), false,
2585 llvm::GlobalValue::InternalLinkage,
2586 C, "\01L_OBJC_METH_VAR_TYPE_",
2587 &CGM.getModule());
2588 Entry->setSection("__TEXT,__cstring,cstring_literals");
2589 UsedGlobals.push_back(Entry);
2590 }
2591
2592 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002593}
2594
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002595// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002596llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002597 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2598
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002599 if (!Entry)
2600 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
2601 llvm::ConstantArray::get(Ident->getName()),
2602 "__TEXT,__cstring,cstring_literals",
2603 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002604
2605 return getConstantGEP(Entry, 0, 0);
2606}
2607
2608// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002609// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002610llvm::Constant *
2611 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2612 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002613 std::string TypeStr;
2614 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002615 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2616}
2617
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002618void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2619 const ObjCContainerDecl *CD,
2620 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002621 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002622 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002623 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002624 assert (CD && "Missing container decl in GetNameForMethod");
2625 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002626 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2627 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002628 NameOut += ' ';
2629 NameOut += D->getSelector().getAsString();
2630 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002631}
2632
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002633/// GetFirstIvarInRecord - This routine returns the record for the
2634/// implementation of the fiven class OID. It also returns field
2635/// corresponding to the first ivar in the class in FIV. It also
2636/// returns the one before the first ivar.
2637///
2638const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2639 const ObjCInterfaceDecl *OID,
2640 RecordDecl::field_iterator &FIV,
2641 RecordDecl::field_iterator &PIV) {
2642 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2643 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2644 RecordDecl::field_iterator ifield = RD->field_begin();
2645 RecordDecl::field_iterator pfield = RD->field_end();
2646 while (countSuperClassIvars-- > 0) {
2647 pfield = ifield;
2648 ++ifield;
2649 }
2650 FIV = ifield;
2651 PIV = pfield;
2652 return RD;
2653}
2654
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002655void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002656 EmitModuleInfo();
2657
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002658 // Emit the dummy bodies for any protocols which were referenced but
2659 // never defined.
2660 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2661 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2662 if (i->second->hasInitializer())
2663 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002664
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002665 std::vector<llvm::Constant*> Values(5);
2666 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2667 Values[1] = GetClassName(i->first);
2668 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2669 Values[3] = Values[4] =
2670 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2671 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2672 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2673 Values));
2674 }
2675
2676 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002677 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002678 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002679 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002680 }
2681
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002682 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002683 llvm::GlobalValue *GV =
2684 new llvm::GlobalVariable(AT, false,
2685 llvm::GlobalValue::AppendingLinkage,
2686 llvm::ConstantArray::get(AT, Used),
2687 "llvm.used",
2688 &CGM.getModule());
2689
2690 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002691
2692 // Add assembler directives to add lazy undefined symbol references
2693 // for classes which are referenced but not defined. This is
2694 // important for correct linker interaction.
2695
2696 // FIXME: Uh, this isn't particularly portable.
2697 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002698
2699 if (!CGM.getModule().getModuleInlineAsm().empty())
2700 s << "\n";
2701
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002702 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2703 e = LazySymbols.end(); i != e; ++i) {
2704 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2705 }
2706 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2707 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002708 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002709 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2710 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002711
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002712 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002713}
2714
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002715CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002716 : CGObjCCommonMac(cgm),
2717 ObjCTypes(cgm)
2718{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002719 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002720 ObjCABI = 2;
2721}
2722
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002723/* *** */
2724
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002725ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2726: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002727{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002728 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2729 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002730
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002731 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002732 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002733 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002734 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2735
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002736 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002737 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002738 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002739
2740 // FIXME: It would be nice to unify this with the opaque type, so
2741 // that the IR comes out a bit cleaner.
2742 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2743 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002744
2745 // I'm not sure I like this. The implicit coordination is a bit
2746 // gross. We should solve this in a reasonable fashion because this
2747 // is a pretty common task (match some runtime data structure with
2748 // an LLVM data structure).
2749
2750 // FIXME: This is leaked.
2751 // FIXME: Merge with rewriter code?
2752
2753 // struct _objc_super {
2754 // id self;
2755 // Class cls;
2756 // }
2757 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2758 SourceLocation(),
2759 &Ctx.Idents.get("_objc_super"));
2760 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2761 Ctx.getObjCIdType(), 0, false));
2762 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2763 Ctx.getObjCClassType(), 0, false));
2764 RD->completeDefinition(Ctx);
2765
2766 SuperCTy = Ctx.getTagDeclType(RD);
2767 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2768
2769 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002770 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2771
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002772 // struct _prop_t {
2773 // char *name;
2774 // char *attributes;
2775 // }
2776 PropertyTy = llvm::StructType::get(Int8PtrTy,
2777 Int8PtrTy,
2778 NULL);
2779 CGM.getModule().addTypeName("struct._prop_t",
2780 PropertyTy);
2781
2782 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002783 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002784 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002785 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002786 // }
2787 PropertyListTy = llvm::StructType::get(IntTy,
2788 IntTy,
2789 llvm::ArrayType::get(PropertyTy, 0),
2790 NULL);
2791 CGM.getModule().addTypeName("struct._prop_list_t",
2792 PropertyListTy);
2793 // struct _prop_list_t *
2794 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2795
2796 // struct _objc_method {
2797 // SEL _cmd;
2798 // char *method_type;
2799 // char *_imp;
2800 // }
2801 MethodTy = llvm::StructType::get(SelectorPtrTy,
2802 Int8PtrTy,
2803 Int8PtrTy,
2804 NULL);
2805 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002806
2807 // struct _objc_cache *
2808 CacheTy = llvm::OpaqueType::get();
2809 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2810 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002811
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002812 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002813
2814 QualType IdType = Ctx.getObjCIdType();
2815 QualType SelType = Ctx.getObjCSelType();
2816 llvm::SmallVector<QualType,16> Params;
2817 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002818
2819 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002820 Params.push_back(IdType);
2821 Params.push_back(SelType);
2822 Params.push_back(Ctx.LongTy);
2823 Params.push_back(Ctx.BoolTy);
2824 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2825 false);
2826 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002827
2828 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2829 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002830 Params.push_back(IdType);
2831 Params.push_back(SelType);
2832 Params.push_back(Ctx.LongTy);
2833 Params.push_back(IdType);
2834 Params.push_back(Ctx.BoolTy);
2835 Params.push_back(Ctx.BoolTy);
2836 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2837 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2838
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002839 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002840
2841 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002842 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002843 Params.push_back(IdType);
2844 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2845 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2846 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002847
2848 // gc's API
2849 // id objc_read_weak (id *)
2850 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002851 Params.push_back(Ctx.getPointerType(IdType));
2852 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2853 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2854
2855 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002856 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002857 Params.push_back(IdType);
2858 Params.push_back(Ctx.getPointerType(IdType));
2859
2860 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2861 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2862 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2863 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2864 GcAssignStrongCastFn =
2865 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002866
2867 // void objc_exception_throw(id)
2868 Params.clear();
2869 Params.push_back(IdType);
2870
2871 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002872 ExceptionThrowFn =
2873 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002874
2875 // synchronized APIs
2876 // void objc_sync_enter (id)
2877 // void objc_sync_exit (id)
2878 Params.clear();
2879 Params.push_back(IdType);
2880
2881 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2882 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2883 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002884}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002885
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002886ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2887 : ObjCCommonTypesHelper(cgm)
2888{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002889 // struct _objc_method_description {
2890 // SEL name;
2891 // char *types;
2892 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002893 MethodDescriptionTy =
2894 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002895 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002896 NULL);
2897 CGM.getModule().addTypeName("struct._objc_method_description",
2898 MethodDescriptionTy);
2899
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002900 // struct _objc_method_description_list {
2901 // int count;
2902 // struct _objc_method_description[1];
2903 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002904 MethodDescriptionListTy =
2905 llvm::StructType::get(IntTy,
2906 llvm::ArrayType::get(MethodDescriptionTy, 0),
2907 NULL);
2908 CGM.getModule().addTypeName("struct._objc_method_description_list",
2909 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002910
2911 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002912 MethodDescriptionListPtrTy =
2913 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2914
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002915 // Protocol description structures
2916
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002917 // struct _objc_protocol_extension {
2918 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2919 // struct _objc_method_description_list *optional_instance_methods;
2920 // struct _objc_method_description_list *optional_class_methods;
2921 // struct _objc_property_list *instance_properties;
2922 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002923 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002924 llvm::StructType::get(IntTy,
2925 MethodDescriptionListPtrTy,
2926 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002927 PropertyListPtrTy,
2928 NULL);
2929 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2930 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002931
2932 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002933 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2934
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002935 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002936
2937 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2938 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2939
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002940 const llvm::Type *T =
2941 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2942 LongTy,
2943 llvm::ArrayType::get(ProtocolTyHolder, 0),
2944 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002945 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2946
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002947 // struct _objc_protocol {
2948 // struct _objc_protocol_extension *isa;
2949 // char *protocol_name;
2950 // struct _objc_protocol **_objc_protocol_list;
2951 // struct _objc_method_description_list *instance_methods;
2952 // struct _objc_method_description_list *class_methods;
2953 // }
2954 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002955 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002956 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2957 MethodDescriptionListPtrTy,
2958 MethodDescriptionListPtrTy,
2959 NULL);
2960 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2961
2962 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2963 CGM.getModule().addTypeName("struct._objc_protocol_list",
2964 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002965 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002966 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2967
2968 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002969 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002970 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002971
2972 // Class description structures
2973
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002974 // struct _objc_ivar {
2975 // char *ivar_name;
2976 // char *ivar_type;
2977 // int ivar_offset;
2978 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002979 IvarTy = llvm::StructType::get(Int8PtrTy,
2980 Int8PtrTy,
2981 IntTy,
2982 NULL);
2983 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2984
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002985 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002986 IvarListTy = llvm::OpaqueType::get();
2987 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2988 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2989
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002990 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002991 MethodListTy = llvm::OpaqueType::get();
2992 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2993 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2994
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002995 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002996 ClassExtensionTy =
2997 llvm::StructType::get(IntTy,
2998 Int8PtrTy,
2999 PropertyListPtrTy,
3000 NULL);
3001 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3002 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3003
3004 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3005
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003006 // struct _objc_class {
3007 // Class isa;
3008 // Class super_class;
3009 // char *name;
3010 // long version;
3011 // long info;
3012 // long instance_size;
3013 // struct _objc_ivar_list *ivars;
3014 // struct _objc_method_list *methods;
3015 // struct _objc_cache *cache;
3016 // struct _objc_protocol_list *protocols;
3017 // char *ivar_layout;
3018 // struct _objc_class_ext *ext;
3019 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003020 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3021 llvm::PointerType::getUnqual(ClassTyHolder),
3022 Int8PtrTy,
3023 LongTy,
3024 LongTy,
3025 LongTy,
3026 IvarListPtrTy,
3027 MethodListPtrTy,
3028 CachePtrTy,
3029 ProtocolListPtrTy,
3030 Int8PtrTy,
3031 ClassExtensionPtrTy,
3032 NULL);
3033 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3034
3035 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3036 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3037 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3038
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003039 // struct _objc_category {
3040 // char *category_name;
3041 // char *class_name;
3042 // struct _objc_method_list *instance_method;
3043 // struct _objc_method_list *class_method;
3044 // uint32_t size; // sizeof(struct _objc_category)
3045 // struct _objc_property_list *instance_properties;// category's @property
3046 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003047 CategoryTy = llvm::StructType::get(Int8PtrTy,
3048 Int8PtrTy,
3049 MethodListPtrTy,
3050 MethodListPtrTy,
3051 ProtocolListPtrTy,
3052 IntTy,
3053 PropertyListPtrTy,
3054 NULL);
3055 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3056
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003057 // Global metadata structures
3058
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003059 // struct _objc_symtab {
3060 // long sel_ref_cnt;
3061 // SEL *refs;
3062 // short cls_def_cnt;
3063 // short cat_def_cnt;
3064 // char *defs[cls_def_cnt + cat_def_cnt];
3065 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003066 SymtabTy = llvm::StructType::get(LongTy,
3067 SelectorPtrTy,
3068 ShortTy,
3069 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003070 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003071 NULL);
3072 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3073 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3074
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003075 // struct _objc_module {
3076 // long version;
3077 // long size; // sizeof(struct _objc_module)
3078 // char *name;
3079 // struct _objc_symtab* symtab;
3080 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003081 ModuleTy =
3082 llvm::StructType::get(LongTy,
3083 LongTy,
3084 Int8PtrTy,
3085 SymtabPtrTy,
3086 NULL);
3087 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003088
Daniel Dunbar49f66022008-09-24 03:38:44 +00003089 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003090
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003091 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003092 std::vector<const llvm::Type*> Params;
3093 Params.push_back(ObjectPtrTy);
3094 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003095 MessageSendFn =
3096 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3097 Params,
3098 true),
3099 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003100
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003101 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003102 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003103 Params.push_back(ObjectPtrTy);
3104 Params.push_back(SelectorPtrTy);
3105 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003106 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3107 Params,
3108 true),
3109 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003110
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003111 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003112 Params.clear();
3113 Params.push_back(ObjectPtrTy);
3114 Params.push_back(SelectorPtrTy);
3115 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003116 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003117 MessageSendFpretFn =
3118 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3119 Params,
3120 true),
3121 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003122
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003123 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003124 Params.clear();
3125 Params.push_back(SuperPtrTy);
3126 Params.push_back(SelectorPtrTy);
3127 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003128 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3129 Params,
3130 true),
3131 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003132
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003133 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3134 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003135 Params.clear();
3136 Params.push_back(Int8PtrTy);
3137 Params.push_back(SuperPtrTy);
3138 Params.push_back(SelectorPtrTy);
3139 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003140 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3141 Params,
3142 true),
3143 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003144
3145 // There is no objc_msgSendSuper_fpret? How can that work?
3146 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003147
Anders Carlsson124526b2008-09-09 10:10:21 +00003148 // FIXME: This is the size of the setjmp buffer and should be
3149 // target specific. 18 is what's used on 32-bit X86.
3150 uint64_t SetJmpBufferSize = 18;
3151
3152 // Exceptions
3153 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003154 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003155
3156 ExceptionDataTy =
3157 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3158 SetJmpBufferSize),
3159 StackPtrTy, NULL);
3160 CGM.getModule().addTypeName("struct._objc_exception_data",
3161 ExceptionDataTy);
3162
3163 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003164 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3165 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003166 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3167 Params,
3168 false),
3169 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003170 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003171 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3172 Params,
3173 false),
3174 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003175 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003176 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3177 Params,
3178 false),
3179 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003180
3181 Params.clear();
3182 Params.push_back(ClassPtrTy);
3183 Params.push_back(ObjectPtrTy);
3184 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003185 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3186 Params,
3187 false),
3188 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003189
Anders Carlsson124526b2008-09-09 10:10:21 +00003190 Params.clear();
3191 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3192 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003193 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3194 Params,
3195 false),
3196 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003197
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003198}
3199
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003200ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003201: ObjCCommonTypesHelper(cgm)
3202{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003203 // struct _method_list_t {
3204 // uint32_t entsize; // sizeof(struct _objc_method)
3205 // uint32_t method_count;
3206 // struct _objc_method method_list[method_count];
3207 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003208 MethodListnfABITy = llvm::StructType::get(IntTy,
3209 IntTy,
3210 llvm::ArrayType::get(MethodTy, 0),
3211 NULL);
3212 CGM.getModule().addTypeName("struct.__method_list_t",
3213 MethodListnfABITy);
3214 // struct method_list_t *
3215 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003216
3217 // struct _protocol_t {
3218 // id isa; // NULL
3219 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003220 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003221 // const struct method_list_t * const instance_methods;
3222 // const struct method_list_t * const class_methods;
3223 // const struct method_list_t *optionalInstanceMethods;
3224 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003225 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003226 // const uint32_t size; // sizeof(struct _protocol_t)
3227 // const uint32_t flags; // = 0
3228 // }
3229
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003230 // Holder for struct _protocol_list_t *
3231 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3232
3233 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3234 Int8PtrTy,
3235 llvm::PointerType::getUnqual(
3236 ProtocolListTyHolder),
3237 MethodListnfABIPtrTy,
3238 MethodListnfABIPtrTy,
3239 MethodListnfABIPtrTy,
3240 MethodListnfABIPtrTy,
3241 PropertyListPtrTy,
3242 IntTy,
3243 IntTy,
3244 NULL);
3245 CGM.getModule().addTypeName("struct._protocol_t",
3246 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003247
3248 // struct _protocol_t*
3249 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003250
Fariborz Jahanianda320092009-01-29 19:24:30 +00003251 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003252 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003253 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003254 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003255 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3256 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003257 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003258 NULL);
3259 CGM.getModule().addTypeName("struct._objc_protocol_list",
3260 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003261 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3262 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003263
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003264 // struct _objc_protocol_list*
3265 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003266
3267 // struct _ivar_t {
3268 // unsigned long int *offset; // pointer to ivar offset location
3269 // char *name;
3270 // char *type;
3271 // uint32_t alignment;
3272 // uint32_t size;
3273 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003274 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3275 Int8PtrTy,
3276 Int8PtrTy,
3277 IntTy,
3278 IntTy,
3279 NULL);
3280 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3281
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003282 // struct _ivar_list_t {
3283 // uint32 entsize; // sizeof(struct _ivar_t)
3284 // uint32 count;
3285 // struct _iver_t list[count];
3286 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003287 IvarListnfABITy = llvm::StructType::get(IntTy,
3288 IntTy,
3289 llvm::ArrayType::get(
3290 IvarnfABITy, 0),
3291 NULL);
3292 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3293
3294 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003295
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003296 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003297 // uint32_t const flags;
3298 // uint32_t const instanceStart;
3299 // uint32_t const instanceSize;
3300 // uint32_t const reserved; // only when building for 64bit targets
3301 // const uint8_t * const ivarLayout;
3302 // const char *const name;
3303 // const struct _method_list_t * const baseMethods;
3304 // const struct _objc_protocol_list *const baseProtocols;
3305 // const struct _ivar_list_t *const ivars;
3306 // const uint8_t * const weakIvarLayout;
3307 // const struct _prop_list_t * const properties;
3308 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003309
3310 // FIXME. Add 'reserved' field in 64bit abi mode!
3311 ClassRonfABITy = llvm::StructType::get(IntTy,
3312 IntTy,
3313 IntTy,
3314 Int8PtrTy,
3315 Int8PtrTy,
3316 MethodListnfABIPtrTy,
3317 ProtocolListnfABIPtrTy,
3318 IvarListnfABIPtrTy,
3319 Int8PtrTy,
3320 PropertyListPtrTy,
3321 NULL);
3322 CGM.getModule().addTypeName("struct._class_ro_t",
3323 ClassRonfABITy);
3324
3325 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3326 std::vector<const llvm::Type*> Params;
3327 Params.push_back(ObjectPtrTy);
3328 Params.push_back(SelectorPtrTy);
3329 ImpnfABITy = llvm::PointerType::getUnqual(
3330 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3331
3332 // struct _class_t {
3333 // struct _class_t *isa;
3334 // struct _class_t * const superclass;
3335 // void *cache;
3336 // IMP *vtable;
3337 // struct class_ro_t *ro;
3338 // }
3339
3340 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3341 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3342 llvm::PointerType::getUnqual(ClassTyHolder),
3343 CachePtrTy,
3344 llvm::PointerType::getUnqual(ImpnfABITy),
3345 llvm::PointerType::getUnqual(
3346 ClassRonfABITy),
3347 NULL);
3348 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3349
3350 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3351 ClassnfABITy);
3352
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003353 // LLVM for struct _class_t *
3354 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3355
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003356 // struct _category_t {
3357 // const char * const name;
3358 // struct _class_t *const cls;
3359 // const struct _method_list_t * const instance_methods;
3360 // const struct _method_list_t * const class_methods;
3361 // const struct _protocol_list_t * const protocols;
3362 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003363 // }
3364 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003365 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003366 MethodListnfABIPtrTy,
3367 MethodListnfABIPtrTy,
3368 ProtocolListnfABIPtrTy,
3369 PropertyListPtrTy,
3370 NULL);
3371 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003372
3373 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003374 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3375 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003376
3377 // MessageRefTy - LLVM for:
3378 // struct _message_ref_t {
3379 // IMP messenger;
3380 // SEL name;
3381 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003382
3383 // First the clang type for struct _message_ref_t
3384 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3385 SourceLocation(),
3386 &Ctx.Idents.get("_message_ref_t"));
3387 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3388 Ctx.VoidPtrTy, 0, false));
3389 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3390 Ctx.getObjCSelType(), 0, false));
3391 RD->completeDefinition(Ctx);
3392
3393 MessageRefCTy = Ctx.getTagDeclType(RD);
3394 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3395 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003396
3397 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3398 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3399
3400 // SuperMessageRefTy - LLVM for:
3401 // struct _super_message_ref_t {
3402 // SUPER_IMP messenger;
3403 // SEL name;
3404 // };
3405 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3406 SelectorPtrTy,
3407 NULL);
3408 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3409
3410 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3411 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3412
3413 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3414 Params.clear();
3415 Params.push_back(ObjectPtrTy);
3416 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003417 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3418 Params,
3419 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003420 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003421 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003422 "objc_msgSend_fixup");
3423
3424 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3425 MessageSendFpretFixupFn =
3426 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3427 Params,
3428 true),
3429 "objc_msgSend_fpret_fixup");
3430
3431 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3432 MessageSendStretFixupFn =
3433 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3434 Params,
3435 true),
3436 "objc_msgSend_stret_fixup");
3437
3438 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3439 MessageSendIdFixupFn =
3440 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3441 Params,
3442 true),
3443 "objc_msgSendId_fixup");
3444
3445
3446 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3447 MessageSendIdStretFixupFn =
3448 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3449 Params,
3450 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003451 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003452
3453 // id objc_msgSendSuper2_fixup (struct objc_super *,
3454 // struct _super_message_ref_t*, ...)
3455 Params.clear();
3456 Params.push_back(SuperPtrTy);
3457 Params.push_back(SuperMessageRefPtrTy);
3458 MessageSendSuper2FixupFn =
3459 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3460 Params,
3461 true),
3462 "objc_msgSendSuper2_fixup");
3463
3464
3465 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3466 // struct _super_message_ref_t*, ...)
3467 MessageSendSuper2StretFixupFn =
3468 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3469 Params,
3470 true),
3471 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003472
3473 Params.clear();
3474 llvm::Constant *Personality =
3475 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3476 Params,
3477 true),
3478 "__objc_personality_v0");
3479 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3480
3481 Params.clear();
3482 Params.push_back(Int8PtrTy);
3483 UnwindResumeOrRethrowFn =
3484 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3485 Params,
3486 false),
3487 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003488 ObjCBeginCatchFn =
3489 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3490 Params,
3491 false),
3492 "objc_begin_catch");
3493
3494 Params.clear();
3495 ObjCEndCatchFn =
3496 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3497 Params,
3498 false),
3499 "objc_end_catch");
3500
3501 // struct objc_typeinfo {
3502 // const void** vtable; // objc_ehtype_vtable + 2
3503 // const char* name; // c++ typeinfo string
3504 // Class cls;
3505 // };
3506 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3507 Int8PtrTy,
3508 ClassnfABIPtrTy,
3509 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003510 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003511 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003512}
3513
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003514llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3515 FinishNonFragileABIModule();
3516
3517 return NULL;
3518}
3519
3520void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3521 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003522
3523 // Build list of all implemented classe addresses in array
3524 // L_OBJC_LABEL_CLASS_$.
3525 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3526 // list of 'nonlazy' implementations (defined as those with a +load{}
3527 // method!!).
3528 unsigned NumClasses = DefinedClasses.size();
3529 if (NumClasses) {
3530 std::vector<llvm::Constant*> Symbols(NumClasses);
3531 for (unsigned i=0; i<NumClasses; i++)
3532 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3533 ObjCTypes.Int8PtrTy);
3534 llvm::Constant* Init =
3535 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3536 NumClasses),
3537 Symbols);
3538
3539 llvm::GlobalVariable *GV =
3540 new llvm::GlobalVariable(Init->getType(), false,
3541 llvm::GlobalValue::InternalLinkage,
3542 Init,
3543 "\01L_OBJC_LABEL_CLASS_$",
3544 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003545 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003546 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3547 UsedGlobals.push_back(GV);
3548 }
3549
3550 // Build list of all implemented category addresses in array
3551 // L_OBJC_LABEL_CATEGORY_$.
3552 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3553 // list of 'nonlazy' category implementations (defined as those with a +load{}
3554 // method!!).
3555 unsigned NumCategory = DefinedCategories.size();
3556 if (NumCategory) {
3557 std::vector<llvm::Constant*> Symbols(NumCategory);
3558 for (unsigned i=0; i<NumCategory; i++)
3559 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3560 ObjCTypes.Int8PtrTy);
3561 llvm::Constant* Init =
3562 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3563 NumCategory),
3564 Symbols);
3565
3566 llvm::GlobalVariable *GV =
3567 new llvm::GlobalVariable(Init->getType(), false,
3568 llvm::GlobalValue::InternalLinkage,
3569 Init,
3570 "\01L_OBJC_LABEL_CATEGORY_$",
3571 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003572 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003573 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3574 UsedGlobals.push_back(GV);
3575 }
3576
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003577 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3578 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3579 std::vector<llvm::Constant*> Values(2);
3580 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003581 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003582 // FIXME: Fix and continue?
3583 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3584 flags |= eImageInfo_GarbageCollected;
3585 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3586 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003587 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003588 llvm::Constant* Init = llvm::ConstantArray::get(
3589 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3590 Values);
3591 llvm::GlobalVariable *IMGV =
3592 new llvm::GlobalVariable(Init->getType(), false,
3593 llvm::GlobalValue::InternalLinkage,
3594 Init,
3595 "\01L_OBJC_IMAGE_INFO",
3596 &CGM.getModule());
3597 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3598 UsedGlobals.push_back(IMGV);
3599
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003600 std::vector<llvm::Constant*> Used;
3601 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3602 e = UsedGlobals.end(); i != e; ++i) {
3603 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3604 }
3605
3606 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3607 llvm::GlobalValue *GV =
3608 new llvm::GlobalVariable(AT, false,
3609 llvm::GlobalValue::AppendingLinkage,
3610 llvm::ConstantArray::get(AT, Used),
3611 "llvm.used",
3612 &CGM.getModule());
3613
3614 GV->setSection("llvm.metadata");
3615
3616}
3617
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003618// Metadata flags
3619enum MetaDataDlags {
3620 CLS = 0x0,
3621 CLS_META = 0x1,
3622 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003623 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003624 CLS_EXCEPTION = 0x20
3625};
3626/// BuildClassRoTInitializer - generate meta-data for:
3627/// struct _class_ro_t {
3628/// uint32_t const flags;
3629/// uint32_t const instanceStart;
3630/// uint32_t const instanceSize;
3631/// uint32_t const reserved; // only when building for 64bit targets
3632/// const uint8_t * const ivarLayout;
3633/// const char *const name;
3634/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003635/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003636/// const struct _ivar_list_t *const ivars;
3637/// const uint8_t * const weakIvarLayout;
3638/// const struct _prop_list_t * const properties;
3639/// }
3640///
3641llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3642 unsigned flags,
3643 unsigned InstanceStart,
3644 unsigned InstanceSize,
3645 const ObjCImplementationDecl *ID) {
3646 std::string ClassName = ID->getNameAsString();
3647 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3648 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3649 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3650 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3651 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003652 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003653 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003654 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003655 // const struct _method_list_t * const baseMethods;
3656 std::vector<llvm::Constant*> Methods;
3657 std::string MethodListName("\01l_OBJC_$_");
3658 if (flags & CLS_META) {
3659 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3660 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3661 e = ID->classmeth_end(); i != e; ++i) {
3662 // Class methods should always be defined.
3663 Methods.push_back(GetMethodConstant(*i));
3664 }
3665 } else {
3666 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3667 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3668 e = ID->instmeth_end(); i != e; ++i) {
3669 // Instance methods should always be defined.
3670 Methods.push_back(GetMethodConstant(*i));
3671 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003672 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3673 e = ID->propimpl_end(); i != e; ++i) {
3674 ObjCPropertyImplDecl *PID = *i;
3675
3676 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3677 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3678
3679 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3680 if (llvm::Constant *C = GetMethodConstant(MD))
3681 Methods.push_back(C);
3682 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3683 if (llvm::Constant *C = GetMethodConstant(MD))
3684 Methods.push_back(C);
3685 }
3686 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003687 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003688 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003689 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003690
3691 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3692 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3693 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3694 + OID->getNameAsString(),
3695 OID->protocol_begin(),
3696 OID->protocol_end());
3697
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003698 if (flags & CLS_META)
3699 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3700 else
3701 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003702 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003703 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003704 if (flags & CLS_META)
3705 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3706 else
3707 Values[ 9] =
3708 EmitPropertyList(
3709 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3710 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003711 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3712 Values);
3713 llvm::GlobalVariable *CLASS_RO_GV =
3714 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3715 llvm::GlobalValue::InternalLinkage,
3716 Init,
3717 (flags & CLS_META) ?
3718 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3719 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3720 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003721 CLASS_RO_GV->setAlignment(
3722 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003723 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003724 UsedGlobals.push_back(CLASS_RO_GV);
3725 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003726
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003727}
3728
3729/// BuildClassMetaData - This routine defines that to-level meta-data
3730/// for the given ClassName for:
3731/// struct _class_t {
3732/// struct _class_t *isa;
3733/// struct _class_t * const superclass;
3734/// void *cache;
3735/// IMP *vtable;
3736/// struct class_ro_t *ro;
3737/// }
3738///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003739llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3740 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003741 llvm::Constant *IsAGV,
3742 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003743 llvm::Constant *ClassRoGV,
3744 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003745 std::vector<llvm::Constant*> Values(5);
3746 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003747 Values[1] = SuperClassGV
3748 ? SuperClassGV
3749 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003750 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3751 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3752 Values[4] = ClassRoGV; // &CLASS_RO_GV
3753 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3754 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003755 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3756 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003757 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003758 GV->setAlignment(
3759 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003760 if (HiddenVisibility)
3761 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003762 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003763 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003764}
3765
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003766void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3767 std::string ClassName = ID->getNameAsString();
3768 if (!ObjCEmptyCacheVar) {
3769 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003770 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003771 false,
3772 llvm::GlobalValue::ExternalLinkage,
3773 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003774 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003775 &CGM.getModule());
3776 UsedGlobals.push_back(ObjCEmptyCacheVar);
3777
3778 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003779 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003780 false,
3781 llvm::GlobalValue::ExternalLinkage,
3782 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003783 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003784 &CGM.getModule());
3785 UsedGlobals.push_back(ObjCEmptyVtableVar);
3786 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003787 assert(ID->getClassInterface() &&
3788 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003789 uint32_t InstanceStart =
3790 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3791 uint32_t InstanceSize = InstanceStart;
3792 uint32_t flags = CLS_META;
3793 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3794 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003795
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003796 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003797
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003798 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3799 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003800 flags |= OBJC2_CLS_HIDDEN;
3801 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003802 // class is root
3803 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003804 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3805 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003806 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003807 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003808 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3809 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3810 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003811 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003812 // work on super class metadata symbol.
3813 std::string SuperClassName =
3814 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003815 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003816 }
3817 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3818 InstanceStart,
3819 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003820 std::string TClassName = ObjCMetaClassName + ClassName;
3821 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003822 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3823 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003824
3825 // Metadata for the class
3826 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003827 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003828 flags |= OBJC2_CLS_HIDDEN;
3829 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003830 flags |= CLS_ROOT;
3831 SuperClassGV = 0;
3832 }
3833 else {
3834 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003835 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003836 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003837 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003838 }
3839
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003840 InstanceStart = InstanceSize = 0;
3841 if (ObjCInterfaceDecl *OID =
3842 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3843 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003844 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003845 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003846 const llvm::StructLayout *Layout =
3847 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003848
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003849 RecordDecl::field_iterator firstField, lastField;
3850 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003851
3852 for (RecordDecl::field_iterator e = RD->field_end(),
3853 ifield = firstField; ifield != e; ++ifield)
3854 lastField = ifield;
3855
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003856 if (lastField != RD->field_end()) {
3857 FieldDecl *Field = *lastField;
3858 const llvm::Type *FieldTy =
3859 CGM.getTypes().ConvertTypeForMem(Field->getType());
3860 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003861 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003862 if (firstField == RD->field_end())
3863 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003864 else {
3865 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003866 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003867 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003868 }
3869 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003870 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003871 InstanceStart,
3872 InstanceSize,
3873 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003874
3875 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003876 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003877 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3878 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003879 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003880}
3881
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003882/// GenerateProtocolRef - This routine is called to generate code for
3883/// a protocol reference expression; as in:
3884/// @code
3885/// @protocol(Proto1);
3886/// @endcode
3887/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3888/// which will hold address of the protocol meta-data.
3889///
3890llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3891 const ObjCProtocolDecl *PD) {
3892
3893 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3894 ObjCTypes.ExternalProtocolPtrTy);
3895
3896 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3897 ProtocolName += PD->getNameAsCString();
3898
3899 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3900 if (PTGV)
3901 return Builder.CreateLoad(PTGV, false, "tmp");
3902 PTGV = new llvm::GlobalVariable(
3903 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00003904 // FIXME: review, was WeakLinkage,
3905 // also review all other WeakLinkage changes
3906 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003907 Init,
3908 ProtocolName,
3909 &CGM.getModule());
3910 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3911 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3912 UsedGlobals.push_back(PTGV);
3913 return Builder.CreateLoad(PTGV, false, "tmp");
3914}
3915
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003916/// GenerateCategory - Build metadata for a category implementation.
3917/// struct _category_t {
3918/// const char * const name;
3919/// struct _class_t *const cls;
3920/// const struct _method_list_t * const instance_methods;
3921/// const struct _method_list_t * const class_methods;
3922/// const struct _protocol_list_t * const protocols;
3923/// const struct _prop_list_t * const properties;
3924/// }
3925///
3926void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3927{
3928 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003929 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3930 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003931 "_$_" + OCD->getNameAsString());
3932 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3933
3934 std::vector<llvm::Constant*> Values(6);
3935 Values[0] = GetClassName(OCD->getIdentifier());
3936 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003937 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003938 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003939 std::vector<llvm::Constant*> Methods;
3940 std::string MethodListName(Prefix);
3941 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3942 "_$_" + OCD->getNameAsString();
3943
3944 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3945 e = OCD->instmeth_end(); i != e; ++i) {
3946 // Instance methods should always be defined.
3947 Methods.push_back(GetMethodConstant(*i));
3948 }
3949
3950 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003951 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003952 Methods);
3953
3954 MethodListName = Prefix;
3955 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3956 OCD->getNameAsString();
3957 Methods.clear();
3958 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3959 e = OCD->classmeth_end(); i != e; ++i) {
3960 // Class methods should always be defined.
3961 Methods.push_back(GetMethodConstant(*i));
3962 }
3963
3964 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003965 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003966 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003967 const ObjCCategoryDecl *Category =
3968 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003969 if (Category) {
3970 std::string ExtName(Interface->getNameAsString() + "_$_" +
3971 OCD->getNameAsString());
3972 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3973 + Interface->getNameAsString() + "_$_"
3974 + Category->getNameAsString(),
3975 Category->protocol_begin(),
3976 Category->protocol_end());
3977 Values[5] =
3978 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3979 OCD, Category, ObjCTypes);
3980 }
3981 else {
3982 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3983 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3984 }
3985
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003986 llvm::Constant *Init =
3987 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3988 Values);
3989 llvm::GlobalVariable *GCATV
3990 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3991 false,
3992 llvm::GlobalValue::InternalLinkage,
3993 Init,
3994 ExtCatName,
3995 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003996 GCATV->setAlignment(
3997 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003998 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003999 UsedGlobals.push_back(GCATV);
4000 DefinedCategories.push_back(GCATV);
4001}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004002
4003/// GetMethodConstant - Return a struct objc_method constant for the
4004/// given method if it has been defined. The result is null if the
4005/// method has not been defined. The return value has type MethodPtrTy.
4006llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4007 const ObjCMethodDecl *MD) {
4008 // FIXME: Use DenseMap::lookup
4009 llvm::Function *Fn = MethodDefinitions[MD];
4010 if (!Fn)
4011 return 0;
4012
4013 std::vector<llvm::Constant*> Method(3);
4014 Method[0] =
4015 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4016 ObjCTypes.SelectorPtrTy);
4017 Method[1] = GetMethodVarType(MD);
4018 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4019 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4020}
4021
4022/// EmitMethodList - Build meta-data for method declarations
4023/// struct _method_list_t {
4024/// uint32_t entsize; // sizeof(struct _objc_method)
4025/// uint32_t method_count;
4026/// struct _objc_method method_list[method_count];
4027/// }
4028///
4029llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4030 const std::string &Name,
4031 const char *Section,
4032 const ConstantVector &Methods) {
4033 // Return null for empty list.
4034 if (Methods.empty())
4035 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4036
4037 std::vector<llvm::Constant*> Values(3);
4038 // sizeof(struct _objc_method)
4039 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4040 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4041 // method_count
4042 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4043 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4044 Methods.size());
4045 Values[2] = llvm::ConstantArray::get(AT, Methods);
4046 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4047
4048 llvm::GlobalVariable *GV =
4049 new llvm::GlobalVariable(Init->getType(), false,
4050 llvm::GlobalValue::InternalLinkage,
4051 Init,
4052 Name,
4053 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004054 GV->setAlignment(
4055 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004056 GV->setSection(Section);
4057 UsedGlobals.push_back(GV);
4058 return llvm::ConstantExpr::getBitCast(GV,
4059 ObjCTypes.MethodListnfABIPtrTy);
4060}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004061
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004062/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4063/// the given ivar.
4064///
4065llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4066 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004067 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004068 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004069 Name += "\01_OBJC_IVAR_$_" +
4070 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004071 + Ivar->getNameAsString();
4072 llvm::GlobalVariable *IvarOffsetGV =
4073 CGM.getModule().getGlobalVariable(Name);
4074 if (!IvarOffsetGV)
4075 IvarOffsetGV =
4076 new llvm::GlobalVariable(ObjCTypes.LongTy,
4077 false,
4078 llvm::GlobalValue::ExternalLinkage,
4079 0,
4080 Name,
4081 &CGM.getModule());
4082 return IvarOffsetGV;
4083}
4084
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004085llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004086 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004087 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004088 unsigned long int Offset) {
4089
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004090 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004091 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004092 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004093 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004094
4095 llvm::GlobalVariable *IvarOffsetGV =
4096 CGM.getModule().getGlobalVariable(ExternalName);
4097 if (IvarOffsetGV) {
4098 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004099 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004100 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004101 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004102 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004103 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004104 return IvarOffsetGV;
4105 }
4106
4107 IvarOffsetGV =
4108 new llvm::GlobalVariable(Init->getType(),
4109 false,
4110 llvm::GlobalValue::ExternalLinkage,
4111 Init,
4112 ExternalName,
4113 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004114 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004115 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004116 // @private and @package have hidden visibility.
4117 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4118 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4119 if (!globalVisibility)
4120 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004121 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004122 if (IsClassHidden(ID))
4123 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004124
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004125 IvarOffsetGV->setSection("__DATA, __objc_const");
4126 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004127 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004128}
4129
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004130/// EmitIvarList - Emit the ivar list for the given
4131/// implementation. If ForClass is true the list of class ivars
4132/// (i.e. metaclass ivars) is emitted, otherwise the list of
4133/// interface ivars will be emitted. The return value has type
4134/// IvarListnfABIPtrTy.
4135/// struct _ivar_t {
4136/// unsigned long int *offset; // pointer to ivar offset location
4137/// char *name;
4138/// char *type;
4139/// uint32_t alignment;
4140/// uint32_t size;
4141/// }
4142/// struct _ivar_list_t {
4143/// uint32 entsize; // sizeof(struct _ivar_t)
4144/// uint32 count;
4145/// struct _iver_t list[count];
4146/// }
4147///
4148llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4149 const ObjCImplementationDecl *ID) {
4150
4151 std::vector<llvm::Constant*> Ivars, Ivar(5);
4152
4153 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4154 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4155
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004156 // FIXME. Consolidate this with similar code in GenerateClass.
4157 const llvm::Type *InterfaceTy =
4158 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4159 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004160 const llvm::StructLayout *Layout =
4161 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004162
4163 RecordDecl::field_iterator i,p;
4164 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004165 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4166
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004167 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004168 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004169 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004170 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004171 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004172 if (Field->getIdentifier())
4173 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4174 else
4175 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004176 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004177 const llvm::Type *FieldTy =
4178 CGM.getTypes().ConvertTypeForMem(Field->getType());
4179 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4180 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4181 Field->getType().getTypePtr()) >> 3;
4182 Align = llvm::Log2_32(Align);
4183 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004184 // NOTE. Size of a bitfield does not match gcc's, because of the way
4185 // bitfields are treated special in each. But I am told that 'size'
4186 // for bitfield ivars is ignored by the runtime so it does not matter.
4187 // (even if it matters, some day, there is enough info. to get the bitfield
4188 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004189 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4190 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4191 }
4192 // Return null for empty list.
4193 if (Ivars.empty())
4194 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4195 std::vector<llvm::Constant*> Values(3);
4196 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4197 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4198 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4199 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4200 Ivars.size());
4201 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4202 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4203 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4204 llvm::GlobalVariable *GV =
4205 new llvm::GlobalVariable(Init->getType(), false,
4206 llvm::GlobalValue::InternalLinkage,
4207 Init,
4208 Prefix + OID->getNameAsString(),
4209 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004210 GV->setAlignment(
4211 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004212 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004213
4214 UsedGlobals.push_back(GV);
4215 return llvm::ConstantExpr::getBitCast(GV,
4216 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004217}
4218
4219llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4220 const ObjCProtocolDecl *PD) {
4221 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4222
4223 if (!Entry) {
4224 // We use the initializer as a marker of whether this is a forward
4225 // reference or not. At module finalization we add the empty
4226 // contents for protocols which were referenced but never defined.
4227 Entry =
4228 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4229 llvm::GlobalValue::ExternalLinkage,
4230 0,
4231 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4232 &CGM.getModule());
4233 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4234 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004235 }
4236
4237 return Entry;
4238}
4239
4240/// GetOrEmitProtocol - Generate the protocol meta-data:
4241/// @code
4242/// struct _protocol_t {
4243/// id isa; // NULL
4244/// const char * const protocol_name;
4245/// const struct _protocol_list_t * protocol_list; // super protocols
4246/// const struct method_list_t * const instance_methods;
4247/// const struct method_list_t * const class_methods;
4248/// const struct method_list_t *optionalInstanceMethods;
4249/// const struct method_list_t *optionalClassMethods;
4250/// const struct _prop_list_t * properties;
4251/// const uint32_t size; // sizeof(struct _protocol_t)
4252/// const uint32_t flags; // = 0
4253/// }
4254/// @endcode
4255///
4256
4257llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4258 const ObjCProtocolDecl *PD) {
4259 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4260
4261 // Early exit if a defining object has already been generated.
4262 if (Entry && Entry->hasInitializer())
4263 return Entry;
4264
4265 const char *ProtocolName = PD->getNameAsCString();
4266
4267 // Construct method lists.
4268 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4269 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4270 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4271 e = PD->instmeth_end(); i != e; ++i) {
4272 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004273 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004274 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4275 OptInstanceMethods.push_back(C);
4276 } else {
4277 InstanceMethods.push_back(C);
4278 }
4279 }
4280
4281 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4282 e = PD->classmeth_end(); i != e; ++i) {
4283 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004284 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004285 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4286 OptClassMethods.push_back(C);
4287 } else {
4288 ClassMethods.push_back(C);
4289 }
4290 }
4291
4292 std::vector<llvm::Constant*> Values(10);
4293 // isa is NULL
4294 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4295 Values[1] = GetClassName(PD->getIdentifier());
4296 Values[2] = EmitProtocolList(
4297 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4298 PD->protocol_begin(),
4299 PD->protocol_end());
4300
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004301 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004302 + PD->getNameAsString(),
4303 "__DATA, __objc_const",
4304 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004305 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004306 + PD->getNameAsString(),
4307 "__DATA, __objc_const",
4308 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004309 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004310 + PD->getNameAsString(),
4311 "__DATA, __objc_const",
4312 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004313 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004314 + PD->getNameAsString(),
4315 "__DATA, __objc_const",
4316 OptClassMethods);
4317 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4318 0, PD, ObjCTypes);
4319 uint32_t Size =
4320 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4321 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4322 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4323 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4324 Values);
4325
4326 if (Entry) {
4327 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004328 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004329 Entry->setInitializer(Init);
4330 } else {
4331 Entry =
4332 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004333 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004334 Init,
4335 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4336 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004337 Entry->setAlignment(
4338 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004339 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004340 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004341 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4342
4343 // Use this protocol meta-data to build protocol list table in section
4344 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004345 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004346 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004347 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004348 Entry,
4349 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4350 +ProtocolName,
4351 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004352 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004353 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004354 PTGV->setSection("__DATA, __objc_protolist");
4355 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4356 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004357 return Entry;
4358}
4359
4360/// EmitProtocolList - Generate protocol list meta-data:
4361/// @code
4362/// struct _protocol_list_t {
4363/// long protocol_count; // Note, this is 32/64 bit
4364/// struct _protocol_t[protocol_count];
4365/// }
4366/// @endcode
4367///
4368llvm::Constant *
4369CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4370 ObjCProtocolDecl::protocol_iterator begin,
4371 ObjCProtocolDecl::protocol_iterator end) {
4372 std::vector<llvm::Constant*> ProtocolRefs;
4373
Fariborz Jahanianda320092009-01-29 19:24:30 +00004374 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004375 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004376 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4377
Daniel Dunbar948e2582009-02-15 07:36:20 +00004378 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004379 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4380 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004381 return llvm::ConstantExpr::getBitCast(GV,
4382 ObjCTypes.ProtocolListnfABIPtrTy);
4383
4384 for (; begin != end; ++begin)
4385 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4386
Fariborz Jahanianda320092009-01-29 19:24:30 +00004387 // This list is null terminated.
4388 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004389 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004390
4391 std::vector<llvm::Constant*> Values(2);
4392 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4393 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004394 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004395 ProtocolRefs.size()),
4396 ProtocolRefs);
4397
4398 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4399 GV = new llvm::GlobalVariable(Init->getType(), false,
4400 llvm::GlobalValue::InternalLinkage,
4401 Init,
4402 Name,
4403 &CGM.getModule());
4404 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004405 GV->setAlignment(
4406 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004407 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004408 return llvm::ConstantExpr::getBitCast(GV,
4409 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004410}
4411
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004412/// GetMethodDescriptionConstant - This routine build following meta-data:
4413/// struct _objc_method {
4414/// SEL _cmd;
4415/// char *method_type;
4416/// char *_imp;
4417/// }
4418
4419llvm::Constant *
4420CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4421 std::vector<llvm::Constant*> Desc(3);
4422 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4423 ObjCTypes.SelectorPtrTy);
4424 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004425 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004426 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4427 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4428}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004429
4430/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4431/// This code gen. amounts to generating code for:
4432/// @code
4433/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4434/// @encode
4435///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004436LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004437 CodeGen::CodeGenFunction &CGF,
4438 QualType ObjectTy,
4439 llvm::Value *BaseValue,
4440 const ObjCIvarDecl *Ivar,
4441 const FieldDecl *Field,
4442 unsigned CVRQualifiers) {
4443 assert(ObjectTy->isObjCInterfaceType() &&
4444 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004445 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004446 std::string ExternalName;
4447 llvm::GlobalVariable *IvarOffsetGV =
4448 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004449
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004450 // (char *) BaseValue
4451 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4452 ObjCTypes.Int8PtrTy);
4453 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4454 // (char*)BaseValue + Offset_symbol
4455 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4456 // (type *)((char*)BaseValue + Offset_symbol)
4457 const llvm::Type *IvarTy =
4458 CGM.getTypes().ConvertType(Ivar->getType());
4459 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4460 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004461
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004462 if (Ivar->isBitField()) {
4463 CodeGenTypes::BitFieldInfo bitFieldInfo =
4464 CGM.getTypes().getBitFieldInfo(Field);
4465 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4466 Field->getType()->isSignedIntegerType(),
4467 Field->getType().getCVRQualifiers()|CVRQualifiers);
4468 }
4469
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004470 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004471 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4472 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004473 LValue::SetObjCIvar(LV, true);
4474 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004475}
4476
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004477llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4478 CodeGen::CodeGenFunction &CGF,
4479 ObjCInterfaceDecl *Interface,
4480 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004481 std::string ExternalName;
4482 llvm::GlobalVariable *IvarOffsetGV =
4483 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4484
4485 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004486}
4487
Fariborz Jahanian46551122009-02-04 00:22:57 +00004488CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4489 CodeGen::CodeGenFunction &CGF,
4490 QualType ResultType,
4491 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004492 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004493 QualType Arg0Ty,
4494 bool IsSuper,
4495 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004496 // FIXME. Even though IsSuper is passes. This function doese not
4497 // handle calls to 'super' receivers.
4498 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004499 llvm::Value *Arg0 = Receiver;
4500 if (!IsSuper)
4501 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004502
4503 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004504 // FIXME. This is too much work to get the ABI-specific result type
4505 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004506 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4507 llvm::SmallVector<QualType, 16>());
4508 llvm::Constant *Fn;
4509 std::string Name("\01l_");
4510 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004511#if 0
4512 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004513 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4514 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4515 // FIXME. Is there a better way of getting these names.
4516 // They are available in RuntimeFunctions vector pair.
4517 Name += "objc_msgSendId_stret_fixup";
4518 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004519 else
4520#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004521 if (IsSuper) {
4522 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4523 Name += "objc_msgSendSuper2_stret_fixup";
4524 }
4525 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004526 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004527 Fn = ObjCTypes.MessageSendStretFixupFn;
4528 Name += "objc_msgSend_stret_fixup";
4529 }
4530 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004531 else if (ResultType->isFloatingType() &&
4532 // Selection of frret API only happens in 32bit nonfragile ABI.
4533 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004534 Fn = ObjCTypes.MessageSendFpretFixupFn;
4535 Name += "objc_msgSend_fpret_fixup";
4536 }
4537 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004538#if 0
4539// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004540 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4541 Fn = ObjCTypes.MessageSendIdFixupFn;
4542 Name += "objc_msgSendId_fixup";
4543 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004544 else
4545#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004546 if (IsSuper) {
4547 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4548 Name += "objc_msgSendSuper2_fixup";
4549 }
4550 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004551 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004552 Fn = ObjCTypes.MessageSendFixupFn;
4553 Name += "objc_msgSend_fixup";
4554 }
4555 }
4556 Name += '_';
4557 std::string SelName(Sel.getAsString());
4558 // Replace all ':' in selector name with '_' ouch!
4559 for(unsigned i = 0; i < SelName.size(); i++)
4560 if (SelName[i] == ':')
4561 SelName[i] = '_';
4562 Name += SelName;
4563 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4564 if (!GV) {
4565 // Build messafe ref table entry.
4566 std::vector<llvm::Constant*> Values(2);
4567 Values[0] = Fn;
4568 Values[1] = GetMethodVarName(Sel);
4569 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4570 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004571 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004572 Init,
4573 Name,
4574 &CGM.getModule());
4575 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4576 GV->setAlignment(
4577 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4578 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4579 UsedGlobals.push_back(GV);
4580 }
4581 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004582
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004583 CallArgList ActualArgs;
4584 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4585 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4586 ObjCTypes.MessageRefCPtrTy));
4587 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004588 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4589 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4590 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004591 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004592 Callee = CGF.Builder.CreateBitCast(Callee,
4593 llvm::PointerType::getUnqual(FTy));
4594 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004595}
4596
4597/// Generate code for a message send expression in the nonfragile abi.
4598CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4599 CodeGen::CodeGenFunction &CGF,
4600 QualType ResultType,
4601 Selector Sel,
4602 llvm::Value *Receiver,
4603 bool IsClassMessage,
4604 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004605 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004606 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004607 false, CallArgs);
4608}
4609
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004610llvm::GlobalVariable *
4611CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4612 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4613
Daniel Dunbardfff2302009-03-02 05:18:14 +00004614 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004615 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4616 llvm::GlobalValue::ExternalLinkage,
4617 0, Name, &CGM.getModule());
4618 UsedGlobals.push_back(GV);
4619 }
4620
4621 return GV;
4622}
4623
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004624llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004625 const ObjCInterfaceDecl *ID,
4626 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004627
4628 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4629
4630 if (!Entry) {
4631 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004632 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004633 Entry =
4634 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4635 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004636 ClassGV,
4637 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4638 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004639 &CGM.getModule());
4640 Entry->setAlignment(
4641 CGM.getTargetData().getPrefTypeAlignment(
4642 ObjCTypes.ClassnfABIPtrTy));
4643
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004644 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004645 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004646 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004647 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004648 UsedGlobals.push_back(Entry);
4649 }
4650
4651 return Builder.CreateLoad(Entry, false, "tmp");
4652}
4653
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004654/// EmitMetaClassRef - Return a Value * of the address of _class_t
4655/// meta-data
4656///
4657llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4658 const ObjCInterfaceDecl *ID) {
4659 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4660 if (Entry)
4661 return Builder.CreateLoad(Entry, false, "tmp");
4662
4663 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004664 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004665 Entry =
4666 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4667 llvm::GlobalValue::InternalLinkage,
4668 MetaClassGV,
4669 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4670 &CGM.getModule());
4671 Entry->setAlignment(
4672 CGM.getTargetData().getPrefTypeAlignment(
4673 ObjCTypes.ClassnfABIPtrTy));
4674
4675 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4676 UsedGlobals.push_back(Entry);
4677
4678 return Builder.CreateLoad(Entry, false, "tmp");
4679}
4680
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004681/// GetClass - Return a reference to the class for the given interface
4682/// decl.
4683llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4684 const ObjCInterfaceDecl *ID) {
4685 return EmitClassRef(Builder, ID);
4686}
4687
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004688/// Generates a message send where the super is the receiver. This is
4689/// a message send to self with special delivery semantics indicating
4690/// which class's method should be called.
4691CodeGen::RValue
4692CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4693 QualType ResultType,
4694 Selector Sel,
4695 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004696 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004697 llvm::Value *Receiver,
4698 bool IsClassMessage,
4699 const CodeGen::CallArgList &CallArgs) {
4700 // ...
4701 // Create and init a super structure; this is a (receiver, class)
4702 // pair we will pass to objc_msgSendSuper.
4703 llvm::Value *ObjCSuper =
4704 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4705
4706 llvm::Value *ReceiverAsObject =
4707 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4708 CGF.Builder.CreateStore(ReceiverAsObject,
4709 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4710
4711 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004712 llvm::Value *Target;
4713 if (IsClassMessage) {
4714 if (isCategoryImpl) {
4715 // Message sent to "super' in a class method defined in
4716 // a category implementation.
4717 Target = EmitClassRef(CGF.Builder, Class, false);
4718 Target = CGF.Builder.CreateStructGEP(Target, 0);
4719 Target = CGF.Builder.CreateLoad(Target);
4720 }
4721 else
4722 Target = EmitMetaClassRef(CGF.Builder, Class);
4723 }
4724 else
4725 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004726
4727 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4728 // and ObjCTypes types.
4729 const llvm::Type *ClassTy =
4730 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4731 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4732 CGF.Builder.CreateStore(Target,
4733 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4734
4735 return EmitMessageSend(CGF, ResultType, Sel,
4736 ObjCSuper, ObjCTypes.SuperPtrCTy,
4737 true, CallArgs);
4738}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004739
4740llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4741 Selector Sel) {
4742 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4743
4744 if (!Entry) {
4745 llvm::Constant *Casted =
4746 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4747 ObjCTypes.SelectorPtrTy);
4748 Entry =
4749 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4750 llvm::GlobalValue::InternalLinkage,
4751 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4752 &CGM.getModule());
4753 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4754 UsedGlobals.push_back(Entry);
4755 }
4756
4757 return Builder.CreateLoad(Entry, false, "tmp");
4758}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004759/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4760/// objc_assign_ivar (id src, id *dst)
4761///
4762void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4763 llvm::Value *src, llvm::Value *dst)
4764{
4765 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4766 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4767 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4768 src, dst, "assignivar");
4769 return;
4770}
4771
4772/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4773/// objc_assign_strongCast (id src, id *dst)
4774///
4775void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4776 CodeGen::CodeGenFunction &CGF,
4777 llvm::Value *src, llvm::Value *dst)
4778{
4779 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4780 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4781 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4782 src, dst, "weakassign");
4783 return;
4784}
4785
4786/// EmitObjCWeakRead - Code gen for loading value of a __weak
4787/// object: objc_read_weak (id *src)
4788///
4789llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4790 CodeGen::CodeGenFunction &CGF,
4791 llvm::Value *AddrWeakObj)
4792{
Eli Friedman8339b352009-03-07 03:57:15 +00004793 const llvm::Type* DestTy =
4794 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004795 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4796 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4797 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00004798 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004799 return read_weak;
4800}
4801
4802/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4803/// objc_assign_weak (id src, id *dst)
4804///
4805void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4806 llvm::Value *src, llvm::Value *dst)
4807{
4808 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4809 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4810 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4811 src, dst, "weakassign");
4812 return;
4813}
4814
4815/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4816/// objc_assign_global (id src, id *dst)
4817///
4818void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4819 llvm::Value *src, llvm::Value *dst)
4820{
4821 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4822 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4823 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4824 src, dst, "globalassign");
4825 return;
4826}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004827
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004828void
4829CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4830 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004831 bool isTry = isa<ObjCAtTryStmt>(S);
4832 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4833 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004834 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004835 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004836 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004837 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4838
4839 // For @synchronized, call objc_sync_enter(sync.expr). The
4840 // evaluation of the expression must occur before we enter the
4841 // @synchronized. We can safely avoid a temp here because jumps into
4842 // @synchronized are illegal & this will dominate uses.
4843 llvm::Value *SyncArg = 0;
4844 if (!isTry) {
4845 SyncArg =
4846 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4847 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4848 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4849 }
4850
4851 // Push an EH context entry, used for handling rethrows and jumps
4852 // through finally.
4853 CGF.PushCleanupBlock(FinallyBlock);
4854
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004855 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004856
4857 CGF.EmitBlock(TryBlock);
4858 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4859 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4860 CGF.EmitBranchThroughCleanup(FinallyEnd);
4861
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004862 // Emit the exception handler.
4863
4864 CGF.EmitBlock(TryHandler);
4865
4866 llvm::Value *llvm_eh_exception =
4867 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4868 llvm::Value *llvm_eh_selector_i64 =
4869 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4870 llvm::Value *llvm_eh_typeid_for_i64 =
4871 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4872 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4873 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4874
4875 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4876 SelectorArgs.push_back(Exc);
4877 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4878
4879 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004880 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004881 bool HasCatchAll = false;
4882 if (isTry) {
4883 if (const ObjCAtCatchStmt* CatchStmt =
4884 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4885 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004886 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00004887 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004888
4889 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004890 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004891 // Use i8* null here to signal this is a catch all, not a cleanup.
4892 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4893 SelectorArgs.push_back(Null);
4894 HasCatchAll = true;
4895 break;
4896 }
4897
Daniel Dunbarede8de92009-03-06 00:01:21 +00004898 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
4899 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004900 llvm::Value *IDEHType =
4901 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4902 if (!IDEHType)
4903 IDEHType =
4904 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4905 llvm::GlobalValue::ExternalLinkage,
4906 0, "OBJC_EHTYPE_id", &CGM.getModule());
4907 SelectorArgs.push_back(IDEHType);
4908 HasCatchAll = true;
4909 break;
4910 }
4911
4912 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004913 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004914 assert(PT && "Invalid @catch type.");
4915 const ObjCInterfaceType *IT =
4916 PT->getPointeeType()->getAsObjCInterfaceType();
4917 assert(IT && "Invalid @catch type.");
4918 llvm::Value *EHType = GetInterfaceEHType(IT);
4919 SelectorArgs.push_back(EHType);
4920 }
4921 }
4922 }
4923
4924 // We use a cleanup unless there was already a catch all.
4925 if (!HasCatchAll) {
4926 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00004927 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004928 }
4929
4930 llvm::Value *Selector =
4931 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4932 SelectorArgs.begin(), SelectorArgs.end(),
4933 "selector");
4934 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004935 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004936 const Stmt *CatchBody = Handlers[i].second;
4937
4938 llvm::BasicBlock *Next = 0;
4939
4940 // The last handler always matches.
4941 if (i + 1 != e) {
4942 assert(CatchParam && "Only last handler can be a catch all.");
4943
4944 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4945 Next = CGF.createBasicBlock("catch.next");
4946 llvm::Value *Id =
4947 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4948 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4949 ObjCTypes.Int8PtrTy));
4950 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4951 Match, Next);
4952
4953 CGF.EmitBlock(Match);
4954 }
4955
4956 if (CatchBody) {
4957 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4958 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4959
4960 // Cleanups must call objc_end_catch.
4961 //
4962 // FIXME: It seems incorrect for objc_begin_catch to be inside
4963 // this context, but this matches gcc.
4964 CGF.PushCleanupBlock(MatchEnd);
4965 CGF.setInvokeDest(MatchHandler);
4966
4967 llvm::Value *ExcObject =
4968 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4969
4970 // Bind the catch parameter if it exists.
4971 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004972 ExcObject =
4973 CGF.Builder.CreateBitCast(ExcObject,
4974 CGF.ConvertType(CatchParam->getType()));
4975 // CatchParam is a ParmVarDecl because of the grammar
4976 // construction used to handle this, but for codegen purposes
4977 // we treat this as a local decl.
4978 CGF.EmitLocalBlockVarDecl(*CatchParam);
4979 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004980 }
4981
4982 CGF.ObjCEHValueStack.push_back(ExcObject);
4983 CGF.EmitStmt(CatchBody);
4984 CGF.ObjCEHValueStack.pop_back();
4985
4986 CGF.EmitBranchThroughCleanup(FinallyEnd);
4987
4988 CGF.EmitBlock(MatchHandler);
4989
4990 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4991 // We are required to emit this call to satisfy LLVM, even
4992 // though we don't use the result.
4993 llvm::SmallVector<llvm::Value*, 8> Args;
4994 Args.push_back(Exc);
4995 Args.push_back(ObjCTypes.EHPersonalityPtr);
4996 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4997 0));
4998 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4999 CGF.Builder.CreateStore(Exc, RethrowPtr);
5000 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5001
5002 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5003
5004 CGF.EmitBlock(MatchEnd);
5005
5006 // Unfortunately, we also have to generate another EH frame here
5007 // in case this throws.
5008 llvm::BasicBlock *MatchEndHandler =
5009 CGF.createBasicBlock("match.end.handler");
5010 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5011 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5012 Cont, MatchEndHandler,
5013 Args.begin(), Args.begin());
5014
5015 CGF.EmitBlock(Cont);
5016 if (Info.SwitchBlock)
5017 CGF.EmitBlock(Info.SwitchBlock);
5018 if (Info.EndBlock)
5019 CGF.EmitBlock(Info.EndBlock);
5020
5021 CGF.EmitBlock(MatchEndHandler);
5022 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5023 // We are required to emit this call to satisfy LLVM, even
5024 // though we don't use the result.
5025 Args.clear();
5026 Args.push_back(Exc);
5027 Args.push_back(ObjCTypes.EHPersonalityPtr);
5028 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5029 0));
5030 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5031 CGF.Builder.CreateStore(Exc, RethrowPtr);
5032 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5033
5034 if (Next)
5035 CGF.EmitBlock(Next);
5036 } else {
5037 assert(!Next && "catchup should be last handler.");
5038
5039 CGF.Builder.CreateStore(Exc, RethrowPtr);
5040 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5041 }
5042 }
5043
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005044 // Pop the cleanup entry, the @finally is outside this cleanup
5045 // scope.
5046 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5047 CGF.setInvokeDest(PrevLandingPad);
5048
5049 CGF.EmitBlock(FinallyBlock);
5050
5051 if (isTry) {
5052 if (const ObjCAtFinallyStmt* FinallyStmt =
5053 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5054 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5055 } else {
5056 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5057 // @synchronized.
5058 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005059 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005060
5061 if (Info.SwitchBlock)
5062 CGF.EmitBlock(Info.SwitchBlock);
5063 if (Info.EndBlock)
5064 CGF.EmitBlock(Info.EndBlock);
5065
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005066 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005067 CGF.EmitBranch(FinallyEnd);
5068
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005069 CGF.EmitBlock(FinallyRethrow);
5070 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5071 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005072 CGF.Builder.CreateUnreachable();
5073
5074 CGF.EmitBlock(FinallyEnd);
5075}
5076
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005077/// EmitThrowStmt - Generate code for a throw statement.
5078void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5079 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005080 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005081 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005082 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005083 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005084 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5085 "Unexpected rethrow outside @catch block.");
5086 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005087 }
5088
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005089 llvm::Value *ExceptionAsObject =
5090 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5091 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5092 if (InvokeDest) {
5093 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5094 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5095 Cont, InvokeDest,
5096 &ExceptionAsObject, &ExceptionAsObject + 1);
5097 CGF.EmitBlock(Cont);
5098 } else
5099 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5100 CGF.Builder.CreateUnreachable();
5101
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005102 // Clear the insertion point to indicate we are in unreachable code.
5103 CGF.Builder.ClearInsertionPoint();
5104}
Daniel Dunbare588b992009-03-01 04:46:24 +00005105
5106llvm::Value *
5107CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5108 const ObjCInterfaceDecl *ID = IT->getDecl();
5109 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5110 if (Entry)
5111 return Entry;
5112
5113 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5114 std::string VTableName = "objc_ehtype_vtable";
5115 llvm::GlobalVariable *VTableGV =
5116 CGM.getModule().getGlobalVariable(VTableName);
5117 if (!VTableGV)
5118 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5119 llvm::GlobalValue::ExternalLinkage,
5120 0, VTableName, &CGM.getModule());
5121
5122 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5123
5124 std::vector<llvm::Constant*> Values(3);
5125 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5126 Values[1] = GetClassName(ID->getIdentifier());
5127 Values[2] = GetClassGlobal(ClassName);
5128 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5129
5130 Entry =
5131 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005132 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005133 Init,
5134 (std::string("OBJC_EHTYPE_$_") +
5135 ID->getIdentifier()->getName()),
5136 &CGM.getModule());
5137
5138 return Entry;
5139}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005140
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005141/* *** */
5142
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005143CodeGen::CGObjCRuntime *
5144CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005145 return new CGObjCMac(CGM);
5146}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005147
5148CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005149CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005150 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005151}