blob: 48ea99ef7d89c657fb96de1c1833a325de4d8e69 [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 Jahanian9397e1d2009-03-11 20:59:05 +0000310public:
311 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000312 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000313 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000314 unsigned int ivar_bytepos;
315 unsigned int ivar_size;
316 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
317 };
318
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000319 class SKIP_SCAN {
320 public:
321 unsigned int skip;
322 unsigned int scan;
323 SKIP_SCAN() : skip(0), scan(0) {}
324 };
325
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000326protected:
327 CodeGen::CodeGenModule &CGM;
328 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000329 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000330
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000331 // gc ivar layout bitmap calculation helper caches.
332 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
333 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
334 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000335
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000336 /// LazySymbols - Symbols to generate a lazy reference for. See
337 /// DefinedSymbols and FinishModule().
338 std::set<IdentifierInfo*> LazySymbols;
339
340 /// DefinedSymbols - External symbols which are defined by this
341 /// module. The symbols in this list and LazySymbols are used to add
342 /// special linker symbols which ensure that Objective-C modules are
343 /// linked properly.
344 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000345
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000346 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000347 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000348
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000349 /// MethodVarNames - uniqued method variable names.
350 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000351
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000352 /// MethodVarTypes - uniqued method type signatures. We have to use
353 /// a StringMap here because have no other unique reference.
354 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000355
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000356 /// MethodDefinitions - map of methods which have been defined in
357 /// this translation unit.
358 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000360 /// PropertyNames - uniqued method variable names.
361 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000362
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000363 /// ClassReferences - uniqued class references.
364 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000366 /// SelectorReferences - uniqued selector references.
367 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000369 /// Protocols - Protocols for which an objc_protocol structure has
370 /// been emitted. Forward declarations are handled by creating an
371 /// empty structure whose initializer is filled in when/if defined.
372 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000373
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000374 /// DefinedProtocols - Protocols which have actually been
375 /// defined. We should not need this, see FIXME in GenerateProtocol.
376 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000377
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000378 /// DefinedClasses - List of defined classes.
379 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000380
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000381 /// DefinedCategories - List of defined categories.
382 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000383
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000384 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000385 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000386 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000387
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000388 /// GetNameForMethod - Return a name for the given method.
389 /// \param[out] NameOut - The return value.
390 void GetNameForMethod(const ObjCMethodDecl *OMD,
391 const ObjCContainerDecl *CD,
392 std::string &NameOut);
393
394 /// GetMethodVarName - Return a unique constant for the given
395 /// selector's name. The return value has type char *.
396 llvm::Constant *GetMethodVarName(Selector Sel);
397 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
398 llvm::Constant *GetMethodVarName(const std::string &Name);
399
400 /// GetMethodVarType - Return a unique constant for the given
401 /// selector's name. The return value has type char *.
402
403 // FIXME: This is a horrible name.
404 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000405 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000406
407 /// GetPropertyName - Return a unique constant for the given
408 /// name. The return value has type char *.
409 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
410
411 // FIXME: This can be dropped once string functions are unified.
412 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
413 const Decl *Container);
414
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000415 /// GetClassName - Return a unique constant for the given selector's
416 /// name. The return value has type char *.
417 llvm::Constant *GetClassName(IdentifierInfo *Ident);
418
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000419 /// BuildIvarLayout - Builds ivar layout bitmap for the class
420 /// implementation for the __strong or __weak case.
421 ///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000422 llvm::Constant *BuildIvarLayout(const llvm::StructLayout *Layout,
423 ObjCImplementationDecl *OI,
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000424 bool ForStrongLayout,
425 const ObjCCommonTypesHelper &ObjCTypes);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000426
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000427 void BuildAggrIvarLayout(const llvm::StructLayout *Layout,
428 const RecordDecl *RD,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000429 const std::vector<FieldDecl*>& RecFields,
430 unsigned int BytePos, bool ForStrongLayout,
431 int &Index, int &SkIndex, bool &HasUnion);
432
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000433 /// GetIvarLayoutName - Returns a unique constant for the given
434 /// ivar layout bitmap.
435 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
436 const ObjCCommonTypesHelper &ObjCTypes);
437
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000438 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
439 RecordDecl::field_iterator &FIV,
440 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000441 /// EmitPropertyList - Emit the given property list. The return
442 /// value has type PropertyListPtrTy.
443 llvm::Constant *EmitPropertyList(const std::string &Name,
444 const Decl *Container,
445 const ObjCContainerDecl *OCD,
446 const ObjCCommonTypesHelper &ObjCTypes);
447
Fariborz Jahanianda320092009-01-29 19:24:30 +0000448 /// GetProtocolRef - Return a reference to the internal protocol
449 /// description, creating an empty one if it has not been
450 /// defined. The return value has type ProtocolPtrTy.
451 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000452
453 /// GetIvarBaseOffset - returns ivars byte offset.
454 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
455 FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000456
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000457 /// CreateMetadataVar - Create a global variable with internal
458 /// linkage for use by the Objective-C runtime.
459 ///
460 /// This is a convenience wrapper which not only creates the
461 /// variable, but also sets the section and alignment and adds the
462 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000463 ///
464 /// \param Name - The variable name.
465 /// \param Init - The variable initializer; this is also used to
466 /// define the type of the variable.
467 /// \param Section - The section the variable should go into, or 0.
468 /// \param Align - The alignment for the variable, or 0.
469 /// \param AddToUsed - Whether the variable should be added to
470 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000471 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
472 llvm::Constant *Init,
473 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000474 unsigned Align,
475 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000476
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000477public:
478 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
479 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000480
481 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000482
483 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
484 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000485
486 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
487
488 /// GetOrEmitProtocol - Get the protocol object for the given
489 /// declaration, emitting it if necessary. The return value has type
490 /// ProtocolPtrTy.
491 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
492
493 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
494 /// object for the given declaration, emitting it if needed. These
495 /// forward references will be filled in with empty bodies if no
496 /// definition is seen. The return value has type ProtocolPtrTy.
497 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000498};
499
500class CGObjCMac : public CGObjCCommonMac {
501private:
502 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000503 /// EmitImageInfo - Emit the image info marker used to encode some module
504 /// level information.
505 void EmitImageInfo();
506
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000507 /// EmitModuleInfo - Another marker encoding module level
508 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000509 void EmitModuleInfo();
510
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000511 /// EmitModuleSymols - Emit module symbols, the list of defined
512 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000513 llvm::Constant *EmitModuleSymbols();
514
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000515 /// FinishModule - Write out global data structures at the end of
516 /// processing a translation unit.
517 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000518
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000519 /// EmitClassExtension - Generate the class extension structure used
520 /// to store the weak ivar layout and properties. The return value
521 /// has type ClassExtensionPtrTy.
522 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
523
524 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
525 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000526 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000527 const ObjCInterfaceDecl *ID);
528
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000529 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000530 QualType ResultType,
531 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000532 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000533 QualType Arg0Ty,
534 bool IsSuper,
535 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000536
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000537 /// EmitIvarList - Emit the ivar list for the given
538 /// implementation. If ForClass is true the list of class ivars
539 /// (i.e. metaclass ivars) is emitted, otherwise the list of
540 /// interface ivars will be emitted. The return value has type
541 /// IvarListPtrTy.
542 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000543 bool ForClass);
544
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000545 /// EmitMetaClass - Emit a forward reference to the class structure
546 /// for the metaclass of the given interface. The return value has
547 /// type ClassPtrTy.
548 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
549
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000550 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000551 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000552 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
553 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000554 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000555 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000556
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000557 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000558
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000559 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000560
561 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000562 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000563 llvm::Constant *EmitMethodList(const std::string &Name,
564 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000565 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000566
567 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000568 /// method declarations.
569 /// - TypeName: The name for the type containing the methods.
570 /// - IsProtocol: True iff these methods are for a protocol.
571 /// - ClassMethds: True iff these are class methods.
572 /// - Required: When true, only "required" methods are
573 /// listed. Similarly, when false only "optional" methods are
574 /// listed. For classes this should always be true.
575 /// - begin, end: The method list to output.
576 ///
577 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000578 llvm::Constant *EmitMethodDescList(const std::string &Name,
579 const char *Section,
580 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000581
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000582 /// GetOrEmitProtocol - Get the protocol object for the given
583 /// declaration, emitting it if necessary. The return value has type
584 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000585 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000586
587 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
588 /// object for the given declaration, emitting it if needed. These
589 /// forward references will be filled in with empty bodies if no
590 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000591 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000592
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000593 /// EmitProtocolExtension - Generate the protocol extension
594 /// structure used to store optional instance and class methods, and
595 /// protocol properties. The return value has type
596 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000597 llvm::Constant *
598 EmitProtocolExtension(const ObjCProtocolDecl *PD,
599 const ConstantVector &OptInstanceMethods,
600 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000601
602 /// EmitProtocolList - Generate the list of referenced
603 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000604 llvm::Constant *EmitProtocolList(const std::string &Name,
605 ObjCProtocolDecl::protocol_iterator begin,
606 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000607
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000608 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
609 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000610 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000611
Fariborz Jahanianda320092009-01-29 19:24:30 +0000612 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000613 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000614
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000615 virtual llvm::Function *ModuleInitFunction();
616
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000617 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000618 QualType ResultType,
619 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000620 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000621 bool IsClassMessage,
622 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000623
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000624 virtual CodeGen::RValue
625 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000626 QualType ResultType,
627 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000628 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000629 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000630 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000631 bool IsClassMessage,
632 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000633
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000634 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000635 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000636
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000637 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000638
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000639 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000640
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000641 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000642
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000643 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000644 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000645
Daniel Dunbar49f66022008-09-24 03:38:44 +0000646 virtual llvm::Function *GetPropertyGetFunction();
647 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000648 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000649
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000650 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
651 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000652 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
653 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000654 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000655 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000656 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
657 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000658 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
659 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000660 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
661 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000662 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
663 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000664
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000665 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
666 QualType ObjectTy,
667 llvm::Value *BaseValue,
668 const ObjCIvarDecl *Ivar,
669 const FieldDecl *Field,
670 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000671 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
672 ObjCInterfaceDecl *Interface,
673 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000674};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000675
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000676class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000677private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000678 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000679 llvm::GlobalVariable* ObjCEmptyCacheVar;
680 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000681
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000682 /// MetaClassReferences - uniqued meta class references.
683 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000684
685 /// EHTypeReferences - uniqued class ehtype references.
686 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000687
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000688 /// FinishNonFragileABIModule - Write out global data structures at the end of
689 /// processing a translation unit.
690 void FinishNonFragileABIModule();
691
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000692 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
693 unsigned InstanceStart,
694 unsigned InstanceSize,
695 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000696 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
697 llvm::Constant *IsAGV,
698 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000699 llvm::Constant *ClassRoGV,
700 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000701
702 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
703
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000704 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
705
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000706 /// EmitMethodList - Emit the method list for the given
707 /// implementation. The return value has type MethodListnfABITy.
708 llvm::Constant *EmitMethodList(const std::string &Name,
709 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000710 const ConstantVector &Methods);
711 /// EmitIvarList - Emit the ivar list for the given
712 /// implementation. If ForClass is true the list of class ivars
713 /// (i.e. metaclass ivars) is emitted, otherwise the list of
714 /// interface ivars will be emitted. The return value has type
715 /// IvarListnfABIPtrTy.
716 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000717
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000718 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000719 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000720 unsigned long int offset);
721
Fariborz Jahanianda320092009-01-29 19:24:30 +0000722 /// GetOrEmitProtocol - Get the protocol object for the given
723 /// declaration, emitting it if necessary. The return value has type
724 /// ProtocolPtrTy.
725 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
726
727 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
728 /// object for the given declaration, emitting it if needed. These
729 /// forward references will be filled in with empty bodies if no
730 /// definition is seen. The return value has type ProtocolPtrTy.
731 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
732
733 /// EmitProtocolList - Generate the list of referenced
734 /// protocols. The return value has type ProtocolListPtrTy.
735 llvm::Constant *EmitProtocolList(const std::string &Name,
736 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000737 ObjCProtocolDecl::protocol_iterator end);
738
739 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
740 QualType ResultType,
741 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000742 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000743 QualType Arg0Ty,
744 bool IsSuper,
745 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000746
747 /// GetClassGlobal - Return the global variable for the Objective-C
748 /// class of the given name.
749 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000750
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000751 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
752 /// for the given class.
753 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000754 const ObjCInterfaceDecl *ID,
755 bool IsSuper = false);
756
757 /// EmitMetaClassRef - Return a Value * of the address of _class_t
758 /// meta-data
759 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
760 const ObjCInterfaceDecl *ID);
761
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000762 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
763 /// the given ivar.
764 ///
765 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000766 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000767 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000768
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000769 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
770 /// for the given selector.
771 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000772
773 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
774 /// interface. The return value has type EHTypePtrTy.
775 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000776
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000777public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000778 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000779 // FIXME. All stubs for now!
780 virtual llvm::Function *ModuleInitFunction();
781
782 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
783 QualType ResultType,
784 Selector Sel,
785 llvm::Value *Receiver,
786 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000787 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000788
789 virtual CodeGen::RValue
790 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
791 QualType ResultType,
792 Selector Sel,
793 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000794 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000795 llvm::Value *Receiver,
796 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000797 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000798
799 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000800 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000801
802 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000803 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000804
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000805 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000806
807 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000808 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000809 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000811 virtual llvm::Function *GetPropertyGetFunction(){
812 return ObjCTypes.GetPropertyFn;
813 }
814 virtual llvm::Function *GetPropertySetFunction(){
815 return ObjCTypes.SetPropertyFn;
816 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000817 virtual llvm::Function *EnumerationMutationFunction() {
818 return ObjCTypes.EnumerationMutationFn;
819 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000820
821 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000822 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000823 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000824 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000825 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000826 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000827 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000828 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000830 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000831 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000832 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000833 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000834 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000835 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
836 QualType ObjectTy,
837 llvm::Value *BaseValue,
838 const ObjCIvarDecl *Ivar,
839 const FieldDecl *Field,
840 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000841 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
842 ObjCInterfaceDecl *Interface,
843 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000844};
845
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000846} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000847
848/* *** Helper Functions *** */
849
850/// getConstantGEP() - Help routine to construct simple GEPs.
851static llvm::Constant *getConstantGEP(llvm::Constant *C,
852 unsigned idx0,
853 unsigned idx1) {
854 llvm::Value *Idxs[] = {
855 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
856 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
857 };
858 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
859}
860
861/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000862
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000863CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
864 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000865{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000866 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000867 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000868}
869
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000870/// GetClass - Return a reference to the class for the given interface
871/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000872llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000873 const ObjCInterfaceDecl *ID) {
874 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000875}
876
877/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000878llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000879 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000880}
881
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000882/// Generate a constant CFString object.
883/*
884 struct __builtin_CFString {
885 const int *isa; // point to __CFConstantStringClassReference
886 int flags;
887 const char *str;
888 long length;
889 };
890*/
891
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000892llvm::Constant *CGObjCCommonMac::GenerateConstantString(
893 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000894 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000895}
896
897/// Generates a message send where the super is the receiver. This is
898/// a message send to self with special delivery semantics indicating
899/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000900CodeGen::RValue
901CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000902 QualType ResultType,
903 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000904 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000905 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000906 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000907 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000908 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000909 // Create and init a super structure; this is a (receiver, class)
910 // pair we will pass to objc_msgSendSuper.
911 llvm::Value *ObjCSuper =
912 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
913 llvm::Value *ReceiverAsObject =
914 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
915 CGF.Builder.CreateStore(ReceiverAsObject,
916 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000917
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000918 // If this is a class message the metaclass is passed as the target.
919 llvm::Value *Target;
920 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000921 if (isCategoryImpl) {
922 // Message sent to 'super' in a class method defined in a category
923 // implementation requires an odd treatment.
924 // If we are in a class method, we must retrieve the
925 // _metaclass_ for the current class, pointed at by
926 // the class's "isa" pointer. The following assumes that
927 // isa" is the first ivar in a class (which it must be).
928 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
929 Target = CGF.Builder.CreateStructGEP(Target, 0);
930 Target = CGF.Builder.CreateLoad(Target);
931 }
932 else {
933 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
934 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
935 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
936 Target = Super;
937 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000938 } else {
939 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
940 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000941 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
942 // and ObjCTypes types.
943 const llvm::Type *ClassTy =
944 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000945 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000946 CGF.Builder.CreateStore(Target,
947 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
948
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000949 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000950 ObjCSuper, ObjCTypes.SuperPtrCTy,
951 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000952}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000953
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000954/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000955CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000956 QualType ResultType,
957 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000958 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000959 bool IsClassMessage,
960 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000961 llvm::Value *Arg0 =
962 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000963 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000964 Arg0, CGF.getContext().getObjCIdType(),
965 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000966}
967
968CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000969 QualType ResultType,
970 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000971 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000972 QualType Arg0Ty,
973 bool IsSuper,
974 const CallArgList &CallArgs) {
975 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000976 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
977 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
978 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000979 CGF.getContext().getObjCSelType()));
980 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000981
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000982 CodeGenTypes &Types = CGM.getTypes();
983 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
984 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000985
986 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000987 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000988 Fn = ObjCTypes.getSendStretFn(IsSuper);
989 } else if (ResultType->isFloatingType()) {
990 // FIXME: Sadly, this is wrong. This actually depends on the
991 // architecture. This happens to be right for x86-32 though.
992 Fn = ObjCTypes.getSendFpretFn(IsSuper);
993 } else {
994 Fn = ObjCTypes.getSendFn(IsSuper);
995 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000996 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000997 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000998}
999
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001000llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001001 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001002 // FIXME: I don't understand why gcc generates this, or where it is
1003 // resolved. Investigate. Its also wasteful to look this up over and
1004 // over.
1005 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1006
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001007 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1008 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001009}
1010
Fariborz Jahanianda320092009-01-29 19:24:30 +00001011void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001012 // FIXME: We shouldn't need this, the protocol decl should contain
1013 // enough information to tell us whether this was a declaration or a
1014 // definition.
1015 DefinedProtocols.insert(PD->getIdentifier());
1016
1017 // If we have generated a forward reference to this protocol, emit
1018 // it now. Otherwise do nothing, the protocol objects are lazily
1019 // emitted.
1020 if (Protocols.count(PD->getIdentifier()))
1021 GetOrEmitProtocol(PD);
1022}
1023
Fariborz Jahanianda320092009-01-29 19:24:30 +00001024llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001025 if (DefinedProtocols.count(PD->getIdentifier()))
1026 return GetOrEmitProtocol(PD);
1027 return GetOrEmitProtocolRef(PD);
1028}
1029
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001030/*
1031 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1032 struct _objc_protocol {
1033 struct _objc_protocol_extension *isa;
1034 char *protocol_name;
1035 struct _objc_protocol_list *protocol_list;
1036 struct _objc__method_prototype_list *instance_methods;
1037 struct _objc__method_prototype_list *class_methods
1038 };
1039
1040 See EmitProtocolExtension().
1041*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001042llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1043 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1044
1045 // Early exit if a defining object has already been generated.
1046 if (Entry && Entry->hasInitializer())
1047 return Entry;
1048
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001049 // FIXME: I don't understand why gcc generates this, or where it is
1050 // resolved. Investigate. Its also wasteful to look this up over and
1051 // over.
1052 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1053
Chris Lattner8ec03f52008-11-24 03:54:41 +00001054 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001055
1056 // Construct method lists.
1057 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1058 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1059 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1060 e = PD->instmeth_end(); i != e; ++i) {
1061 ObjCMethodDecl *MD = *i;
1062 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1063 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1064 OptInstanceMethods.push_back(C);
1065 } else {
1066 InstanceMethods.push_back(C);
1067 }
1068 }
1069
1070 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1071 e = PD->classmeth_end(); i != e; ++i) {
1072 ObjCMethodDecl *MD = *i;
1073 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1074 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1075 OptClassMethods.push_back(C);
1076 } else {
1077 ClassMethods.push_back(C);
1078 }
1079 }
1080
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001081 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001082 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001083 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001084 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001085 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001086 PD->protocol_begin(),
1087 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001088 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001089 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1090 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001091 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1092 InstanceMethods);
1093 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001094 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1095 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001096 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1097 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001098 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1099 Values);
1100
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001101 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001102 // Already created, fix the linkage and update the initializer.
1103 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001104 Entry->setInitializer(Init);
1105 } else {
1106 Entry =
1107 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1108 llvm::GlobalValue::InternalLinkage,
1109 Init,
1110 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1111 &CGM.getModule());
1112 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001113 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001114 UsedGlobals.push_back(Entry);
1115 // FIXME: Is this necessary? Why only for protocol?
1116 Entry->setAlignment(4);
1117 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001118
1119 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001120}
1121
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001122llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001123 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1124
1125 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001126 // We use the initializer as a marker of whether this is a forward
1127 // reference or not. At module finalization we add the empty
1128 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001129 Entry =
1130 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001131 llvm::GlobalValue::ExternalLinkage,
1132 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001133 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001134 &CGM.getModule());
1135 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001136 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001137 UsedGlobals.push_back(Entry);
1138 // FIXME: Is this necessary? Why only for protocol?
1139 Entry->setAlignment(4);
1140 }
1141
1142 return Entry;
1143}
1144
1145/*
1146 struct _objc_protocol_extension {
1147 uint32_t size;
1148 struct objc_method_description_list *optional_instance_methods;
1149 struct objc_method_description_list *optional_class_methods;
1150 struct objc_property_list *instance_properties;
1151 };
1152*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001153llvm::Constant *
1154CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1155 const ConstantVector &OptInstanceMethods,
1156 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001157 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001158 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001159 std::vector<llvm::Constant*> Values(4);
1160 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001161 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001162 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1163 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001164 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1165 OptInstanceMethods);
1166 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001167 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1168 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001169 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1170 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001171 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1172 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001173 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001174
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001175 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001176 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1177 Values[3]->isNullValue())
1178 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1179
1180 llvm::Constant *Init =
1181 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001182
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001183 // No special section, but goes in llvm.used
1184 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1185 Init,
1186 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001187}
1188
1189/*
1190 struct objc_protocol_list {
1191 struct objc_protocol_list *next;
1192 long count;
1193 Protocol *list[];
1194 };
1195*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001196llvm::Constant *
1197CGObjCMac::EmitProtocolList(const std::string &Name,
1198 ObjCProtocolDecl::protocol_iterator begin,
1199 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001200 std::vector<llvm::Constant*> ProtocolRefs;
1201
Daniel Dunbardbc933702008-08-21 21:57:41 +00001202 for (; begin != end; ++begin)
1203 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001204
1205 // Just return null for empty protocol lists
1206 if (ProtocolRefs.empty())
1207 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1208
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001209 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001210 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1211
1212 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001213 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001214 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1215 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1216 Values[2] =
1217 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1218 ProtocolRefs.size()),
1219 ProtocolRefs);
1220
1221 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1222 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001223 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001224 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001225 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1226}
1227
1228/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001229 struct _objc_property {
1230 const char * const name;
1231 const char * const attributes;
1232 };
1233
1234 struct _objc_property_list {
1235 uint32_t entsize; // sizeof (struct _objc_property)
1236 uint32_t prop_count;
1237 struct _objc_property[prop_count];
1238 };
1239*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001240llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1241 const Decl *Container,
1242 const ObjCContainerDecl *OCD,
1243 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001244 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001245 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1246 E = OCD->prop_end(); I != E; ++I) {
1247 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001248 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001249 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001250 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1251 Prop));
1252 }
1253
1254 // Return null for empty list.
1255 if (Properties.empty())
1256 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1257
1258 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001259 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001260 std::vector<llvm::Constant*> Values(3);
1261 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1262 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1263 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1264 Properties.size());
1265 Values[2] = llvm::ConstantArray::get(AT, Properties);
1266 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1267
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001268 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001269 llvm::GlobalVariable *GV =
1270 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1271 0, true);
1272 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001273}
1274
1275/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001276 struct objc_method_description_list {
1277 int count;
1278 struct objc_method_description list[];
1279 };
1280*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001281llvm::Constant *
1282CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1283 std::vector<llvm::Constant*> Desc(2);
1284 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1285 ObjCTypes.SelectorPtrTy);
1286 Desc[1] = GetMethodVarType(MD);
1287 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1288 Desc);
1289}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001290
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001291llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1292 const char *Section,
1293 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001294 // Return null for empty list.
1295 if (Methods.empty())
1296 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1297
1298 std::vector<llvm::Constant*> Values(2);
1299 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1300 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1301 Methods.size());
1302 Values[1] = llvm::ConstantArray::get(AT, Methods);
1303 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1304
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001305 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001306 return llvm::ConstantExpr::getBitCast(GV,
1307 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001308}
1309
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001310/*
1311 struct _objc_category {
1312 char *category_name;
1313 char *class_name;
1314 struct _objc_method_list *instance_methods;
1315 struct _objc_method_list *class_methods;
1316 struct _objc_protocol_list *protocols;
1317 uint32_t size; // <rdar://4585769>
1318 struct _objc_property_list *instance_properties;
1319 };
1320 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001321void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001322 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001323
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001324 // FIXME: This is poor design, the OCD should have a pointer to the
1325 // category decl. Additionally, note that Category can be null for
1326 // the @implementation w/o an @interface case. Sema should just
1327 // create one for us as it does for @implementation so everyone else
1328 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001329 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001330 const ObjCCategoryDecl *Category =
1331 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001332 std::string ExtName(Interface->getNameAsString() + "_" +
1333 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001334
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001335 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1336 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1337 e = OCD->instmeth_end(); i != e; ++i) {
1338 // Instance methods should always be defined.
1339 InstanceMethods.push_back(GetMethodConstant(*i));
1340 }
1341 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1342 e = OCD->classmeth_end(); i != e; ++i) {
1343 // Class methods should always be defined.
1344 ClassMethods.push_back(GetMethodConstant(*i));
1345 }
1346
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001347 std::vector<llvm::Constant*> Values(7);
1348 Values[0] = GetClassName(OCD->getIdentifier());
1349 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001350 Values[2] =
1351 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1352 ExtName,
1353 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001354 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001355 Values[3] =
1356 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1357 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001358 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001359 if (Category) {
1360 Values[4] =
1361 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1362 Category->protocol_begin(),
1363 Category->protocol_end());
1364 } else {
1365 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1366 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001367 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001368
1369 // If there is no category @interface then there can be no properties.
1370 if (Category) {
1371 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001372 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001373 } else {
1374 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1375 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001376
1377 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1378 Values);
1379
1380 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001381 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1382 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001383 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001384 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001385}
1386
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001387// FIXME: Get from somewhere?
1388enum ClassFlags {
1389 eClassFlags_Factory = 0x00001,
1390 eClassFlags_Meta = 0x00002,
1391 // <rdr://5142207>
1392 eClassFlags_HasCXXStructors = 0x02000,
1393 eClassFlags_Hidden = 0x20000,
1394 eClassFlags_ABI2_Hidden = 0x00010,
1395 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1396};
1397
1398// <rdr://5142207&4705298&4843145>
1399static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1400 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1401 // FIXME: Support -fvisibility
1402 switch (attr->getVisibility()) {
1403 default:
1404 assert(0 && "Unknown visibility");
1405 return false;
1406 case VisibilityAttr::DefaultVisibility:
1407 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1408 return false;
1409 case VisibilityAttr::HiddenVisibility:
1410 return true;
1411 }
1412 } else {
1413 return false; // FIXME: Support -fvisibility
1414 }
1415}
1416
1417/*
1418 struct _objc_class {
1419 Class isa;
1420 Class super_class;
1421 const char *name;
1422 long version;
1423 long info;
1424 long instance_size;
1425 struct _objc_ivar_list *ivars;
1426 struct _objc_method_list *methods;
1427 struct _objc_cache *cache;
1428 struct _objc_protocol_list *protocols;
1429 // Objective-C 1.0 extensions (<rdr://4585769>)
1430 const char *ivar_layout;
1431 struct _objc_class_ext *ext;
1432 };
1433
1434 See EmitClassExtension();
1435 */
1436void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001437 DefinedSymbols.insert(ID->getIdentifier());
1438
Chris Lattner8ec03f52008-11-24 03:54:41 +00001439 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001440 // FIXME: Gross
1441 ObjCInterfaceDecl *Interface =
1442 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001443 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001444 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001445 Interface->protocol_begin(),
1446 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001447 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001448 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001449 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001450 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001451
1452 // FIXME: Set CXX-structors flag.
1453 if (IsClassHidden(ID->getClassInterface()))
1454 Flags |= eClassFlags_Hidden;
1455
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001456 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1457 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1458 e = ID->instmeth_end(); i != e; ++i) {
1459 // Instance methods should always be defined.
1460 InstanceMethods.push_back(GetMethodConstant(*i));
1461 }
1462 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1463 e = ID->classmeth_end(); i != e; ++i) {
1464 // Class methods should always be defined.
1465 ClassMethods.push_back(GetMethodConstant(*i));
1466 }
1467
1468 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1469 e = ID->propimpl_end(); i != e; ++i) {
1470 ObjCPropertyImplDecl *PID = *i;
1471
1472 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1473 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1474
1475 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1476 if (llvm::Constant *C = GetMethodConstant(MD))
1477 InstanceMethods.push_back(C);
1478 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1479 if (llvm::Constant *C = GetMethodConstant(MD))
1480 InstanceMethods.push_back(C);
1481 }
1482 }
1483
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001484 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001485 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001486 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001487 // Record a reference to the super class.
1488 LazySymbols.insert(Super->getIdentifier());
1489
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001490 Values[ 1] =
1491 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1492 ObjCTypes.ClassPtrTy);
1493 } else {
1494 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1495 }
1496 Values[ 2] = GetClassName(ID->getIdentifier());
1497 // Version is always 0.
1498 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1499 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1500 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001501 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001502 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001503 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001504 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001505 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 // cache is always NULL.
1507 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1508 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001509 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001510 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001511 Values[11] = EmitClassExtension(ID);
1512 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1513 Values);
1514
1515 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001516 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1517 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001518 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001519 DefinedClasses.push_back(GV);
1520}
1521
1522llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1523 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001524 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001525 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001526 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001527 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001528
1529 if (IsClassHidden(ID->getClassInterface()))
1530 Flags |= eClassFlags_Hidden;
1531
1532 std::vector<llvm::Constant*> Values(12);
1533 // The isa for the metaclass is the root of the hierarchy.
1534 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1535 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1536 Root = Super;
1537 Values[ 0] =
1538 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1539 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001540 // The super class for the metaclass is emitted as the name of the
1541 // super class. The runtime fixes this up to point to the
1542 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001543 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1544 Values[ 1] =
1545 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1546 ObjCTypes.ClassPtrTy);
1547 } else {
1548 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1549 }
1550 Values[ 2] = GetClassName(ID->getIdentifier());
1551 // Version is always 0.
1552 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1553 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1554 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001555 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001556 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001557 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001558 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001559 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001560 // cache is always NULL.
1561 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1562 Values[ 9] = Protocols;
1563 // ivar_layout for metaclass is always NULL.
1564 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1565 // The class extension is always unused for metaclasses.
1566 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1567 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1568 Values);
1569
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001570 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001571 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001572
1573 // Check for a forward reference.
1574 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1575 if (GV) {
1576 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1577 "Forward metaclass reference has incorrect type.");
1578 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1579 GV->setInitializer(Init);
1580 } else {
1581 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1582 llvm::GlobalValue::InternalLinkage,
1583 Init, Name,
1584 &CGM.getModule());
1585 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001586 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001587 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001588 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001589
1590 return GV;
1591}
1592
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001593llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001594 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001595
1596 // FIXME: Should we look these up somewhere other than the
1597 // module. Its a bit silly since we only generate these while
1598 // processing an implementation, so exactly one pointer would work
1599 // if know when we entered/exitted an implementation block.
1600
1601 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001602 // Previously, metaclass with internal linkage may have been defined.
1603 // pass 'true' as 2nd argument so it is returned.
1604 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001605 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1606 "Forward metaclass reference has incorrect type.");
1607 return GV;
1608 } else {
1609 // Generate as an external reference to keep a consistent
1610 // module. This will be patched up when we emit the metaclass.
1611 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1612 llvm::GlobalValue::ExternalLinkage,
1613 0,
1614 Name,
1615 &CGM.getModule());
1616 }
1617}
1618
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001619/*
1620 struct objc_class_ext {
1621 uint32_t size;
1622 const char *weak_ivar_layout;
1623 struct _objc_property_list *properties;
1624 };
1625*/
1626llvm::Constant *
1627CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1628 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001629 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001630
1631 std::vector<llvm::Constant*> Values(3);
1632 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001633 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001634 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001635 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001636 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001637
1638 // Return null if no extension bits are used.
1639 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1640 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1641
1642 llvm::Constant *Init =
1643 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001644 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1645 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001646}
1647
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001648/// countInheritedIvars - count number of ivars in class and its super class(s)
1649///
1650static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1651 int count = 0;
1652 if (!OI)
1653 return 0;
1654 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1655 if (SuperClass)
1656 count += countInheritedIvars(SuperClass);
1657 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1658 E = OI->ivar_end(); I != E; ++I)
1659 ++count;
1660 return count;
1661}
1662
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001663/// getInterfaceDeclForIvar - Get the interface declaration node where
1664/// this ivar is declared in.
1665/// FIXME. Ideally, this info should be in the ivar node. But currently
1666/// it is not and prevailing wisdom is that ASTs should not have more
1667/// info than is absolutely needed, even though this info reflects the
1668/// source language.
1669///
1670static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1671 const ObjCInterfaceDecl *OI,
1672 const ObjCIvarDecl *IVD) {
1673 if (!OI)
1674 return 0;
1675 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1676 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1677 E = OI->ivar_end(); I != E; ++I)
1678 if ((*I)->getIdentifier() == IVD->getIdentifier())
1679 return OI;
1680 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1681}
1682
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001683/*
1684 struct objc_ivar {
1685 char *ivar_name;
1686 char *ivar_type;
1687 int ivar_offset;
1688 };
1689
1690 struct objc_ivar_list {
1691 int ivar_count;
1692 struct objc_ivar list[count];
1693 };
1694 */
1695llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001696 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001697 std::vector<llvm::Constant*> Ivars, Ivar(3);
1698
1699 // When emitting the root class GCC emits ivar entries for the
1700 // actual class structure. It is not clear if we need to follow this
1701 // behavior; for now lets try and get away with not doing it. If so,
1702 // the cleanest solution would be to make up an ObjCInterfaceDecl
1703 // for the class.
1704 if (ForClass)
1705 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001706
1707 ObjCInterfaceDecl *OID =
1708 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1709 const llvm::Type *InterfaceTy =
1710 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001711 const llvm::StructLayout *Layout =
1712 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001713
1714 RecordDecl::field_iterator ifield, pfield;
1715 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001716 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1717 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001718 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001719 if (Field->getIdentifier())
1720 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1721 else
1722 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001723 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001724 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001725 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001726 }
1727
1728 // Return null for empty list.
1729 if (Ivars.empty())
1730 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1731
1732 std::vector<llvm::Constant*> Values(2);
1733 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1734 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1735 Ivars.size());
1736 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1737 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1738
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001739 llvm::GlobalVariable *GV;
1740 if (ForClass)
1741 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001742 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1743 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001744 else
1745 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1746 + ID->getNameAsString(),
1747 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1748 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001749 return llvm::ConstantExpr::getBitCast(GV,
1750 ObjCTypes.IvarListPtrTy);
1751}
1752
1753/*
1754 struct objc_method {
1755 SEL method_name;
1756 char *method_types;
1757 void *method;
1758 };
1759
1760 struct objc_method_list {
1761 struct objc_method_list *obsolete;
1762 int count;
1763 struct objc_method methods_list[count];
1764 };
1765*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001766
1767/// GetMethodConstant - Return a struct objc_method constant for the
1768/// given method if it has been defined. The result is null if the
1769/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001770llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001771 // FIXME: Use DenseMap::lookup
1772 llvm::Function *Fn = MethodDefinitions[MD];
1773 if (!Fn)
1774 return 0;
1775
1776 std::vector<llvm::Constant*> Method(3);
1777 Method[0] =
1778 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1779 ObjCTypes.SelectorPtrTy);
1780 Method[1] = GetMethodVarType(MD);
1781 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1782 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1783}
1784
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001785llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1786 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001787 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001788 // Return null for empty list.
1789 if (Methods.empty())
1790 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1791
1792 std::vector<llvm::Constant*> Values(3);
1793 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1794 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1795 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1796 Methods.size());
1797 Values[2] = llvm::ConstantArray::get(AT, Methods);
1798 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1799
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001800 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001801 return llvm::ConstantExpr::getBitCast(GV,
1802 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001803}
1804
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001805llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001806 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001807 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001808 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001809
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001810 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001811 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001812 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001813 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001814 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001815 llvm::GlobalValue::InternalLinkage,
1816 Name,
1817 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001818 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001819
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001820 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001821}
1822
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001823uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
1824 FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001825 if (!Field->isBitField())
1826 return Layout->getElementOffset(
1827 CGM.getTypes().getLLVMFieldNo(Field));
1828 // FIXME. Must be a better way of getting a bitfield base offset.
1829 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1830 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1831 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1832 offset = (offset*size)/8;
1833 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001834}
1835
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001836llvm::GlobalVariable *
1837CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1838 llvm::Constant *Init,
1839 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001840 unsigned Align,
1841 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001842 const llvm::Type *Ty = Init->getType();
1843 llvm::GlobalVariable *GV =
1844 new llvm::GlobalVariable(Ty, false,
1845 llvm::GlobalValue::InternalLinkage,
1846 Init,
1847 Name,
1848 &CGM.getModule());
1849 if (Section)
1850 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001851 if (Align)
1852 GV->setAlignment(Align);
1853 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001854 UsedGlobals.push_back(GV);
1855 return GV;
1856}
1857
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001858llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001859 // Abuse this interface function as a place to finalize.
1860 FinishModule();
1861
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001862 return NULL;
1863}
1864
Daniel Dunbar49f66022008-09-24 03:38:44 +00001865llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1866 return ObjCTypes.GetPropertyFn;
1867}
1868
1869llvm::Function *CGObjCMac::GetPropertySetFunction() {
1870 return ObjCTypes.SetPropertyFn;
1871}
1872
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001873llvm::Function *CGObjCMac::EnumerationMutationFunction()
1874{
1875 return ObjCTypes.EnumerationMutationFn;
1876}
1877
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001878/*
1879
1880Objective-C setjmp-longjmp (sjlj) Exception Handling
1881--
1882
1883The basic framework for a @try-catch-finally is as follows:
1884{
1885 objc_exception_data d;
1886 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001887 bool _call_try_exit = true;
1888
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001889 objc_exception_try_enter(&d);
1890 if (!setjmp(d.jmp_buf)) {
1891 ... try body ...
1892 } else {
1893 // exception path
1894 id _caught = objc_exception_extract(&d);
1895
1896 // enter new try scope for handlers
1897 if (!setjmp(d.jmp_buf)) {
1898 ... match exception and execute catch blocks ...
1899
1900 // fell off end, rethrow.
1901 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001902 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001903 } else {
1904 // exception in catch block
1905 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001906 _call_try_exit = false;
1907 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001908 }
1909 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001910 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001911
1912finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001913 if (_call_try_exit)
1914 objc_exception_try_exit(&d);
1915
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001916 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001917 ... dispatch to finally destination ...
1918
1919finally_rethrow:
1920 objc_exception_throw(_rethrow);
1921
1922finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001923}
1924
1925This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001926uses _rethrow to determine if objc_exception_try_exit should be called
1927and if the object should be rethrown. This breaks in the face of
1928throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001929
1930We specialize this framework for a few particular circumstances:
1931
1932 - If there are no catch blocks, then we avoid emitting the second
1933 exception handling context.
1934
1935 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1936 e)) we avoid emitting the code to rethrow an uncaught exception.
1937
1938 - FIXME: If there is no @finally block we can do a few more
1939 simplifications.
1940
1941Rethrows and Jumps-Through-Finally
1942--
1943
1944Support for implicit rethrows and jumping through the finally block is
1945handled by storing the current exception-handling context in
1946ObjCEHStack.
1947
Daniel Dunbar898d5082008-09-30 01:06:03 +00001948In order to implement proper @finally semantics, we support one basic
1949mechanism for jumping through the finally block to an arbitrary
1950destination. Constructs which generate exits from a @try or @catch
1951block use this mechanism to implement the proper semantics by chaining
1952jumps, as necessary.
1953
1954This mechanism works like the one used for indirect goto: we
1955arbitrarily assign an ID to each destination and store the ID for the
1956destination in a variable prior to entering the finally block. At the
1957end of the finally block we simply create a switch to the proper
1958destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001959
1960Code gen for @synchronized(expr) stmt;
1961Effectively generating code for:
1962objc_sync_enter(expr);
1963@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001964*/
1965
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001966void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1967 const Stmt &S) {
1968 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001969 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001970 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001971 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001972 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1973 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1974 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001975
1976 // For @synchronized, call objc_sync_enter(sync.expr). The
1977 // evaluation of the expression must occur before we enter the
1978 // @synchronized. We can safely avoid a temp here because jumps into
1979 // @synchronized are illegal & this will dominate uses.
1980 llvm::Value *SyncArg = 0;
1981 if (!isTry) {
1982 SyncArg =
1983 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1984 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1985 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1986 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001987
1988 // Push an EH context entry, used for handling rethrows and jumps
1989 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001990 CGF.PushCleanupBlock(FinallyBlock);
1991
Anders Carlsson273558f2009-02-07 21:37:21 +00001992 CGF.ObjCEHValueStack.push_back(0);
1993
Daniel Dunbar898d5082008-09-30 01:06:03 +00001994 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001995 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1996 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001997 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1998 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001999 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2000 "_call_try_exit");
2001 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2002
Anders Carlsson80f25672008-09-09 17:59:25 +00002003 // Enter a new try block and call setjmp.
2004 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2005 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2006 "jmpbufarray");
2007 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2008 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2009 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002010
Daniel Dunbar55e87422008-11-11 02:29:29 +00002011 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2012 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002013 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002014 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002015
2016 // Emit the @try block.
2017 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002018 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2019 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002020 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002021
2022 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002023 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002024
2025 // Retrieve the exception object. We may emit multiple blocks but
2026 // nothing can cross this so the value is already in SSA form.
2027 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2028 ExceptionData,
2029 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002030 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002031 if (!isTry)
2032 {
2033 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002034 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002035 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002036 }
2037 else if (const ObjCAtCatchStmt* CatchStmt =
2038 cast<ObjCAtTryStmt>(S).getCatchStmts())
2039 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002040 // Enter a new exception try block (in case a @catch block throws
2041 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002042 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002043
Anders Carlsson80f25672008-09-09 17:59:25 +00002044 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2045 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002046 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002047
Daniel Dunbar55e87422008-11-11 02:29:29 +00002048 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2049 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002050 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002051
2052 CGF.EmitBlock(CatchBlock);
2053
Daniel Dunbar55e40722008-09-27 07:03:52 +00002054 // Handle catch list. As a special case we check if everything is
2055 // matched and avoid generating code for falling off the end if
2056 // so.
2057 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002058 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002059 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002060
Steve Naroff7ba138a2009-03-03 19:52:17 +00002061 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002062 const PointerType *PT = 0;
2063
Anders Carlsson80f25672008-09-09 17:59:25 +00002064 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002065 if (!CatchParam) {
2066 AllMatched = true;
2067 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002068 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002069
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002070 // catch(id e) always matches.
2071 // FIXME: For the time being we also match id<X>; this should
2072 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002073 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002074 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002075 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002076 }
2077
Daniel Dunbar55e40722008-09-27 07:03:52 +00002078 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002079 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002080 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002081 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002082 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002083 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002084
Anders Carlssondde0a942008-09-11 09:15:33 +00002085 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002086 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002087 break;
2088 }
2089
Daniel Dunbar129271a2008-09-27 07:36:24 +00002090 assert(PT && "Unexpected non-pointer type in @catch");
2091 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002092 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002093 assert(ObjCType && "Catch parameter must have Objective-C type!");
2094
2095 // Check if the @catch block matches the exception object.
2096 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2097
Anders Carlsson80f25672008-09-09 17:59:25 +00002098 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2099 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002100
Daniel Dunbar55e87422008-11-11 02:29:29 +00002101 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002102
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002103 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002104 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002105
2106 // Emit the @catch block.
2107 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002108 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002109 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002110
2111 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002112 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002113 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002114 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002115
2116 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002117 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002118
2119 CGF.EmitBlock(NextCatchBlock);
2120 }
2121
Daniel Dunbar55e40722008-09-27 07:03:52 +00002122 if (!AllMatched) {
2123 // None of the handlers caught the exception, so store it to be
2124 // rethrown at the end of the @finally block.
2125 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002126 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002127 }
2128
2129 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002130 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002131 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2132 ExceptionData),
2133 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002134 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002135 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002136 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002137 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002138 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002139 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002140 }
2141
Daniel Dunbar898d5082008-09-30 01:06:03 +00002142 // Pop the exception-handling stack entry. It is important to do
2143 // this now, because the code in the @finally block is not in this
2144 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002145 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2146
Anders Carlsson273558f2009-02-07 21:37:21 +00002147 CGF.ObjCEHValueStack.pop_back();
2148
Anders Carlsson80f25672008-09-09 17:59:25 +00002149 // Emit the @finally block.
2150 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002151 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2152
2153 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2154
2155 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002156 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002157
2158 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002159 if (isTry) {
2160 if (const ObjCAtFinallyStmt* FinallyStmt =
2161 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2162 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002163 } else {
2164 // Emit objc_sync_exit(expr); as finally's sole statement for
2165 // @synchronized.
2166 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002167 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002168
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002169 // Emit the switch block
2170 if (Info.SwitchBlock)
2171 CGF.EmitBlock(Info.SwitchBlock);
2172 if (Info.EndBlock)
2173 CGF.EmitBlock(Info.EndBlock);
2174
Daniel Dunbar898d5082008-09-30 01:06:03 +00002175 CGF.EmitBlock(FinallyRethrow);
2176 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2177 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002178 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002179
2180 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002181}
2182
2183void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002184 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002185 llvm::Value *ExceptionAsObject;
2186
2187 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2188 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2189 ExceptionAsObject =
2190 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2191 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002192 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002193 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002194 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002195 }
2196
2197 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002198 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002199
2200 // Clear the insertion point to indicate we are in unreachable code.
2201 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002202}
2203
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002204/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002205/// object: objc_read_weak (id *src)
2206///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002207llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002208 llvm::Value *AddrWeakObj)
2209{
Eli Friedman8339b352009-03-07 03:57:15 +00002210 const llvm::Type* DestTy =
2211 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002212 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002213 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002214 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002215 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002216 return read_weak;
2217}
2218
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002219/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2220/// objc_assign_weak (id src, id *dst)
2221///
2222void CGObjCMac::EmitObjCWeakAssign(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 Jahanian3e283e32008-11-18 22:37:34 +00002227 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2228 src, dst, "weakassign");
2229 return;
2230}
2231
Fariborz Jahanian58626502008-11-19 00:59:10 +00002232/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2233/// objc_assign_global (id src, id *dst)
2234///
2235void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2236 llvm::Value *src, llvm::Value *dst)
2237{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002238 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2239 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002240 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2241 src, dst, "globalassign");
2242 return;
2243}
2244
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002245/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2246/// objc_assign_ivar (id src, id *dst)
2247///
2248void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2249 llvm::Value *src, llvm::Value *dst)
2250{
2251 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2252 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2253 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2254 src, dst, "assignivar");
2255 return;
2256}
2257
Fariborz Jahanian58626502008-11-19 00:59:10 +00002258/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2259/// objc_assign_strongCast (id src, id *dst)
2260///
2261void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2262 llvm::Value *src, llvm::Value *dst)
2263{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002264 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2265 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002266 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2267 src, dst, "weakassign");
2268 return;
2269}
2270
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002271/// EmitObjCValueForIvar - Code Gen for ivar reference.
2272///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002273LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2274 QualType ObjectTy,
2275 llvm::Value *BaseValue,
2276 const ObjCIvarDecl *Ivar,
2277 const FieldDecl *Field,
2278 unsigned CVRQualifiers) {
2279 if (Ivar->isBitField())
2280 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2281 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002282 // TODO: Add a special case for isa (index 0)
2283 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2284 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002285 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002286 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2287 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002288 LValue::SetObjCIvar(LV, true);
2289 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002290}
2291
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002292llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2293 ObjCInterfaceDecl *Interface,
2294 const ObjCIvarDecl *Ivar) {
2295 const llvm::Type *InterfaceLTy =
2296 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2297 const llvm::StructLayout *Layout =
2298 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2299 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002300 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002301 return llvm::ConstantInt::get(
2302 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2303 Offset);
2304}
2305
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002306/* *** Private Interface *** */
2307
2308/// EmitImageInfo - Emit the image info marker used to encode some module
2309/// level information.
2310///
2311/// See: <rdr://4810609&4810587&4810587>
2312/// struct IMAGE_INFO {
2313/// unsigned version;
2314/// unsigned flags;
2315/// };
2316enum ImageInfoFlags {
2317 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2318 eImageInfo_GarbageCollected = (1 << 1),
2319 eImageInfo_GCOnly = (1 << 2)
2320};
2321
2322void CGObjCMac::EmitImageInfo() {
2323 unsigned version = 0; // Version is unused?
2324 unsigned flags = 0;
2325
2326 // FIXME: Fix and continue?
2327 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2328 flags |= eImageInfo_GarbageCollected;
2329 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2330 flags |= eImageInfo_GCOnly;
2331
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002332 // Emitted as int[2];
2333 llvm::Constant *values[2] = {
2334 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2335 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2336 };
2337 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002338
2339 const char *Section;
2340 if (ObjCABI == 1)
2341 Section = "__OBJC, __image_info,regular";
2342 else
2343 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002344 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002345 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2346 llvm::ConstantArray::get(AT, values, 2),
2347 Section,
2348 0,
2349 true);
2350 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002351}
2352
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002353
2354// struct objc_module {
2355// unsigned long version;
2356// unsigned long size;
2357// const char *name;
2358// Symtab symtab;
2359// };
2360
2361// FIXME: Get from somewhere
2362static const int ModuleVersion = 7;
2363
2364void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002365 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002366
2367 std::vector<llvm::Constant*> Values(4);
2368 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2369 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002370 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002371 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002372 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002373 CreateMetadataVar("\01L_OBJC_MODULES",
2374 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2375 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002376 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002377}
2378
2379llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002380 unsigned NumClasses = DefinedClasses.size();
2381 unsigned NumCategories = DefinedCategories.size();
2382
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002383 // Return null if no symbols were defined.
2384 if (!NumClasses && !NumCategories)
2385 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2386
2387 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002388 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2389 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2390 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2391 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2392
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002393 // The runtime expects exactly the list of defined classes followed
2394 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002395 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002396 for (unsigned i=0; i<NumClasses; i++)
2397 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2398 ObjCTypes.Int8PtrTy);
2399 for (unsigned i=0; i<NumCategories; i++)
2400 Symbols[NumClasses + i] =
2401 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2402 ObjCTypes.Int8PtrTy);
2403
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002404 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002405 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002406 NumClasses + NumCategories),
2407 Symbols);
2408
2409 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2410
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002411 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002412 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2413 "__OBJC,__symbols,regular,no_dead_strip",
2414 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002415 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2416}
2417
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002418llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002419 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002420 LazySymbols.insert(ID->getIdentifier());
2421
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002422 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2423
2424 if (!Entry) {
2425 llvm::Constant *Casted =
2426 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2427 ObjCTypes.ClassPtrTy);
2428 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002429 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2430 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2431 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002432 }
2433
2434 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002435}
2436
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002437llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002438 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2439
2440 if (!Entry) {
2441 llvm::Constant *Casted =
2442 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2443 ObjCTypes.SelectorPtrTy);
2444 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002445 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2446 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2447 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002448 }
2449
2450 return Builder.CreateLoad(Entry, false, "tmp");
2451}
2452
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002453llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002454 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002455
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002456 if (!Entry)
2457 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2458 llvm::ConstantArray::get(Ident->getName()),
2459 "__TEXT,__cstring,cstring_literals",
2460 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002461
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002462 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002463}
2464
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002465/// GetIvarLayoutName - Returns a unique constant for the given
2466/// ivar layout bitmap.
2467llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2468 const ObjCCommonTypesHelper &ObjCTypes) {
2469 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2470}
2471
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002472void CGObjCCommonMac::BuildAggrIvarLayout(const llvm::StructLayout *Layout,
2473 const RecordDecl *RD,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002474 const std::vector<FieldDecl*>& RecFields,
2475 unsigned int BytePos, bool ForStrongLayout,
2476 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002477 bool IsUnion = (RD && RD->isUnion());
2478 uint64_t MaxUnionIvarSize = 0;
2479 uint64_t MaxSkippedUnionIvarSize = 0;
2480 FieldDecl *MaxField = 0;
2481 FieldDecl *MaxSkippedField = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002482 unsigned int base = 0;
2483 if (RecFields.empty())
2484 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002485 if (IsUnion)
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002486 base = BytePos + GetIvarBaseOffset(Layout, RecFields[0]);
2487
2488 for (unsigned i = 0; i < RecFields.size(); i++) {
2489 FieldDecl *Field = RecFields[i];
2490 // Skip over unnamed or bitfields
2491 if (!Field->getIdentifier() || Field->isBitField())
2492 continue;
2493 QualType FQT = Field->getType();
2494 if (FQT->isAggregateType()) {
2495 std::vector<FieldDecl*> NestedRecFields;
2496 if (FQT->isUnionType())
2497 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002498 else
2499 assert(FQT->isRecordType() &&
2500 "only union/record is supported for ivar layout bitmap");
2501
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002502 const RecordType *RT = FQT->getAsRecordType();
2503 const RecordDecl *RD = RT->getDecl();
2504 // FIXME - Find a more efficiant way of passing records down.
2505 unsigned j = 0;
2506 for (RecordDecl::field_iterator i = RD->field_begin(),
2507 e = RD->field_end(); i != e; ++i)
2508 NestedRecFields[j++] = (*i);
2509 // FIXME - Is Layout correct?
2510 BuildAggrIvarLayout(Layout, RD, NestedRecFields,
2511 BytePos + GetIvarBaseOffset(Layout, Field),
2512 ForStrongLayout, Index, SkIndex,
2513 HasUnion);
2514 continue;
2515 }
2516 else if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002517 const ConstantArrayType *CArray =
2518 dyn_cast_or_null<ConstantArrayType>(Array);
2519 assert(CArray && "only array with know element size is supported");
2520 FQT = CArray->getElementType();
2521 assert(!FQT->isUnionType() &&
2522 "layout for array of unions not supported");
2523 if (FQT->isRecordType()) {
2524 uint64_t ElCount = CArray->getSize().getZExtValue();
2525 int OldIndex = Index;
2526 int OldSkIndex = SkIndex;
2527
2528 std::vector<FieldDecl*> ElementRecFields;
2529 // FIXME - Use a common routine with the above!
2530 const RecordType *RT = FQT->getAsRecordType();
2531 const RecordDecl *RD = RT->getDecl();
2532 // FIXME - Find a more efficiant way of passing records down.
2533 unsigned j = 0;
2534 for (RecordDecl::field_iterator i = RD->field_begin(),
2535 e = RD->field_end(); i != e; ++i)
2536 ElementRecFields[j++] = (*i);
2537 BuildAggrIvarLayout(Layout, RD,
2538 ElementRecFields,
2539 BytePos + GetIvarBaseOffset(Layout, Field),
2540 ForStrongLayout, Index, SkIndex,
2541 HasUnion);
2542 // Replicate layout information for each array element. Note that
2543 // one element is already done.
2544 uint64_t ElIx = 1;
2545 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2546 ElIx < ElCount; ElIx++) {
2547 uint64_t Size = CGM.getContext().getTypeSize(RT);
2548 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2549 {
2550 IvarsInfo[++Index].ivar_bytepos =
2551 IvarsInfo[i].ivar_bytepos + Size*ElIx;
2552 IvarsInfo[Index].ivar_size = IvarsInfo[i].ivar_size;
2553 }
2554
2555 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
2556 {
2557 SkipIvars[++SkIndex].ivar_bytepos =
2558 SkipIvars[i].ivar_bytepos + Size*ElIx;
2559 SkipIvars[SkIndex].ivar_size = SkipIvars[i].ivar_size;
2560 }
2561 }
2562 continue;
2563 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002564 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002565 // At this point, we are done with Record/Union and array there of.
2566 // For other arrays we are down to its element type.
2567 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2568 do {
2569 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2570 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2571 break;
2572 }
2573 else if (FQT->hasObjCPointerRepresentation()) {
2574 GCAttr = QualType::Strong;
2575 break;
2576 }
2577 else if (const PointerType *PT = FQT->getAsPointerType()) {
2578 FQT = PT->getPointeeType();
2579 }
2580 else {
2581 break;
2582 }
2583 } while (true);
2584 if ((ForStrongLayout && GCAttr == QualType::Strong)
2585 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2586 if (IsUnion)
2587 {
2588 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2589 if (UnionIvarSize > MaxUnionIvarSize)
2590 {
2591 MaxUnionIvarSize = UnionIvarSize;
2592 MaxField = Field;
2593 }
2594 }
2595 else
2596 {
2597 IvarsInfo[++Index].ivar_bytepos =
2598 BytePos + GetIvarBaseOffset(Layout, Field);
2599 IvarsInfo[Index].ivar_size =
2600 CGM.getContext().getTypeSize(Field->getType());
2601 }
2602 }
2603 else if ((ForStrongLayout &&
2604 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2605 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2606 if (IsUnion)
2607 {
2608 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2609 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2610 {
2611 MaxSkippedUnionIvarSize = UnionIvarSize;
2612 MaxSkippedField = Field;
2613 }
2614 }
2615 else
2616 {
2617 SkipIvars[++SkIndex].ivar_bytepos =
2618 BytePos + GetIvarBaseOffset(Layout, Field);
2619 SkipIvars[SkIndex].ivar_size =
2620 CGM.getContext().getTypeSize(Field->getType());
2621 }
2622 }
2623 }
2624 if (MaxField)
2625 {
2626 IvarsInfo[++Index].ivar_bytepos =
2627 BytePos + GetIvarBaseOffset(Layout, MaxField);
2628 IvarsInfo[Index].ivar_size = MaxUnionIvarSize;
2629 }
2630 if (MaxSkippedField)
2631 {
2632 SkipIvars[++SkIndex].ivar_bytepos =
2633 BytePos + GetIvarBaseOffset(Layout, MaxSkippedField);
2634 SkipIvars[SkIndex].ivar_size = MaxSkippedUnionIvarSize;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002635 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002636 return;
2637}
2638
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002639static int
2640IvarBytePosCompare (const void *a, const void *b)
2641{
2642 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2643 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2644
2645 if (sa < sb)
2646 return -1;
2647 if (sa > sb)
2648 return 1;
2649 return 0;
2650}
2651
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002652/// BuildIvarLayout - Builds ivar layout bitmap for the class
2653/// implementation for the __strong or __weak case.
2654/// The layout map displays which words in ivar list must be skipped
2655/// and which must be scanned by GC (see below). String is built of bytes.
2656/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2657/// of words to skip and right nibble is count of words to scan. So, each
2658/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2659/// represented by a 0x00 byte which also ends the string.
2660/// 1. when ForStrongLayout is true, following ivars are scanned:
2661/// - id, Class
2662/// - object *
2663/// - __strong anything
2664///
2665/// 2. When ForStrongLayout is false, following ivars are scanned:
2666/// - __weak anything
2667///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002668llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002669 const llvm::StructLayout *Layout,
2670 ObjCImplementationDecl *OMD,
2671 bool ForStrongLayout,
2672 const ObjCCommonTypesHelper &ObjCTypes) {
2673 int Index = -1;
2674 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002675 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002676 int SkipScan;
2677 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002678
2679 std::vector<FieldDecl*> RecFields;
2680 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2681 CGM.getContext().CollectObjCIvars(OI, RecFields);
2682 if (RecFields.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002683 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2684
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002685 BuildAggrIvarLayout (Layout, 0, RecFields, 0, ForStrongLayout,
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002686 Index, SkIndex, hasUnion);
2687 if (Index == -1)
2688 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2689
2690 // Sort on byte position in case we encounterred a union nested in
2691 // the ivar list.
2692 if (hasUnion && Index > 0)
2693 // FIXME - Is this correct?
2694 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2695 if (hasUnion && SkIndex > 0)
2696 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2697
2698 // Build the string of skip/scan nibbles
2699 SkipScan = -1;
2700 unsigned int WordSize =
2701 CGM.getTypes().getTargetData().getTypePaddedSize(ObjCTypes.Int8PtrTy);
2702 if (IvarsInfo[0].ivar_bytepos == 0) {
2703 WordsToSkip = 0;
2704 WordsToScan = IvarsInfo[0].ivar_size;
2705 }
2706 else {
2707 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2708 WordsToScan = IvarsInfo[0].ivar_size;
2709 }
2710 for (int i=1; i <= Index; i++)
2711 {
2712 unsigned int TailPrevGCObjC =
2713 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2714 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2715 {
2716 // consecutive 'scanned' object pointers.
2717 WordsToScan += IvarsInfo[i].ivar_size;
2718 }
2719 else
2720 {
2721 // Skip over 'gc'able object pointer which lay over each other.
2722 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2723 continue;
2724 // Must skip over 1 or more words. We save current skip/scan values
2725 // and start a new pair.
2726 SkipScanIvars[++SkipScan].skip = WordsToSkip;
2727 SkipScanIvars[SkipScan].scan = WordsToScan;
2728 // Skip the hole.
2729 SkipScanIvars[++SkipScan].skip =
2730 (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2731 SkipScanIvars[SkipScan].scan = 0;
2732 WordsToSkip = 0;
2733 WordsToScan = IvarsInfo[i].ivar_size;
2734 }
2735 }
2736 if (WordsToScan > 0)
2737 {
2738 SkipScanIvars[++SkipScan].skip = WordsToSkip;
2739 SkipScanIvars[SkipScan].scan = WordsToScan;
2740 }
2741
2742 bool BytesSkipped = false;
2743 if (SkIndex >= 0)
2744 {
2745 int LastByteSkipped =
2746 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2747 int LastByteScanned =
2748 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2749 BytesSkipped = (LastByteSkipped > LastByteScanned);
2750 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2751 if (BytesSkipped)
2752 {
2753 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
2754 SkipScanIvars[++SkipScan].skip = TotalWords - (LastByteScanned/WordSize);
2755 SkipScanIvars[SkipScan].scan = 0;
2756 }
2757 }
2758 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2759 // as 0xMN.
2760 for (int i = 0; i <= SkipScan; i++)
2761 {
2762 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2763 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2764 // 0xM0 followed by 0x0N detected.
2765 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2766 for (int j = i+1; j < SkipScan; j++)
2767 SkipScanIvars[j] = SkipScanIvars[j+1];
2768 --SkipScan;
2769 }
2770 }
2771
2772 // Generate the string.
2773 std::string BitMap;
2774 for (int i = 0; i <= SkipScan; i++)
2775 {
2776 unsigned char byte;
2777 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2778 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2779 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2780 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2781
2782 if (skip_small > 0 || skip_big > 0)
2783 BytesSkipped = true;
2784 // first skip big.
2785 for (unsigned int ix = 0; ix < skip_big; ix++)
2786 BitMap += (unsigned char)(0xf0);
2787
2788 // next (skip small, scan)
2789 if (skip_small)
2790 {
2791 byte = skip_small << 4;
2792 if (scan_big > 0)
2793 {
2794 byte |= 0xf;
2795 --scan_big;
2796 }
2797 else if (scan_small)
2798 {
2799 byte |= scan_small;
2800 scan_small = 0;
2801 }
2802 BitMap += byte;
2803 }
2804 // next scan big
2805 for (unsigned int ix = 0; ix < scan_big; ix++)
2806 BitMap += (unsigned char)(0x0f);
2807 // last scan small
2808 if (scan_small)
2809 {
2810 byte = scan_small;
2811 BitMap += byte;
2812 }
2813 }
2814 // null terminate string.
2815 // BitMap += (unsigned char)0;
2816 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2817 // final layout.
2818 if (ForStrongLayout && !BytesSkipped)
2819 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2820
2821 return llvm::ConstantArray::get(BitMap);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002822}
2823
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002824llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002825 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2826
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002827 // FIXME: Avoid std::string copying.
2828 if (!Entry)
2829 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2830 llvm::ConstantArray::get(Sel.getAsString()),
2831 "__TEXT,__cstring,cstring_literals",
2832 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002833
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002834 return getConstantGEP(Entry, 0, 0);
2835}
2836
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002837// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002838llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002839 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2840}
2841
2842// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002843llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002844 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2845}
2846
Devang Patel7794bb82009-03-04 18:21:39 +00002847llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2848 std::string TypeStr;
2849 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2850
2851 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002852
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002853 if (!Entry)
2854 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2855 llvm::ConstantArray::get(TypeStr),
2856 "__TEXT,__cstring,cstring_literals",
2857 0, true);
2858
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002859 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002860}
2861
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002862llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002863 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002864 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2865 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002866
2867 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2868
2869 if (!Entry) {
2870 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2871 Entry =
2872 new llvm::GlobalVariable(C->getType(), false,
2873 llvm::GlobalValue::InternalLinkage,
2874 C, "\01L_OBJC_METH_VAR_TYPE_",
2875 &CGM.getModule());
2876 Entry->setSection("__TEXT,__cstring,cstring_literals");
2877 UsedGlobals.push_back(Entry);
2878 }
2879
2880 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002881}
2882
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002883// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002884llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002885 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2886
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002887 if (!Entry)
2888 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
2889 llvm::ConstantArray::get(Ident->getName()),
2890 "__TEXT,__cstring,cstring_literals",
2891 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002892
2893 return getConstantGEP(Entry, 0, 0);
2894}
2895
2896// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002897// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002898llvm::Constant *
2899 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2900 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002901 std::string TypeStr;
2902 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002903 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2904}
2905
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002906void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2907 const ObjCContainerDecl *CD,
2908 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002909 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002910 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002911 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002912 assert (CD && "Missing container decl in GetNameForMethod");
2913 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002914 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2915 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002916 NameOut += ' ';
2917 NameOut += D->getSelector().getAsString();
2918 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002919}
2920
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002921/// GetFirstIvarInRecord - This routine returns the record for the
2922/// implementation of the fiven class OID. It also returns field
2923/// corresponding to the first ivar in the class in FIV. It also
2924/// returns the one before the first ivar.
2925///
2926const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2927 const ObjCInterfaceDecl *OID,
2928 RecordDecl::field_iterator &FIV,
2929 RecordDecl::field_iterator &PIV) {
2930 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2931 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2932 RecordDecl::field_iterator ifield = RD->field_begin();
2933 RecordDecl::field_iterator pfield = RD->field_end();
2934 while (countSuperClassIvars-- > 0) {
2935 pfield = ifield;
2936 ++ifield;
2937 }
2938 FIV = ifield;
2939 PIV = pfield;
2940 return RD;
2941}
2942
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002943void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002944 EmitModuleInfo();
2945
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002946 // Emit the dummy bodies for any protocols which were referenced but
2947 // never defined.
2948 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2949 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2950 if (i->second->hasInitializer())
2951 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002952
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002953 std::vector<llvm::Constant*> Values(5);
2954 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2955 Values[1] = GetClassName(i->first);
2956 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2957 Values[3] = Values[4] =
2958 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2959 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2960 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2961 Values));
2962 }
2963
2964 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002965 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002966 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002967 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002968 }
2969
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002970 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002971 llvm::GlobalValue *GV =
2972 new llvm::GlobalVariable(AT, false,
2973 llvm::GlobalValue::AppendingLinkage,
2974 llvm::ConstantArray::get(AT, Used),
2975 "llvm.used",
2976 &CGM.getModule());
2977
2978 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002979
2980 // Add assembler directives to add lazy undefined symbol references
2981 // for classes which are referenced but not defined. This is
2982 // important for correct linker interaction.
2983
2984 // FIXME: Uh, this isn't particularly portable.
2985 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002986
2987 if (!CGM.getModule().getModuleInlineAsm().empty())
2988 s << "\n";
2989
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002990 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2991 e = LazySymbols.end(); i != e; ++i) {
2992 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2993 }
2994 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2995 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002996 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002997 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2998 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002999
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003000 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003001}
3002
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003003CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003004 : CGObjCCommonMac(cgm),
3005 ObjCTypes(cgm)
3006{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003007 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003008 ObjCABI = 2;
3009}
3010
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003011/* *** */
3012
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003013ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3014: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003015{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003016 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3017 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003018
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003019 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003020 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003021 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003022 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3023
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003024 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003025 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003026 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003027
3028 // FIXME: It would be nice to unify this with the opaque type, so
3029 // that the IR comes out a bit cleaner.
3030 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3031 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003032
3033 // I'm not sure I like this. The implicit coordination is a bit
3034 // gross. We should solve this in a reasonable fashion because this
3035 // is a pretty common task (match some runtime data structure with
3036 // an LLVM data structure).
3037
3038 // FIXME: This is leaked.
3039 // FIXME: Merge with rewriter code?
3040
3041 // struct _objc_super {
3042 // id self;
3043 // Class cls;
3044 // }
3045 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3046 SourceLocation(),
3047 &Ctx.Idents.get("_objc_super"));
3048 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3049 Ctx.getObjCIdType(), 0, false));
3050 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3051 Ctx.getObjCClassType(), 0, false));
3052 RD->completeDefinition(Ctx);
3053
3054 SuperCTy = Ctx.getTagDeclType(RD);
3055 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3056
3057 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003058 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3059
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003060 // struct _prop_t {
3061 // char *name;
3062 // char *attributes;
3063 // }
3064 PropertyTy = llvm::StructType::get(Int8PtrTy,
3065 Int8PtrTy,
3066 NULL);
3067 CGM.getModule().addTypeName("struct._prop_t",
3068 PropertyTy);
3069
3070 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003071 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003072 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003073 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003074 // }
3075 PropertyListTy = llvm::StructType::get(IntTy,
3076 IntTy,
3077 llvm::ArrayType::get(PropertyTy, 0),
3078 NULL);
3079 CGM.getModule().addTypeName("struct._prop_list_t",
3080 PropertyListTy);
3081 // struct _prop_list_t *
3082 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3083
3084 // struct _objc_method {
3085 // SEL _cmd;
3086 // char *method_type;
3087 // char *_imp;
3088 // }
3089 MethodTy = llvm::StructType::get(SelectorPtrTy,
3090 Int8PtrTy,
3091 Int8PtrTy,
3092 NULL);
3093 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003094
3095 // struct _objc_cache *
3096 CacheTy = llvm::OpaqueType::get();
3097 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3098 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003099
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003100 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003101
3102 QualType IdType = Ctx.getObjCIdType();
3103 QualType SelType = Ctx.getObjCSelType();
3104 llvm::SmallVector<QualType,16> Params;
3105 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003106
3107 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003108 Params.push_back(IdType);
3109 Params.push_back(SelType);
3110 Params.push_back(Ctx.LongTy);
3111 Params.push_back(Ctx.BoolTy);
3112 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3113 false);
3114 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003115
3116 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3117 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003118 Params.push_back(IdType);
3119 Params.push_back(SelType);
3120 Params.push_back(Ctx.LongTy);
3121 Params.push_back(IdType);
3122 Params.push_back(Ctx.BoolTy);
3123 Params.push_back(Ctx.BoolTy);
3124 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3125 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3126
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003127 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003128
3129 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003130 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003131 Params.push_back(IdType);
3132 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3133 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3134 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003135
3136 // gc's API
3137 // id objc_read_weak (id *)
3138 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003139 Params.push_back(Ctx.getPointerType(IdType));
3140 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3141 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3142
3143 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003144 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003145 Params.push_back(IdType);
3146 Params.push_back(Ctx.getPointerType(IdType));
3147
3148 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3149 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3150 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3151 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3152 GcAssignStrongCastFn =
3153 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003154
3155 // void objc_exception_throw(id)
3156 Params.clear();
3157 Params.push_back(IdType);
3158
3159 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003160 ExceptionThrowFn =
3161 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003162
3163 // synchronized APIs
3164 // void objc_sync_enter (id)
3165 // void objc_sync_exit (id)
3166 Params.clear();
3167 Params.push_back(IdType);
3168
3169 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3170 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
3171 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003172}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003173
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003174ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3175 : ObjCCommonTypesHelper(cgm)
3176{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003177 // struct _objc_method_description {
3178 // SEL name;
3179 // char *types;
3180 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003181 MethodDescriptionTy =
3182 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003183 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003184 NULL);
3185 CGM.getModule().addTypeName("struct._objc_method_description",
3186 MethodDescriptionTy);
3187
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003188 // struct _objc_method_description_list {
3189 // int count;
3190 // struct _objc_method_description[1];
3191 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003192 MethodDescriptionListTy =
3193 llvm::StructType::get(IntTy,
3194 llvm::ArrayType::get(MethodDescriptionTy, 0),
3195 NULL);
3196 CGM.getModule().addTypeName("struct._objc_method_description_list",
3197 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003198
3199 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003200 MethodDescriptionListPtrTy =
3201 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3202
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003203 // Protocol description structures
3204
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003205 // struct _objc_protocol_extension {
3206 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3207 // struct _objc_method_description_list *optional_instance_methods;
3208 // struct _objc_method_description_list *optional_class_methods;
3209 // struct _objc_property_list *instance_properties;
3210 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003211 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003212 llvm::StructType::get(IntTy,
3213 MethodDescriptionListPtrTy,
3214 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003215 PropertyListPtrTy,
3216 NULL);
3217 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3218 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003219
3220 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003221 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3222
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003223 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003224
3225 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3226 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3227
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003228 const llvm::Type *T =
3229 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3230 LongTy,
3231 llvm::ArrayType::get(ProtocolTyHolder, 0),
3232 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003233 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3234
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003235 // struct _objc_protocol {
3236 // struct _objc_protocol_extension *isa;
3237 // char *protocol_name;
3238 // struct _objc_protocol **_objc_protocol_list;
3239 // struct _objc_method_description_list *instance_methods;
3240 // struct _objc_method_description_list *class_methods;
3241 // }
3242 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003243 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003244 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3245 MethodDescriptionListPtrTy,
3246 MethodDescriptionListPtrTy,
3247 NULL);
3248 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3249
3250 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3251 CGM.getModule().addTypeName("struct._objc_protocol_list",
3252 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003253 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003254 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3255
3256 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003257 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003258 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003259
3260 // Class description structures
3261
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003262 // struct _objc_ivar {
3263 // char *ivar_name;
3264 // char *ivar_type;
3265 // int ivar_offset;
3266 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003267 IvarTy = llvm::StructType::get(Int8PtrTy,
3268 Int8PtrTy,
3269 IntTy,
3270 NULL);
3271 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3272
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003273 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003274 IvarListTy = llvm::OpaqueType::get();
3275 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3276 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3277
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003278 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003279 MethodListTy = llvm::OpaqueType::get();
3280 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3281 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3282
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003283 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003284 ClassExtensionTy =
3285 llvm::StructType::get(IntTy,
3286 Int8PtrTy,
3287 PropertyListPtrTy,
3288 NULL);
3289 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3290 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3291
3292 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3293
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003294 // struct _objc_class {
3295 // Class isa;
3296 // Class super_class;
3297 // char *name;
3298 // long version;
3299 // long info;
3300 // long instance_size;
3301 // struct _objc_ivar_list *ivars;
3302 // struct _objc_method_list *methods;
3303 // struct _objc_cache *cache;
3304 // struct _objc_protocol_list *protocols;
3305 // char *ivar_layout;
3306 // struct _objc_class_ext *ext;
3307 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003308 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3309 llvm::PointerType::getUnqual(ClassTyHolder),
3310 Int8PtrTy,
3311 LongTy,
3312 LongTy,
3313 LongTy,
3314 IvarListPtrTy,
3315 MethodListPtrTy,
3316 CachePtrTy,
3317 ProtocolListPtrTy,
3318 Int8PtrTy,
3319 ClassExtensionPtrTy,
3320 NULL);
3321 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3322
3323 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3324 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3325 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3326
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003327 // struct _objc_category {
3328 // char *category_name;
3329 // char *class_name;
3330 // struct _objc_method_list *instance_method;
3331 // struct _objc_method_list *class_method;
3332 // uint32_t size; // sizeof(struct _objc_category)
3333 // struct _objc_property_list *instance_properties;// category's @property
3334 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003335 CategoryTy = llvm::StructType::get(Int8PtrTy,
3336 Int8PtrTy,
3337 MethodListPtrTy,
3338 MethodListPtrTy,
3339 ProtocolListPtrTy,
3340 IntTy,
3341 PropertyListPtrTy,
3342 NULL);
3343 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3344
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003345 // Global metadata structures
3346
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003347 // struct _objc_symtab {
3348 // long sel_ref_cnt;
3349 // SEL *refs;
3350 // short cls_def_cnt;
3351 // short cat_def_cnt;
3352 // char *defs[cls_def_cnt + cat_def_cnt];
3353 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003354 SymtabTy = llvm::StructType::get(LongTy,
3355 SelectorPtrTy,
3356 ShortTy,
3357 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003358 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003359 NULL);
3360 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3361 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3362
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003363 // struct _objc_module {
3364 // long version;
3365 // long size; // sizeof(struct _objc_module)
3366 // char *name;
3367 // struct _objc_symtab* symtab;
3368 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003369 ModuleTy =
3370 llvm::StructType::get(LongTy,
3371 LongTy,
3372 Int8PtrTy,
3373 SymtabPtrTy,
3374 NULL);
3375 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003376
Daniel Dunbar49f66022008-09-24 03:38:44 +00003377 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003378
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003379 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003380 std::vector<const llvm::Type*> Params;
3381 Params.push_back(ObjectPtrTy);
3382 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003383 MessageSendFn =
3384 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3385 Params,
3386 true),
3387 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003388
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003389 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003390 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003391 Params.push_back(ObjectPtrTy);
3392 Params.push_back(SelectorPtrTy);
3393 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003394 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3395 Params,
3396 true),
3397 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003398
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003399 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003400 Params.clear();
3401 Params.push_back(ObjectPtrTy);
3402 Params.push_back(SelectorPtrTy);
3403 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003404 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003405 MessageSendFpretFn =
3406 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3407 Params,
3408 true),
3409 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003410
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003411 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003412 Params.clear();
3413 Params.push_back(SuperPtrTy);
3414 Params.push_back(SelectorPtrTy);
3415 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003416 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3417 Params,
3418 true),
3419 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003420
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003421 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3422 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003423 Params.clear();
3424 Params.push_back(Int8PtrTy);
3425 Params.push_back(SuperPtrTy);
3426 Params.push_back(SelectorPtrTy);
3427 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003428 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3429 Params,
3430 true),
3431 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003432
3433 // There is no objc_msgSendSuper_fpret? How can that work?
3434 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003435
Anders Carlsson124526b2008-09-09 10:10:21 +00003436 // FIXME: This is the size of the setjmp buffer and should be
3437 // target specific. 18 is what's used on 32-bit X86.
3438 uint64_t SetJmpBufferSize = 18;
3439
3440 // Exceptions
3441 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003442 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003443
3444 ExceptionDataTy =
3445 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3446 SetJmpBufferSize),
3447 StackPtrTy, NULL);
3448 CGM.getModule().addTypeName("struct._objc_exception_data",
3449 ExceptionDataTy);
3450
3451 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003452 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3453 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003454 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3455 Params,
3456 false),
3457 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003458 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003459 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3460 Params,
3461 false),
3462 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003463 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003464 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3465 Params,
3466 false),
3467 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003468
3469 Params.clear();
3470 Params.push_back(ClassPtrTy);
3471 Params.push_back(ObjectPtrTy);
3472 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003473 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3474 Params,
3475 false),
3476 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003477
Anders Carlsson124526b2008-09-09 10:10:21 +00003478 Params.clear();
3479 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3480 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003481 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3482 Params,
3483 false),
3484 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003485
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003486}
3487
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003488ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003489: ObjCCommonTypesHelper(cgm)
3490{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003491 // struct _method_list_t {
3492 // uint32_t entsize; // sizeof(struct _objc_method)
3493 // uint32_t method_count;
3494 // struct _objc_method method_list[method_count];
3495 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003496 MethodListnfABITy = llvm::StructType::get(IntTy,
3497 IntTy,
3498 llvm::ArrayType::get(MethodTy, 0),
3499 NULL);
3500 CGM.getModule().addTypeName("struct.__method_list_t",
3501 MethodListnfABITy);
3502 // struct method_list_t *
3503 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003504
3505 // struct _protocol_t {
3506 // id isa; // NULL
3507 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003508 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003509 // const struct method_list_t * const instance_methods;
3510 // const struct method_list_t * const class_methods;
3511 // const struct method_list_t *optionalInstanceMethods;
3512 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003513 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003514 // const uint32_t size; // sizeof(struct _protocol_t)
3515 // const uint32_t flags; // = 0
3516 // }
3517
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003518 // Holder for struct _protocol_list_t *
3519 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3520
3521 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3522 Int8PtrTy,
3523 llvm::PointerType::getUnqual(
3524 ProtocolListTyHolder),
3525 MethodListnfABIPtrTy,
3526 MethodListnfABIPtrTy,
3527 MethodListnfABIPtrTy,
3528 MethodListnfABIPtrTy,
3529 PropertyListPtrTy,
3530 IntTy,
3531 IntTy,
3532 NULL);
3533 CGM.getModule().addTypeName("struct._protocol_t",
3534 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003535
3536 // struct _protocol_t*
3537 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003538
Fariborz Jahanianda320092009-01-29 19:24:30 +00003539 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003540 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003541 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003542 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003543 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3544 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003545 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003546 NULL);
3547 CGM.getModule().addTypeName("struct._objc_protocol_list",
3548 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003549 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3550 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003551
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003552 // struct _objc_protocol_list*
3553 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003554
3555 // struct _ivar_t {
3556 // unsigned long int *offset; // pointer to ivar offset location
3557 // char *name;
3558 // char *type;
3559 // uint32_t alignment;
3560 // uint32_t size;
3561 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003562 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3563 Int8PtrTy,
3564 Int8PtrTy,
3565 IntTy,
3566 IntTy,
3567 NULL);
3568 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3569
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003570 // struct _ivar_list_t {
3571 // uint32 entsize; // sizeof(struct _ivar_t)
3572 // uint32 count;
3573 // struct _iver_t list[count];
3574 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003575 IvarListnfABITy = llvm::StructType::get(IntTy,
3576 IntTy,
3577 llvm::ArrayType::get(
3578 IvarnfABITy, 0),
3579 NULL);
3580 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3581
3582 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003583
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003584 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003585 // uint32_t const flags;
3586 // uint32_t const instanceStart;
3587 // uint32_t const instanceSize;
3588 // uint32_t const reserved; // only when building for 64bit targets
3589 // const uint8_t * const ivarLayout;
3590 // const char *const name;
3591 // const struct _method_list_t * const baseMethods;
3592 // const struct _objc_protocol_list *const baseProtocols;
3593 // const struct _ivar_list_t *const ivars;
3594 // const uint8_t * const weakIvarLayout;
3595 // const struct _prop_list_t * const properties;
3596 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003597
3598 // FIXME. Add 'reserved' field in 64bit abi mode!
3599 ClassRonfABITy = llvm::StructType::get(IntTy,
3600 IntTy,
3601 IntTy,
3602 Int8PtrTy,
3603 Int8PtrTy,
3604 MethodListnfABIPtrTy,
3605 ProtocolListnfABIPtrTy,
3606 IvarListnfABIPtrTy,
3607 Int8PtrTy,
3608 PropertyListPtrTy,
3609 NULL);
3610 CGM.getModule().addTypeName("struct._class_ro_t",
3611 ClassRonfABITy);
3612
3613 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3614 std::vector<const llvm::Type*> Params;
3615 Params.push_back(ObjectPtrTy);
3616 Params.push_back(SelectorPtrTy);
3617 ImpnfABITy = llvm::PointerType::getUnqual(
3618 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3619
3620 // struct _class_t {
3621 // struct _class_t *isa;
3622 // struct _class_t * const superclass;
3623 // void *cache;
3624 // IMP *vtable;
3625 // struct class_ro_t *ro;
3626 // }
3627
3628 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3629 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3630 llvm::PointerType::getUnqual(ClassTyHolder),
3631 CachePtrTy,
3632 llvm::PointerType::getUnqual(ImpnfABITy),
3633 llvm::PointerType::getUnqual(
3634 ClassRonfABITy),
3635 NULL);
3636 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3637
3638 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3639 ClassnfABITy);
3640
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003641 // LLVM for struct _class_t *
3642 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3643
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003644 // struct _category_t {
3645 // const char * const name;
3646 // struct _class_t *const cls;
3647 // const struct _method_list_t * const instance_methods;
3648 // const struct _method_list_t * const class_methods;
3649 // const struct _protocol_list_t * const protocols;
3650 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003651 // }
3652 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003653 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003654 MethodListnfABIPtrTy,
3655 MethodListnfABIPtrTy,
3656 ProtocolListnfABIPtrTy,
3657 PropertyListPtrTy,
3658 NULL);
3659 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003660
3661 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003662 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3663 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003664
3665 // MessageRefTy - LLVM for:
3666 // struct _message_ref_t {
3667 // IMP messenger;
3668 // SEL name;
3669 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003670
3671 // First the clang type for struct _message_ref_t
3672 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3673 SourceLocation(),
3674 &Ctx.Idents.get("_message_ref_t"));
3675 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3676 Ctx.VoidPtrTy, 0, false));
3677 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3678 Ctx.getObjCSelType(), 0, false));
3679 RD->completeDefinition(Ctx);
3680
3681 MessageRefCTy = Ctx.getTagDeclType(RD);
3682 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3683 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003684
3685 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3686 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3687
3688 // SuperMessageRefTy - LLVM for:
3689 // struct _super_message_ref_t {
3690 // SUPER_IMP messenger;
3691 // SEL name;
3692 // };
3693 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3694 SelectorPtrTy,
3695 NULL);
3696 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3697
3698 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3699 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3700
3701 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3702 Params.clear();
3703 Params.push_back(ObjectPtrTy);
3704 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003705 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3706 Params,
3707 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003708 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003709 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003710 "objc_msgSend_fixup");
3711
3712 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3713 MessageSendFpretFixupFn =
3714 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3715 Params,
3716 true),
3717 "objc_msgSend_fpret_fixup");
3718
3719 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3720 MessageSendStretFixupFn =
3721 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3722 Params,
3723 true),
3724 "objc_msgSend_stret_fixup");
3725
3726 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3727 MessageSendIdFixupFn =
3728 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3729 Params,
3730 true),
3731 "objc_msgSendId_fixup");
3732
3733
3734 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3735 MessageSendIdStretFixupFn =
3736 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3737 Params,
3738 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003739 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003740
3741 // id objc_msgSendSuper2_fixup (struct objc_super *,
3742 // struct _super_message_ref_t*, ...)
3743 Params.clear();
3744 Params.push_back(SuperPtrTy);
3745 Params.push_back(SuperMessageRefPtrTy);
3746 MessageSendSuper2FixupFn =
3747 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3748 Params,
3749 true),
3750 "objc_msgSendSuper2_fixup");
3751
3752
3753 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3754 // struct _super_message_ref_t*, ...)
3755 MessageSendSuper2StretFixupFn =
3756 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3757 Params,
3758 true),
3759 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003760
3761 Params.clear();
3762 llvm::Constant *Personality =
3763 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3764 Params,
3765 true),
3766 "__objc_personality_v0");
3767 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3768
3769 Params.clear();
3770 Params.push_back(Int8PtrTy);
3771 UnwindResumeOrRethrowFn =
3772 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3773 Params,
3774 false),
3775 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003776 ObjCBeginCatchFn =
3777 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3778 Params,
3779 false),
3780 "objc_begin_catch");
3781
3782 Params.clear();
3783 ObjCEndCatchFn =
3784 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3785 Params,
3786 false),
3787 "objc_end_catch");
3788
3789 // struct objc_typeinfo {
3790 // const void** vtable; // objc_ehtype_vtable + 2
3791 // const char* name; // c++ typeinfo string
3792 // Class cls;
3793 // };
3794 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3795 Int8PtrTy,
3796 ClassnfABIPtrTy,
3797 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003798 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003799 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003800}
3801
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003802llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3803 FinishNonFragileABIModule();
3804
3805 return NULL;
3806}
3807
3808void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3809 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003810
3811 // Build list of all implemented classe addresses in array
3812 // L_OBJC_LABEL_CLASS_$.
3813 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3814 // list of 'nonlazy' implementations (defined as those with a +load{}
3815 // method!!).
3816 unsigned NumClasses = DefinedClasses.size();
3817 if (NumClasses) {
3818 std::vector<llvm::Constant*> Symbols(NumClasses);
3819 for (unsigned i=0; i<NumClasses; i++)
3820 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3821 ObjCTypes.Int8PtrTy);
3822 llvm::Constant* Init =
3823 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3824 NumClasses),
3825 Symbols);
3826
3827 llvm::GlobalVariable *GV =
3828 new llvm::GlobalVariable(Init->getType(), false,
3829 llvm::GlobalValue::InternalLinkage,
3830 Init,
3831 "\01L_OBJC_LABEL_CLASS_$",
3832 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003833 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003834 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3835 UsedGlobals.push_back(GV);
3836 }
3837
3838 // Build list of all implemented category addresses in array
3839 // L_OBJC_LABEL_CATEGORY_$.
3840 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3841 // list of 'nonlazy' category implementations (defined as those with a +load{}
3842 // method!!).
3843 unsigned NumCategory = DefinedCategories.size();
3844 if (NumCategory) {
3845 std::vector<llvm::Constant*> Symbols(NumCategory);
3846 for (unsigned i=0; i<NumCategory; i++)
3847 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3848 ObjCTypes.Int8PtrTy);
3849 llvm::Constant* Init =
3850 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3851 NumCategory),
3852 Symbols);
3853
3854 llvm::GlobalVariable *GV =
3855 new llvm::GlobalVariable(Init->getType(), false,
3856 llvm::GlobalValue::InternalLinkage,
3857 Init,
3858 "\01L_OBJC_LABEL_CATEGORY_$",
3859 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003860 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003861 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3862 UsedGlobals.push_back(GV);
3863 }
3864
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003865 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3866 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3867 std::vector<llvm::Constant*> Values(2);
3868 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003869 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003870 // FIXME: Fix and continue?
3871 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3872 flags |= eImageInfo_GarbageCollected;
3873 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3874 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003875 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003876 llvm::Constant* Init = llvm::ConstantArray::get(
3877 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3878 Values);
3879 llvm::GlobalVariable *IMGV =
3880 new llvm::GlobalVariable(Init->getType(), false,
3881 llvm::GlobalValue::InternalLinkage,
3882 Init,
3883 "\01L_OBJC_IMAGE_INFO",
3884 &CGM.getModule());
3885 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3886 UsedGlobals.push_back(IMGV);
3887
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003888 std::vector<llvm::Constant*> Used;
3889 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3890 e = UsedGlobals.end(); i != e; ++i) {
3891 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3892 }
3893
3894 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3895 llvm::GlobalValue *GV =
3896 new llvm::GlobalVariable(AT, false,
3897 llvm::GlobalValue::AppendingLinkage,
3898 llvm::ConstantArray::get(AT, Used),
3899 "llvm.used",
3900 &CGM.getModule());
3901
3902 GV->setSection("llvm.metadata");
3903
3904}
3905
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003906// Metadata flags
3907enum MetaDataDlags {
3908 CLS = 0x0,
3909 CLS_META = 0x1,
3910 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003911 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003912 CLS_EXCEPTION = 0x20
3913};
3914/// BuildClassRoTInitializer - generate meta-data for:
3915/// struct _class_ro_t {
3916/// uint32_t const flags;
3917/// uint32_t const instanceStart;
3918/// uint32_t const instanceSize;
3919/// uint32_t const reserved; // only when building for 64bit targets
3920/// const uint8_t * const ivarLayout;
3921/// const char *const name;
3922/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003923/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003924/// const struct _ivar_list_t *const ivars;
3925/// const uint8_t * const weakIvarLayout;
3926/// const struct _prop_list_t * const properties;
3927/// }
3928///
3929llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3930 unsigned flags,
3931 unsigned InstanceStart,
3932 unsigned InstanceSize,
3933 const ObjCImplementationDecl *ID) {
3934 std::string ClassName = ID->getNameAsString();
3935 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3936 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3937 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3938 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3939 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003940 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003941 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003942 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003943 // const struct _method_list_t * const baseMethods;
3944 std::vector<llvm::Constant*> Methods;
3945 std::string MethodListName("\01l_OBJC_$_");
3946 if (flags & CLS_META) {
3947 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3948 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3949 e = ID->classmeth_end(); i != e; ++i) {
3950 // Class methods should always be defined.
3951 Methods.push_back(GetMethodConstant(*i));
3952 }
3953 } else {
3954 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3955 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3956 e = ID->instmeth_end(); i != e; ++i) {
3957 // Instance methods should always be defined.
3958 Methods.push_back(GetMethodConstant(*i));
3959 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003960 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3961 e = ID->propimpl_end(); i != e; ++i) {
3962 ObjCPropertyImplDecl *PID = *i;
3963
3964 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3965 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3966
3967 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3968 if (llvm::Constant *C = GetMethodConstant(MD))
3969 Methods.push_back(C);
3970 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3971 if (llvm::Constant *C = GetMethodConstant(MD))
3972 Methods.push_back(C);
3973 }
3974 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003975 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003976 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003977 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003978
3979 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3980 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3981 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3982 + OID->getNameAsString(),
3983 OID->protocol_begin(),
3984 OID->protocol_end());
3985
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003986 if (flags & CLS_META)
3987 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3988 else
3989 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003990 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003991 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003992 if (flags & CLS_META)
3993 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3994 else
3995 Values[ 9] =
3996 EmitPropertyList(
3997 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3998 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003999 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4000 Values);
4001 llvm::GlobalVariable *CLASS_RO_GV =
4002 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4003 llvm::GlobalValue::InternalLinkage,
4004 Init,
4005 (flags & CLS_META) ?
4006 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4007 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4008 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004009 CLASS_RO_GV->setAlignment(
4010 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004011 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004012 UsedGlobals.push_back(CLASS_RO_GV);
4013 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004014
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004015}
4016
4017/// BuildClassMetaData - This routine defines that to-level meta-data
4018/// for the given ClassName for:
4019/// struct _class_t {
4020/// struct _class_t *isa;
4021/// struct _class_t * const superclass;
4022/// void *cache;
4023/// IMP *vtable;
4024/// struct class_ro_t *ro;
4025/// }
4026///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004027llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4028 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004029 llvm::Constant *IsAGV,
4030 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004031 llvm::Constant *ClassRoGV,
4032 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004033 std::vector<llvm::Constant*> Values(5);
4034 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004035 Values[1] = SuperClassGV
4036 ? SuperClassGV
4037 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004038 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4039 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4040 Values[4] = ClassRoGV; // &CLASS_RO_GV
4041 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4042 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004043 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4044 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004045 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004046 GV->setAlignment(
4047 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004048 if (HiddenVisibility)
4049 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004050 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004051 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004052}
4053
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004054void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4055 std::string ClassName = ID->getNameAsString();
4056 if (!ObjCEmptyCacheVar) {
4057 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004058 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004059 false,
4060 llvm::GlobalValue::ExternalLinkage,
4061 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004062 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004063 &CGM.getModule());
4064 UsedGlobals.push_back(ObjCEmptyCacheVar);
4065
4066 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004067 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004068 false,
4069 llvm::GlobalValue::ExternalLinkage,
4070 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004071 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004072 &CGM.getModule());
4073 UsedGlobals.push_back(ObjCEmptyVtableVar);
4074 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004075 assert(ID->getClassInterface() &&
4076 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004077 uint32_t InstanceStart =
4078 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4079 uint32_t InstanceSize = InstanceStart;
4080 uint32_t flags = CLS_META;
4081 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
4082 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004083
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004084 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004085
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004086 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4087 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004088 flags |= OBJC2_CLS_HIDDEN;
4089 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004090 // class is root
4091 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004092 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4093 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004094 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004095 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004096 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4097 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4098 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004099 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004100 // work on super class metadata symbol.
4101 std::string SuperClassName =
4102 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004103 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004104 }
4105 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4106 InstanceStart,
4107 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004108 std::string TClassName = ObjCMetaClassName + ClassName;
4109 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004110 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4111 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004112
4113 // Metadata for the class
4114 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004115 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004116 flags |= OBJC2_CLS_HIDDEN;
4117 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004118 flags |= CLS_ROOT;
4119 SuperClassGV = 0;
4120 }
4121 else {
4122 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004123 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004124 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004125 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004126 }
4127
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004128 InstanceStart = InstanceSize = 0;
4129 if (ObjCInterfaceDecl *OID =
4130 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4131 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004132 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00004133 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004134 const llvm::StructLayout *Layout =
4135 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004136
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004137 RecordDecl::field_iterator firstField, lastField;
4138 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004139
4140 for (RecordDecl::field_iterator e = RD->field_end(),
4141 ifield = firstField; ifield != e; ++ifield)
4142 lastField = ifield;
4143
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004144 if (lastField != RD->field_end()) {
4145 FieldDecl *Field = *lastField;
4146 const llvm::Type *FieldTy =
4147 CGM.getTypes().ConvertTypeForMem(Field->getType());
4148 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004149 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004150 if (firstField == RD->field_end())
4151 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004152 else {
4153 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004154 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004155 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004156 }
4157 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004158 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004159 InstanceStart,
4160 InstanceSize,
4161 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004162
4163 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004164 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004165 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4166 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004167 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004168}
4169
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004170/// GenerateProtocolRef - This routine is called to generate code for
4171/// a protocol reference expression; as in:
4172/// @code
4173/// @protocol(Proto1);
4174/// @endcode
4175/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4176/// which will hold address of the protocol meta-data.
4177///
4178llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4179 const ObjCProtocolDecl *PD) {
4180
4181 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4182 ObjCTypes.ExternalProtocolPtrTy);
4183
4184 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4185 ProtocolName += PD->getNameAsCString();
4186
4187 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4188 if (PTGV)
4189 return Builder.CreateLoad(PTGV, false, "tmp");
4190 PTGV = new llvm::GlobalVariable(
4191 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004192 // FIXME: review, was WeakLinkage,
4193 // also review all other WeakLinkage changes
4194 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004195 Init,
4196 ProtocolName,
4197 &CGM.getModule());
4198 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4199 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4200 UsedGlobals.push_back(PTGV);
4201 return Builder.CreateLoad(PTGV, false, "tmp");
4202}
4203
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004204/// GenerateCategory - Build metadata for a category implementation.
4205/// struct _category_t {
4206/// const char * const name;
4207/// struct _class_t *const cls;
4208/// const struct _method_list_t * const instance_methods;
4209/// const struct _method_list_t * const class_methods;
4210/// const struct _protocol_list_t * const protocols;
4211/// const struct _prop_list_t * const properties;
4212/// }
4213///
4214void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4215{
4216 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004217 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4218 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004219 "_$_" + OCD->getNameAsString());
4220 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
4221
4222 std::vector<llvm::Constant*> Values(6);
4223 Values[0] = GetClassName(OCD->getIdentifier());
4224 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004225 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004226 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004227 std::vector<llvm::Constant*> Methods;
4228 std::string MethodListName(Prefix);
4229 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4230 "_$_" + OCD->getNameAsString();
4231
4232 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4233 e = OCD->instmeth_end(); i != e; ++i) {
4234 // Instance methods should always be defined.
4235 Methods.push_back(GetMethodConstant(*i));
4236 }
4237
4238 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004239 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004240 Methods);
4241
4242 MethodListName = Prefix;
4243 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4244 OCD->getNameAsString();
4245 Methods.clear();
4246 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4247 e = OCD->classmeth_end(); i != e; ++i) {
4248 // Class methods should always be defined.
4249 Methods.push_back(GetMethodConstant(*i));
4250 }
4251
4252 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004253 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004254 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004255 const ObjCCategoryDecl *Category =
4256 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004257 if (Category) {
4258 std::string ExtName(Interface->getNameAsString() + "_$_" +
4259 OCD->getNameAsString());
4260 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4261 + Interface->getNameAsString() + "_$_"
4262 + Category->getNameAsString(),
4263 Category->protocol_begin(),
4264 Category->protocol_end());
4265 Values[5] =
4266 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4267 OCD, Category, ObjCTypes);
4268 }
4269 else {
4270 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4271 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4272 }
4273
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004274 llvm::Constant *Init =
4275 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4276 Values);
4277 llvm::GlobalVariable *GCATV
4278 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4279 false,
4280 llvm::GlobalValue::InternalLinkage,
4281 Init,
4282 ExtCatName,
4283 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004284 GCATV->setAlignment(
4285 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004286 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004287 UsedGlobals.push_back(GCATV);
4288 DefinedCategories.push_back(GCATV);
4289}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004290
4291/// GetMethodConstant - Return a struct objc_method constant for the
4292/// given method if it has been defined. The result is null if the
4293/// method has not been defined. The return value has type MethodPtrTy.
4294llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4295 const ObjCMethodDecl *MD) {
4296 // FIXME: Use DenseMap::lookup
4297 llvm::Function *Fn = MethodDefinitions[MD];
4298 if (!Fn)
4299 return 0;
4300
4301 std::vector<llvm::Constant*> Method(3);
4302 Method[0] =
4303 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4304 ObjCTypes.SelectorPtrTy);
4305 Method[1] = GetMethodVarType(MD);
4306 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4307 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4308}
4309
4310/// EmitMethodList - Build meta-data for method declarations
4311/// struct _method_list_t {
4312/// uint32_t entsize; // sizeof(struct _objc_method)
4313/// uint32_t method_count;
4314/// struct _objc_method method_list[method_count];
4315/// }
4316///
4317llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4318 const std::string &Name,
4319 const char *Section,
4320 const ConstantVector &Methods) {
4321 // Return null for empty list.
4322 if (Methods.empty())
4323 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4324
4325 std::vector<llvm::Constant*> Values(3);
4326 // sizeof(struct _objc_method)
4327 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4328 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4329 // method_count
4330 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4331 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4332 Methods.size());
4333 Values[2] = llvm::ConstantArray::get(AT, Methods);
4334 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4335
4336 llvm::GlobalVariable *GV =
4337 new llvm::GlobalVariable(Init->getType(), false,
4338 llvm::GlobalValue::InternalLinkage,
4339 Init,
4340 Name,
4341 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004342 GV->setAlignment(
4343 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004344 GV->setSection(Section);
4345 UsedGlobals.push_back(GV);
4346 return llvm::ConstantExpr::getBitCast(GV,
4347 ObjCTypes.MethodListnfABIPtrTy);
4348}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004349
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004350/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4351/// the given ivar.
4352///
4353llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4354 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004355 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004356 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004357 Name += "\01_OBJC_IVAR_$_" +
4358 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004359 + Ivar->getNameAsString();
4360 llvm::GlobalVariable *IvarOffsetGV =
4361 CGM.getModule().getGlobalVariable(Name);
4362 if (!IvarOffsetGV)
4363 IvarOffsetGV =
4364 new llvm::GlobalVariable(ObjCTypes.LongTy,
4365 false,
4366 llvm::GlobalValue::ExternalLinkage,
4367 0,
4368 Name,
4369 &CGM.getModule());
4370 return IvarOffsetGV;
4371}
4372
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004373llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004374 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004375 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004376 unsigned long int Offset) {
4377
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004378 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004379 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004380 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004381 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004382
4383 llvm::GlobalVariable *IvarOffsetGV =
4384 CGM.getModule().getGlobalVariable(ExternalName);
4385 if (IvarOffsetGV) {
4386 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004387 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004388 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004389 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004390 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004391 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004392 return IvarOffsetGV;
4393 }
4394
4395 IvarOffsetGV =
4396 new llvm::GlobalVariable(Init->getType(),
4397 false,
4398 llvm::GlobalValue::ExternalLinkage,
4399 Init,
4400 ExternalName,
4401 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004402 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004403 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004404 // @private and @package have hidden visibility.
4405 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4406 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4407 if (!globalVisibility)
4408 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004409 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004410 if (IsClassHidden(ID))
4411 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004412
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004413 IvarOffsetGV->setSection("__DATA, __objc_const");
4414 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004415 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004416}
4417
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004418/// EmitIvarList - Emit the ivar list for the given
4419/// implementation. If ForClass is true the list of class ivars
4420/// (i.e. metaclass ivars) is emitted, otherwise the list of
4421/// interface ivars will be emitted. The return value has type
4422/// IvarListnfABIPtrTy.
4423/// struct _ivar_t {
4424/// unsigned long int *offset; // pointer to ivar offset location
4425/// char *name;
4426/// char *type;
4427/// uint32_t alignment;
4428/// uint32_t size;
4429/// }
4430/// struct _ivar_list_t {
4431/// uint32 entsize; // sizeof(struct _ivar_t)
4432/// uint32 count;
4433/// struct _iver_t list[count];
4434/// }
4435///
4436llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4437 const ObjCImplementationDecl *ID) {
4438
4439 std::vector<llvm::Constant*> Ivars, Ivar(5);
4440
4441 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4442 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4443
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004444 // FIXME. Consolidate this with similar code in GenerateClass.
4445 const llvm::Type *InterfaceTy =
4446 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4447 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004448 const llvm::StructLayout *Layout =
4449 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004450
4451 RecordDecl::field_iterator i,p;
4452 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004453 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4454
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004455 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004456 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004457 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004458 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004459 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004460 if (Field->getIdentifier())
4461 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4462 else
4463 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004464 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004465 const llvm::Type *FieldTy =
4466 CGM.getTypes().ConvertTypeForMem(Field->getType());
4467 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4468 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4469 Field->getType().getTypePtr()) >> 3;
4470 Align = llvm::Log2_32(Align);
4471 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004472 // NOTE. Size of a bitfield does not match gcc's, because of the way
4473 // bitfields are treated special in each. But I am told that 'size'
4474 // for bitfield ivars is ignored by the runtime so it does not matter.
4475 // (even if it matters, some day, there is enough info. to get the bitfield
4476 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004477 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4478 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4479 }
4480 // Return null for empty list.
4481 if (Ivars.empty())
4482 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4483 std::vector<llvm::Constant*> Values(3);
4484 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4485 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4486 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4487 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4488 Ivars.size());
4489 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4490 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4491 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4492 llvm::GlobalVariable *GV =
4493 new llvm::GlobalVariable(Init->getType(), false,
4494 llvm::GlobalValue::InternalLinkage,
4495 Init,
4496 Prefix + OID->getNameAsString(),
4497 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004498 GV->setAlignment(
4499 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004500 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004501
4502 UsedGlobals.push_back(GV);
4503 return llvm::ConstantExpr::getBitCast(GV,
4504 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004505}
4506
4507llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4508 const ObjCProtocolDecl *PD) {
4509 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4510
4511 if (!Entry) {
4512 // We use the initializer as a marker of whether this is a forward
4513 // reference or not. At module finalization we add the empty
4514 // contents for protocols which were referenced but never defined.
4515 Entry =
4516 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4517 llvm::GlobalValue::ExternalLinkage,
4518 0,
4519 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4520 &CGM.getModule());
4521 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4522 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004523 }
4524
4525 return Entry;
4526}
4527
4528/// GetOrEmitProtocol - Generate the protocol meta-data:
4529/// @code
4530/// struct _protocol_t {
4531/// id isa; // NULL
4532/// const char * const protocol_name;
4533/// const struct _protocol_list_t * protocol_list; // super protocols
4534/// const struct method_list_t * const instance_methods;
4535/// const struct method_list_t * const class_methods;
4536/// const struct method_list_t *optionalInstanceMethods;
4537/// const struct method_list_t *optionalClassMethods;
4538/// const struct _prop_list_t * properties;
4539/// const uint32_t size; // sizeof(struct _protocol_t)
4540/// const uint32_t flags; // = 0
4541/// }
4542/// @endcode
4543///
4544
4545llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4546 const ObjCProtocolDecl *PD) {
4547 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4548
4549 // Early exit if a defining object has already been generated.
4550 if (Entry && Entry->hasInitializer())
4551 return Entry;
4552
4553 const char *ProtocolName = PD->getNameAsCString();
4554
4555 // Construct method lists.
4556 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4557 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4558 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4559 e = PD->instmeth_end(); i != e; ++i) {
4560 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004561 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004562 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4563 OptInstanceMethods.push_back(C);
4564 } else {
4565 InstanceMethods.push_back(C);
4566 }
4567 }
4568
4569 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4570 e = PD->classmeth_end(); i != e; ++i) {
4571 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004572 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004573 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4574 OptClassMethods.push_back(C);
4575 } else {
4576 ClassMethods.push_back(C);
4577 }
4578 }
4579
4580 std::vector<llvm::Constant*> Values(10);
4581 // isa is NULL
4582 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4583 Values[1] = GetClassName(PD->getIdentifier());
4584 Values[2] = EmitProtocolList(
4585 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4586 PD->protocol_begin(),
4587 PD->protocol_end());
4588
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004589 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004590 + PD->getNameAsString(),
4591 "__DATA, __objc_const",
4592 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004593 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004594 + PD->getNameAsString(),
4595 "__DATA, __objc_const",
4596 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004597 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004598 + PD->getNameAsString(),
4599 "__DATA, __objc_const",
4600 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004601 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004602 + PD->getNameAsString(),
4603 "__DATA, __objc_const",
4604 OptClassMethods);
4605 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4606 0, PD, ObjCTypes);
4607 uint32_t Size =
4608 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4609 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4610 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4611 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4612 Values);
4613
4614 if (Entry) {
4615 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004616 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004617 Entry->setInitializer(Init);
4618 } else {
4619 Entry =
4620 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004621 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004622 Init,
4623 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4624 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004625 Entry->setAlignment(
4626 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004627 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004628 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004629 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4630
4631 // Use this protocol meta-data to build protocol list table in section
4632 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004633 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004634 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004635 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004636 Entry,
4637 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4638 +ProtocolName,
4639 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004640 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004641 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004642 PTGV->setSection("__DATA, __objc_protolist");
4643 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4644 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004645 return Entry;
4646}
4647
4648/// EmitProtocolList - Generate protocol list meta-data:
4649/// @code
4650/// struct _protocol_list_t {
4651/// long protocol_count; // Note, this is 32/64 bit
4652/// struct _protocol_t[protocol_count];
4653/// }
4654/// @endcode
4655///
4656llvm::Constant *
4657CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4658 ObjCProtocolDecl::protocol_iterator begin,
4659 ObjCProtocolDecl::protocol_iterator end) {
4660 std::vector<llvm::Constant*> ProtocolRefs;
4661
Fariborz Jahanianda320092009-01-29 19:24:30 +00004662 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004663 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004664 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4665
Daniel Dunbar948e2582009-02-15 07:36:20 +00004666 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004667 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4668 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004669 return llvm::ConstantExpr::getBitCast(GV,
4670 ObjCTypes.ProtocolListnfABIPtrTy);
4671
4672 for (; begin != end; ++begin)
4673 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4674
Fariborz Jahanianda320092009-01-29 19:24:30 +00004675 // This list is null terminated.
4676 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004677 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004678
4679 std::vector<llvm::Constant*> Values(2);
4680 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4681 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004682 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004683 ProtocolRefs.size()),
4684 ProtocolRefs);
4685
4686 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4687 GV = new llvm::GlobalVariable(Init->getType(), false,
4688 llvm::GlobalValue::InternalLinkage,
4689 Init,
4690 Name,
4691 &CGM.getModule());
4692 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004693 GV->setAlignment(
4694 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004695 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004696 return llvm::ConstantExpr::getBitCast(GV,
4697 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004698}
4699
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004700/// GetMethodDescriptionConstant - This routine build following meta-data:
4701/// struct _objc_method {
4702/// SEL _cmd;
4703/// char *method_type;
4704/// char *_imp;
4705/// }
4706
4707llvm::Constant *
4708CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4709 std::vector<llvm::Constant*> Desc(3);
4710 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4711 ObjCTypes.SelectorPtrTy);
4712 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004713 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004714 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4715 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4716}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004717
4718/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4719/// This code gen. amounts to generating code for:
4720/// @code
4721/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4722/// @encode
4723///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004724LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004725 CodeGen::CodeGenFunction &CGF,
4726 QualType ObjectTy,
4727 llvm::Value *BaseValue,
4728 const ObjCIvarDecl *Ivar,
4729 const FieldDecl *Field,
4730 unsigned CVRQualifiers) {
4731 assert(ObjectTy->isObjCInterfaceType() &&
4732 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004733 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004734 std::string ExternalName;
4735 llvm::GlobalVariable *IvarOffsetGV =
4736 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004737
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004738 // (char *) BaseValue
4739 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4740 ObjCTypes.Int8PtrTy);
4741 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4742 // (char*)BaseValue + Offset_symbol
4743 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4744 // (type *)((char*)BaseValue + Offset_symbol)
4745 const llvm::Type *IvarTy =
4746 CGM.getTypes().ConvertType(Ivar->getType());
4747 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4748 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004749
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004750 if (Ivar->isBitField()) {
4751 CodeGenTypes::BitFieldInfo bitFieldInfo =
4752 CGM.getTypes().getBitFieldInfo(Field);
4753 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4754 Field->getType()->isSignedIntegerType(),
4755 Field->getType().getCVRQualifiers()|CVRQualifiers);
4756 }
4757
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004758 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004759 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4760 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004761 LValue::SetObjCIvar(LV, true);
4762 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004763}
4764
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004765llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4766 CodeGen::CodeGenFunction &CGF,
4767 ObjCInterfaceDecl *Interface,
4768 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004769 std::string ExternalName;
4770 llvm::GlobalVariable *IvarOffsetGV =
4771 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4772
4773 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004774}
4775
Fariborz Jahanian46551122009-02-04 00:22:57 +00004776CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4777 CodeGen::CodeGenFunction &CGF,
4778 QualType ResultType,
4779 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004780 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004781 QualType Arg0Ty,
4782 bool IsSuper,
4783 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004784 // FIXME. Even though IsSuper is passes. This function doese not
4785 // handle calls to 'super' receivers.
4786 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004787 llvm::Value *Arg0 = Receiver;
4788 if (!IsSuper)
4789 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004790
4791 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004792 // FIXME. This is too much work to get the ABI-specific result type
4793 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004794 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4795 llvm::SmallVector<QualType, 16>());
4796 llvm::Constant *Fn;
4797 std::string Name("\01l_");
4798 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004799#if 0
4800 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004801 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4802 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4803 // FIXME. Is there a better way of getting these names.
4804 // They are available in RuntimeFunctions vector pair.
4805 Name += "objc_msgSendId_stret_fixup";
4806 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004807 else
4808#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004809 if (IsSuper) {
4810 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4811 Name += "objc_msgSendSuper2_stret_fixup";
4812 }
4813 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004814 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004815 Fn = ObjCTypes.MessageSendStretFixupFn;
4816 Name += "objc_msgSend_stret_fixup";
4817 }
4818 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004819 else if (ResultType->isFloatingType() &&
4820 // Selection of frret API only happens in 32bit nonfragile ABI.
4821 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004822 Fn = ObjCTypes.MessageSendFpretFixupFn;
4823 Name += "objc_msgSend_fpret_fixup";
4824 }
4825 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004826#if 0
4827// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004828 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4829 Fn = ObjCTypes.MessageSendIdFixupFn;
4830 Name += "objc_msgSendId_fixup";
4831 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004832 else
4833#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004834 if (IsSuper) {
4835 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4836 Name += "objc_msgSendSuper2_fixup";
4837 }
4838 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004839 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004840 Fn = ObjCTypes.MessageSendFixupFn;
4841 Name += "objc_msgSend_fixup";
4842 }
4843 }
4844 Name += '_';
4845 std::string SelName(Sel.getAsString());
4846 // Replace all ':' in selector name with '_' ouch!
4847 for(unsigned i = 0; i < SelName.size(); i++)
4848 if (SelName[i] == ':')
4849 SelName[i] = '_';
4850 Name += SelName;
4851 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4852 if (!GV) {
4853 // Build messafe ref table entry.
4854 std::vector<llvm::Constant*> Values(2);
4855 Values[0] = Fn;
4856 Values[1] = GetMethodVarName(Sel);
4857 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4858 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004859 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004860 Init,
4861 Name,
4862 &CGM.getModule());
4863 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4864 GV->setAlignment(
4865 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4866 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4867 UsedGlobals.push_back(GV);
4868 }
4869 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004870
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004871 CallArgList ActualArgs;
4872 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4873 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4874 ObjCTypes.MessageRefCPtrTy));
4875 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004876 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4877 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4878 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004879 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004880 Callee = CGF.Builder.CreateBitCast(Callee,
4881 llvm::PointerType::getUnqual(FTy));
4882 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004883}
4884
4885/// Generate code for a message send expression in the nonfragile abi.
4886CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4887 CodeGen::CodeGenFunction &CGF,
4888 QualType ResultType,
4889 Selector Sel,
4890 llvm::Value *Receiver,
4891 bool IsClassMessage,
4892 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004893 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004894 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004895 false, CallArgs);
4896}
4897
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004898llvm::GlobalVariable *
4899CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4900 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4901
Daniel Dunbardfff2302009-03-02 05:18:14 +00004902 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004903 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4904 llvm::GlobalValue::ExternalLinkage,
4905 0, Name, &CGM.getModule());
4906 UsedGlobals.push_back(GV);
4907 }
4908
4909 return GV;
4910}
4911
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004912llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004913 const ObjCInterfaceDecl *ID,
4914 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004915
4916 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4917
4918 if (!Entry) {
4919 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004920 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004921 Entry =
4922 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4923 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004924 ClassGV,
4925 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4926 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004927 &CGM.getModule());
4928 Entry->setAlignment(
4929 CGM.getTargetData().getPrefTypeAlignment(
4930 ObjCTypes.ClassnfABIPtrTy));
4931
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004932 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004933 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004934 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004935 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004936 UsedGlobals.push_back(Entry);
4937 }
4938
4939 return Builder.CreateLoad(Entry, false, "tmp");
4940}
4941
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004942/// EmitMetaClassRef - Return a Value * of the address of _class_t
4943/// meta-data
4944///
4945llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4946 const ObjCInterfaceDecl *ID) {
4947 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4948 if (Entry)
4949 return Builder.CreateLoad(Entry, false, "tmp");
4950
4951 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004952 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004953 Entry =
4954 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4955 llvm::GlobalValue::InternalLinkage,
4956 MetaClassGV,
4957 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4958 &CGM.getModule());
4959 Entry->setAlignment(
4960 CGM.getTargetData().getPrefTypeAlignment(
4961 ObjCTypes.ClassnfABIPtrTy));
4962
4963 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4964 UsedGlobals.push_back(Entry);
4965
4966 return Builder.CreateLoad(Entry, false, "tmp");
4967}
4968
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004969/// GetClass - Return a reference to the class for the given interface
4970/// decl.
4971llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4972 const ObjCInterfaceDecl *ID) {
4973 return EmitClassRef(Builder, ID);
4974}
4975
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004976/// Generates a message send where the super is the receiver. This is
4977/// a message send to self with special delivery semantics indicating
4978/// which class's method should be called.
4979CodeGen::RValue
4980CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4981 QualType ResultType,
4982 Selector Sel,
4983 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004984 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004985 llvm::Value *Receiver,
4986 bool IsClassMessage,
4987 const CodeGen::CallArgList &CallArgs) {
4988 // ...
4989 // Create and init a super structure; this is a (receiver, class)
4990 // pair we will pass to objc_msgSendSuper.
4991 llvm::Value *ObjCSuper =
4992 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4993
4994 llvm::Value *ReceiverAsObject =
4995 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4996 CGF.Builder.CreateStore(ReceiverAsObject,
4997 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4998
4999 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005000 llvm::Value *Target;
5001 if (IsClassMessage) {
5002 if (isCategoryImpl) {
5003 // Message sent to "super' in a class method defined in
5004 // a category implementation.
5005 Target = EmitClassRef(CGF.Builder, Class, false);
5006 Target = CGF.Builder.CreateStructGEP(Target, 0);
5007 Target = CGF.Builder.CreateLoad(Target);
5008 }
5009 else
5010 Target = EmitMetaClassRef(CGF.Builder, Class);
5011 }
5012 else
5013 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005014
5015 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5016 // and ObjCTypes types.
5017 const llvm::Type *ClassTy =
5018 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5019 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5020 CGF.Builder.CreateStore(Target,
5021 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5022
5023 return EmitMessageSend(CGF, ResultType, Sel,
5024 ObjCSuper, ObjCTypes.SuperPtrCTy,
5025 true, CallArgs);
5026}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005027
5028llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5029 Selector Sel) {
5030 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5031
5032 if (!Entry) {
5033 llvm::Constant *Casted =
5034 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5035 ObjCTypes.SelectorPtrTy);
5036 Entry =
5037 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5038 llvm::GlobalValue::InternalLinkage,
5039 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5040 &CGM.getModule());
5041 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5042 UsedGlobals.push_back(Entry);
5043 }
5044
5045 return Builder.CreateLoad(Entry, false, "tmp");
5046}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005047/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5048/// objc_assign_ivar (id src, id *dst)
5049///
5050void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5051 llvm::Value *src, llvm::Value *dst)
5052{
5053 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5054 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5055 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5056 src, dst, "assignivar");
5057 return;
5058}
5059
5060/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5061/// objc_assign_strongCast (id src, id *dst)
5062///
5063void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5064 CodeGen::CodeGenFunction &CGF,
5065 llvm::Value *src, llvm::Value *dst)
5066{
5067 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5068 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5069 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5070 src, dst, "weakassign");
5071 return;
5072}
5073
5074/// EmitObjCWeakRead - Code gen for loading value of a __weak
5075/// object: objc_read_weak (id *src)
5076///
5077llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5078 CodeGen::CodeGenFunction &CGF,
5079 llvm::Value *AddrWeakObj)
5080{
Eli Friedman8339b352009-03-07 03:57:15 +00005081 const llvm::Type* DestTy =
5082 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005083 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5084 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5085 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005086 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005087 return read_weak;
5088}
5089
5090/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5091/// objc_assign_weak (id src, id *dst)
5092///
5093void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5094 llvm::Value *src, llvm::Value *dst)
5095{
5096 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5097 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5098 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5099 src, dst, "weakassign");
5100 return;
5101}
5102
5103/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5104/// objc_assign_global (id src, id *dst)
5105///
5106void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5107 llvm::Value *src, llvm::Value *dst)
5108{
5109 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5110 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5111 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5112 src, dst, "globalassign");
5113 return;
5114}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005115
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005116void
5117CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5118 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005119 bool isTry = isa<ObjCAtTryStmt>(S);
5120 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5121 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005122 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005123 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005124 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005125 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5126
5127 // For @synchronized, call objc_sync_enter(sync.expr). The
5128 // evaluation of the expression must occur before we enter the
5129 // @synchronized. We can safely avoid a temp here because jumps into
5130 // @synchronized are illegal & this will dominate uses.
5131 llvm::Value *SyncArg = 0;
5132 if (!isTry) {
5133 SyncArg =
5134 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5135 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
5136 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
5137 }
5138
5139 // Push an EH context entry, used for handling rethrows and jumps
5140 // through finally.
5141 CGF.PushCleanupBlock(FinallyBlock);
5142
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005143 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005144
5145 CGF.EmitBlock(TryBlock);
5146 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5147 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5148 CGF.EmitBranchThroughCleanup(FinallyEnd);
5149
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005150 // Emit the exception handler.
5151
5152 CGF.EmitBlock(TryHandler);
5153
5154 llvm::Value *llvm_eh_exception =
5155 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5156 llvm::Value *llvm_eh_selector_i64 =
5157 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5158 llvm::Value *llvm_eh_typeid_for_i64 =
5159 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5160 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5161 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5162
5163 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5164 SelectorArgs.push_back(Exc);
5165 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
5166
5167 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005168 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005169 bool HasCatchAll = false;
5170 if (isTry) {
5171 if (const ObjCAtCatchStmt* CatchStmt =
5172 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5173 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005174 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005175 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005176
5177 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005178 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005179 // Use i8* null here to signal this is a catch all, not a cleanup.
5180 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5181 SelectorArgs.push_back(Null);
5182 HasCatchAll = true;
5183 break;
5184 }
5185
Daniel Dunbarede8de92009-03-06 00:01:21 +00005186 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5187 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005188 llvm::Value *IDEHType =
5189 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5190 if (!IDEHType)
5191 IDEHType =
5192 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5193 llvm::GlobalValue::ExternalLinkage,
5194 0, "OBJC_EHTYPE_id", &CGM.getModule());
5195 SelectorArgs.push_back(IDEHType);
5196 HasCatchAll = true;
5197 break;
5198 }
5199
5200 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005201 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005202 assert(PT && "Invalid @catch type.");
5203 const ObjCInterfaceType *IT =
5204 PT->getPointeeType()->getAsObjCInterfaceType();
5205 assert(IT && "Invalid @catch type.");
5206 llvm::Value *EHType = GetInterfaceEHType(IT);
5207 SelectorArgs.push_back(EHType);
5208 }
5209 }
5210 }
5211
5212 // We use a cleanup unless there was already a catch all.
5213 if (!HasCatchAll) {
5214 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005215 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005216 }
5217
5218 llvm::Value *Selector =
5219 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5220 SelectorArgs.begin(), SelectorArgs.end(),
5221 "selector");
5222 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005223 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005224 const Stmt *CatchBody = Handlers[i].second;
5225
5226 llvm::BasicBlock *Next = 0;
5227
5228 // The last handler always matches.
5229 if (i + 1 != e) {
5230 assert(CatchParam && "Only last handler can be a catch all.");
5231
5232 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5233 Next = CGF.createBasicBlock("catch.next");
5234 llvm::Value *Id =
5235 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5236 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5237 ObjCTypes.Int8PtrTy));
5238 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5239 Match, Next);
5240
5241 CGF.EmitBlock(Match);
5242 }
5243
5244 if (CatchBody) {
5245 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5246 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5247
5248 // Cleanups must call objc_end_catch.
5249 //
5250 // FIXME: It seems incorrect for objc_begin_catch to be inside
5251 // this context, but this matches gcc.
5252 CGF.PushCleanupBlock(MatchEnd);
5253 CGF.setInvokeDest(MatchHandler);
5254
5255 llvm::Value *ExcObject =
5256 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5257
5258 // Bind the catch parameter if it exists.
5259 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005260 ExcObject =
5261 CGF.Builder.CreateBitCast(ExcObject,
5262 CGF.ConvertType(CatchParam->getType()));
5263 // CatchParam is a ParmVarDecl because of the grammar
5264 // construction used to handle this, but for codegen purposes
5265 // we treat this as a local decl.
5266 CGF.EmitLocalBlockVarDecl(*CatchParam);
5267 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005268 }
5269
5270 CGF.ObjCEHValueStack.push_back(ExcObject);
5271 CGF.EmitStmt(CatchBody);
5272 CGF.ObjCEHValueStack.pop_back();
5273
5274 CGF.EmitBranchThroughCleanup(FinallyEnd);
5275
5276 CGF.EmitBlock(MatchHandler);
5277
5278 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5279 // We are required to emit this call to satisfy LLVM, even
5280 // though we don't use the result.
5281 llvm::SmallVector<llvm::Value*, 8> Args;
5282 Args.push_back(Exc);
5283 Args.push_back(ObjCTypes.EHPersonalityPtr);
5284 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5285 0));
5286 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5287 CGF.Builder.CreateStore(Exc, RethrowPtr);
5288 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5289
5290 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5291
5292 CGF.EmitBlock(MatchEnd);
5293
5294 // Unfortunately, we also have to generate another EH frame here
5295 // in case this throws.
5296 llvm::BasicBlock *MatchEndHandler =
5297 CGF.createBasicBlock("match.end.handler");
5298 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5299 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5300 Cont, MatchEndHandler,
5301 Args.begin(), Args.begin());
5302
5303 CGF.EmitBlock(Cont);
5304 if (Info.SwitchBlock)
5305 CGF.EmitBlock(Info.SwitchBlock);
5306 if (Info.EndBlock)
5307 CGF.EmitBlock(Info.EndBlock);
5308
5309 CGF.EmitBlock(MatchEndHandler);
5310 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5311 // We are required to emit this call to satisfy LLVM, even
5312 // though we don't use the result.
5313 Args.clear();
5314 Args.push_back(Exc);
5315 Args.push_back(ObjCTypes.EHPersonalityPtr);
5316 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5317 0));
5318 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5319 CGF.Builder.CreateStore(Exc, RethrowPtr);
5320 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5321
5322 if (Next)
5323 CGF.EmitBlock(Next);
5324 } else {
5325 assert(!Next && "catchup should be last handler.");
5326
5327 CGF.Builder.CreateStore(Exc, RethrowPtr);
5328 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5329 }
5330 }
5331
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005332 // Pop the cleanup entry, the @finally is outside this cleanup
5333 // scope.
5334 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5335 CGF.setInvokeDest(PrevLandingPad);
5336
5337 CGF.EmitBlock(FinallyBlock);
5338
5339 if (isTry) {
5340 if (const ObjCAtFinallyStmt* FinallyStmt =
5341 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5342 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5343 } else {
5344 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5345 // @synchronized.
5346 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005347 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005348
5349 if (Info.SwitchBlock)
5350 CGF.EmitBlock(Info.SwitchBlock);
5351 if (Info.EndBlock)
5352 CGF.EmitBlock(Info.EndBlock);
5353
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005354 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005355 CGF.EmitBranch(FinallyEnd);
5356
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005357 CGF.EmitBlock(FinallyRethrow);
5358 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5359 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005360 CGF.Builder.CreateUnreachable();
5361
5362 CGF.EmitBlock(FinallyEnd);
5363}
5364
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005365/// EmitThrowStmt - Generate code for a throw statement.
5366void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5367 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005368 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005369 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005370 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005371 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5373 "Unexpected rethrow outside @catch block.");
5374 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005375 }
5376
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005377 llvm::Value *ExceptionAsObject =
5378 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5379 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5380 if (InvokeDest) {
5381 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5382 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5383 Cont, InvokeDest,
5384 &ExceptionAsObject, &ExceptionAsObject + 1);
5385 CGF.EmitBlock(Cont);
5386 } else
5387 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5388 CGF.Builder.CreateUnreachable();
5389
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005390 // Clear the insertion point to indicate we are in unreachable code.
5391 CGF.Builder.ClearInsertionPoint();
5392}
Daniel Dunbare588b992009-03-01 04:46:24 +00005393
5394llvm::Value *
5395CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5396 const ObjCInterfaceDecl *ID = IT->getDecl();
5397 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5398 if (Entry)
5399 return Entry;
5400
5401 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5402 std::string VTableName = "objc_ehtype_vtable";
5403 llvm::GlobalVariable *VTableGV =
5404 CGM.getModule().getGlobalVariable(VTableName);
5405 if (!VTableGV)
5406 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5407 llvm::GlobalValue::ExternalLinkage,
5408 0, VTableName, &CGM.getModule());
5409
5410 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5411
5412 std::vector<llvm::Constant*> Values(3);
5413 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5414 Values[1] = GetClassName(ID->getIdentifier());
5415 Values[2] = GetClassGlobal(ClassName);
5416 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5417
5418 Entry =
5419 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005420 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005421 Init,
5422 (std::string("OBJC_EHTYPE_$_") +
5423 ID->getIdentifier()->getName()),
5424 &CGM.getModule());
5425
5426 return Entry;
5427}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005428
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005429/* *** */
5430
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005431CodeGen::CGObjCRuntime *
5432CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005433 return new CGObjCMac(CGM);
5434}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005435
5436CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005437CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005438 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005439}