blob: 75cf4e76abad8499ce7ec2284aab223ae39489e0 [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:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000045 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
Chris Lattner74391b42009-03-22 21:03:39 +000087 llvm::Constant *GetPropertyFn, *SetPropertyFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000088
Chris Lattner74391b42009-03-22 21:03:39 +000089 llvm::Constant *EnumerationMutationFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000090
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner74391b42009-03-22 21:03:39 +000092 llvm::Constant *GcReadWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000093
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner74391b42009-03-22 21:03:39 +000095 llvm::Constant *GcAssignWeakFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000096
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner74391b42009-03-22 21:03:39 +000098 llvm::Constant *GcAssignGlobalFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +000099
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner74391b42009-03-22 21:03:39 +0000101 llvm::Constant *GcAssignIvarFn;
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner74391b42009-03-22 21:03:39 +0000104 llvm::Constant *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner74391b42009-03-22 21:03:39 +0000107 llvm::Constant *ExceptionThrowFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattner74391b42009-03-22 21:03:39 +0000110 llvm::Constant *SyncEnterFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000111
112 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000113 llvm::Constant *SyncExitFn;
Daniel Dunbar1c566672009-02-24 01:43:46 +0000114
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
Chris Lattner74391b42009-03-22 21:03:39 +0000124 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
125 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn,
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000126 *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.
Chris Lattner74391b42009-03-22 21:03:39 +0000184 llvm::Constant *ExceptionTryEnterFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000185
186 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner74391b42009-03-22 21:03:39 +0000187 llvm::Constant *ExceptionTryExitFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000188
189 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner74391b42009-03-22 21:03:39 +0000190 llvm::Constant *ExceptionExtractFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000191
192 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner74391b42009-03-22 21:03:39 +0000193 llvm::Constant *ExceptionMatchFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000194
195 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner74391b42009-03-22 21:03:39 +0000196 llvm::Constant *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
Chris Lattner74391b42009-03-22 21:03:39 +0000203 llvm::Constant *getSendFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000204 return IsSuper ? MessageSendSuperFn : MessageSendFn;
205 }
206
Chris Lattner74391b42009-03-22 21:03:39 +0000207 llvm::Constant *getSendStretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000208 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
209 }
210
Chris Lattner74391b42009-03-22 21:03:39 +0000211 llvm::Constant *getSendFpretFn(bool IsSuper) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000212 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:
Chris Lattner74391b42009-03-22 21:03:39 +0000220 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000221 *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
Chris Lattner74391b42009-03-22 21:03:39 +0000300 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
Daniel Dunbare588b992009-03-01 04:46:24 +0000301
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 Jahanian21e6f172009-03-11 21:42:00 +0000419 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
420 /// interface declaration.
421 const llvm::StructLayout *GetInterfaceDeclStructLayout(
422 const ObjCInterfaceDecl *ID) const;
423
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000424 /// BuildIvarLayout - Builds ivar layout bitmap for the class
425 /// implementation for the __strong or __weak case.
426 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000427 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
428 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000429
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000430 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
431 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000432 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000433 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000434 unsigned int BytePos, bool ForStrongLayout,
435 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000436
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000437 /// GetIvarLayoutName - Returns a unique constant for the given
438 /// ivar layout bitmap.
439 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
440 const ObjCCommonTypesHelper &ObjCTypes);
441
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000442 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
443 RecordDecl::field_iterator &FIV,
444 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000445 /// EmitPropertyList - Emit the given property list. The return
446 /// value has type PropertyListPtrTy.
447 llvm::Constant *EmitPropertyList(const std::string &Name,
448 const Decl *Container,
449 const ObjCContainerDecl *OCD,
450 const ObjCCommonTypesHelper &ObjCTypes);
451
Fariborz Jahanianda320092009-01-29 19:24:30 +0000452 /// GetProtocolRef - Return a reference to the internal protocol
453 /// description, creating an empty one if it has not been
454 /// defined. The return value has type ProtocolPtrTy.
455 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000456
457 /// GetIvarBaseOffset - returns ivars byte offset.
458 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000459 const FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000460
Chris Lattnercd0ee142009-03-31 08:33:16 +0000461 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000462 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
463 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000464 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000465
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000466 /// CreateMetadataVar - Create a global variable with internal
467 /// linkage for use by the Objective-C runtime.
468 ///
469 /// This is a convenience wrapper which not only creates the
470 /// variable, but also sets the section and alignment and adds the
471 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000472 ///
473 /// \param Name - The variable name.
474 /// \param Init - The variable initializer; this is also used to
475 /// define the type of the variable.
476 /// \param Section - The section the variable should go into, or 0.
477 /// \param Align - The alignment for the variable, or 0.
478 /// \param AddToUsed - Whether the variable should be added to
479 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000480 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
481 llvm::Constant *Init,
482 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000483 unsigned Align,
484 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000485
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000486public:
487 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
488 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000489
Steve Naroff33fdb732009-03-31 16:53:37 +0000490 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000491
492 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
493 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000494
495 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
496
497 /// GetOrEmitProtocol - Get the protocol object for the given
498 /// declaration, emitting it if necessary. The return value has type
499 /// ProtocolPtrTy.
500 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
501
502 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
503 /// object for the given declaration, emitting it if needed. These
504 /// forward references will be filled in with empty bodies if no
505 /// definition is seen. The return value has type ProtocolPtrTy.
506 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000507};
508
509class CGObjCMac : public CGObjCCommonMac {
510private:
511 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000512 /// EmitImageInfo - Emit the image info marker used to encode some module
513 /// level information.
514 void EmitImageInfo();
515
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000516 /// EmitModuleInfo - Another marker encoding module level
517 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000518 void EmitModuleInfo();
519
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000520 /// EmitModuleSymols - Emit module symbols, the list of defined
521 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000522 llvm::Constant *EmitModuleSymbols();
523
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000524 /// FinishModule - Write out global data structures at the end of
525 /// processing a translation unit.
526 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000527
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000528 /// EmitClassExtension - Generate the class extension structure used
529 /// to store the weak ivar layout and properties. The return value
530 /// has type ClassExtensionPtrTy.
531 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
532
533 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
534 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000535 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000536 const ObjCInterfaceDecl *ID);
537
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000538 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000539 QualType ResultType,
540 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000541 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000542 QualType Arg0Ty,
543 bool IsSuper,
544 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000545
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000546 /// EmitIvarList - Emit the ivar list for the given
547 /// implementation. If ForClass is true the list of class ivars
548 /// (i.e. metaclass ivars) is emitted, otherwise the list of
549 /// interface ivars will be emitted. The return value has type
550 /// IvarListPtrTy.
551 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000552 bool ForClass);
553
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000554 /// EmitMetaClass - Emit a forward reference to the class structure
555 /// for the metaclass of the given interface. The return value has
556 /// type ClassPtrTy.
557 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
558
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000559 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000560 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000561 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
562 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000563 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000564 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000565
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000566 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000567
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000568 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000569
570 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000571 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000572 llvm::Constant *EmitMethodList(const std::string &Name,
573 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000574 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000575
576 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000577 /// method declarations.
578 /// - TypeName: The name for the type containing the methods.
579 /// - IsProtocol: True iff these methods are for a protocol.
580 /// - ClassMethds: True iff these are class methods.
581 /// - Required: When true, only "required" methods are
582 /// listed. Similarly, when false only "optional" methods are
583 /// listed. For classes this should always be true.
584 /// - begin, end: The method list to output.
585 ///
586 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000587 llvm::Constant *EmitMethodDescList(const std::string &Name,
588 const char *Section,
589 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000590
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000591 /// GetOrEmitProtocol - Get the protocol object for the given
592 /// declaration, emitting it if necessary. The return value has type
593 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000594 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000595
596 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
597 /// object for the given declaration, emitting it if needed. These
598 /// forward references will be filled in with empty bodies if no
599 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000600 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000601
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000602 /// EmitProtocolExtension - Generate the protocol extension
603 /// structure used to store optional instance and class methods, and
604 /// protocol properties. The return value has type
605 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000606 llvm::Constant *
607 EmitProtocolExtension(const ObjCProtocolDecl *PD,
608 const ConstantVector &OptInstanceMethods,
609 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
611 /// EmitProtocolList - Generate the list of referenced
612 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000613 llvm::Constant *EmitProtocolList(const std::string &Name,
614 ObjCProtocolDecl::protocol_iterator begin,
615 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000616
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000617 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
618 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000619 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000620
Fariborz Jahanianda320092009-01-29 19:24:30 +0000621 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000622 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000623
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000624 virtual llvm::Function *ModuleInitFunction();
625
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000626 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000627 QualType ResultType,
628 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000629 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000630 bool IsClassMessage,
631 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000632
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000633 virtual CodeGen::RValue
634 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000635 QualType ResultType,
636 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000637 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000638 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000639 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000640 bool IsClassMessage,
641 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000642
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000643 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000644 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000645
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000646 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000647
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000648 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000649
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000650 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000651
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000652 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000653 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000654
Chris Lattner74391b42009-03-22 21:03:39 +0000655 virtual llvm::Constant *GetPropertyGetFunction();
656 virtual llvm::Constant *GetPropertySetFunction();
657 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000658
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000659 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
660 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000661 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
662 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000663 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000664 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000665 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
666 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000667 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
668 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000669 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
670 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000671 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
672 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000673
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000674 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
675 QualType ObjectTy,
676 llvm::Value *BaseValue,
677 const ObjCIvarDecl *Ivar,
678 const FieldDecl *Field,
679 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000680 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
681 ObjCInterfaceDecl *Interface,
682 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000683};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000684
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000685class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000686private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000687 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000688 llvm::GlobalVariable* ObjCEmptyCacheVar;
689 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000690
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000691 /// MetaClassReferences - uniqued meta class references.
692 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000693
694 /// EHTypeReferences - uniqued class ehtype references.
695 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000696
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000697 /// FinishNonFragileABIModule - Write out global data structures at the end of
698 /// processing a translation unit.
699 void FinishNonFragileABIModule();
700
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000701 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
702 unsigned InstanceStart,
703 unsigned InstanceSize,
704 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000705 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
706 llvm::Constant *IsAGV,
707 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000708 llvm::Constant *ClassRoGV,
709 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000710
711 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
712
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000713 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
714
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000715 /// EmitMethodList - Emit the method list for the given
716 /// implementation. The return value has type MethodListnfABITy.
717 llvm::Constant *EmitMethodList(const std::string &Name,
718 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000719 const ConstantVector &Methods);
720 /// EmitIvarList - Emit the ivar list for the given
721 /// implementation. If ForClass is true the list of class ivars
722 /// (i.e. metaclass ivars) is emitted, otherwise the list of
723 /// interface ivars will be emitted. The return value has type
724 /// IvarListnfABIPtrTy.
725 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000726
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000727 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000728 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000729 unsigned long int offset);
730
Fariborz Jahanianda320092009-01-29 19:24:30 +0000731 /// GetOrEmitProtocol - Get the protocol object for the given
732 /// declaration, emitting it if necessary. The return value has type
733 /// ProtocolPtrTy.
734 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
735
736 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
737 /// object for the given declaration, emitting it if needed. These
738 /// forward references will be filled in with empty bodies if no
739 /// definition is seen. The return value has type ProtocolPtrTy.
740 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
741
742 /// EmitProtocolList - Generate the list of referenced
743 /// protocols. The return value has type ProtocolListPtrTy.
744 llvm::Constant *EmitProtocolList(const std::string &Name,
745 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000746 ObjCProtocolDecl::protocol_iterator end);
747
748 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
749 QualType ResultType,
750 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000751 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000752 QualType Arg0Ty,
753 bool IsSuper,
754 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000755
756 /// GetClassGlobal - Return the global variable for the Objective-C
757 /// class of the given name.
758 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000759
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000760 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
761 /// for the given class.
762 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000763 const ObjCInterfaceDecl *ID,
764 bool IsSuper = false);
765
766 /// EmitMetaClassRef - Return a Value * of the address of _class_t
767 /// meta-data
768 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
769 const ObjCInterfaceDecl *ID);
770
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000771 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
772 /// the given ivar.
773 ///
774 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000775 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000776 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000777
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000778 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
779 /// for the given selector.
780 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000781
782 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
783 /// interface. The return value has type EHTypePtrTy.
784 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000785
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000786public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000787 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000788 // FIXME. All stubs for now!
789 virtual llvm::Function *ModuleInitFunction();
790
791 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
792 QualType ResultType,
793 Selector Sel,
794 llvm::Value *Receiver,
795 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000796 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000797
798 virtual CodeGen::RValue
799 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
800 QualType ResultType,
801 Selector Sel,
802 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000803 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000804 llvm::Value *Receiver,
805 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000806 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000807
808 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000809 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810
811 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000812 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000813
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000814 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000815
816 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000817 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000818 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000819
Chris Lattner74391b42009-03-22 21:03:39 +0000820 virtual llvm::Constant *GetPropertyGetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000821 return ObjCTypes.GetPropertyFn;
822 }
Chris Lattner74391b42009-03-22 21:03:39 +0000823 virtual llvm::Constant *GetPropertySetFunction() {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000824 return ObjCTypes.SetPropertyFn;
825 }
Chris Lattner74391b42009-03-22 21:03:39 +0000826 virtual llvm::Constant *EnumerationMutationFunction() {
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000827 return ObjCTypes.EnumerationMutationFn;
828 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829
830 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000831 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000833 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000834 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000835 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000836 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000837 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000838 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000839 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000840 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000841 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000843 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000844 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
845 QualType ObjectTy,
846 llvm::Value *BaseValue,
847 const ObjCIvarDecl *Ivar,
848 const FieldDecl *Field,
849 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000850 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
851 ObjCInterfaceDecl *Interface,
852 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000853};
854
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000855} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000856
857/* *** Helper Functions *** */
858
859/// getConstantGEP() - Help routine to construct simple GEPs.
860static llvm::Constant *getConstantGEP(llvm::Constant *C,
861 unsigned idx0,
862 unsigned idx1) {
863 llvm::Value *Idxs[] = {
864 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
865 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
866 };
867 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
868}
869
870/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000871
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000872CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
873 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000874{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000875 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000876 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000877}
878
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000879/// GetClass - Return a reference to the class for the given interface
880/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000881llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000882 const ObjCInterfaceDecl *ID) {
883 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000884}
885
886/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000887llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000888 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000889}
890
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000891/// Generate a constant CFString object.
892/*
893 struct __builtin_CFString {
894 const int *isa; // point to __CFConstantStringClassReference
895 int flags;
896 const char *str;
897 long length;
898 };
899*/
900
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000901llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +0000902 const ObjCStringLiteral *SL) {
903 std::string Str(SL->getString()->getStrData(),
904 SL->getString()->getByteLength());
905 if (SL->getString()->containsNonAscii()) {
906 // FIXME: Convert from UTF-8 to UTF-16.
907 }
908 return CGM.GetAddrOfConstantCFString(Str);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000909}
910
911/// Generates a message send where the super is the receiver. This is
912/// a message send to self with special delivery semantics indicating
913/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000914CodeGen::RValue
915CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000916 QualType ResultType,
917 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000918 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000919 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000920 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000921 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000922 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000923 // Create and init a super structure; this is a (receiver, class)
924 // pair we will pass to objc_msgSendSuper.
925 llvm::Value *ObjCSuper =
926 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
927 llvm::Value *ReceiverAsObject =
928 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
929 CGF.Builder.CreateStore(ReceiverAsObject,
930 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000931
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000932 // If this is a class message the metaclass is passed as the target.
933 llvm::Value *Target;
934 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000935 if (isCategoryImpl) {
936 // Message sent to 'super' in a class method defined in a category
937 // implementation requires an odd treatment.
938 // If we are in a class method, we must retrieve the
939 // _metaclass_ for the current class, pointed at by
940 // the class's "isa" pointer. The following assumes that
941 // isa" is the first ivar in a class (which it must be).
942 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
943 Target = CGF.Builder.CreateStructGEP(Target, 0);
944 Target = CGF.Builder.CreateLoad(Target);
945 }
946 else {
947 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
948 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
949 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
950 Target = Super;
951 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000952 } else {
953 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
954 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000955 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
956 // and ObjCTypes types.
957 const llvm::Type *ClassTy =
958 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000959 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000960 CGF.Builder.CreateStore(Target,
961 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
962
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000963 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000964 ObjCSuper, ObjCTypes.SuperPtrCTy,
965 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000966}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000967
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000968/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000969CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000970 QualType ResultType,
971 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000972 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000973 bool IsClassMessage,
974 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000975 llvm::Value *Arg0 =
976 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000977 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000978 Arg0, CGF.getContext().getObjCIdType(),
979 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000980}
981
982CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000983 QualType ResultType,
984 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000985 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000986 QualType Arg0Ty,
987 bool IsSuper,
988 const CallArgList &CallArgs) {
989 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000990 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
991 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
992 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000993 CGF.getContext().getObjCSelType()));
994 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000995
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000996 CodeGenTypes &Types = CGM.getTypes();
997 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
998 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000999
1000 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001001 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001002 Fn = ObjCTypes.getSendStretFn(IsSuper);
1003 } else if (ResultType->isFloatingType()) {
1004 // FIXME: Sadly, this is wrong. This actually depends on the
1005 // architecture. This happens to be right for x86-32 though.
1006 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1007 } else {
1008 Fn = ObjCTypes.getSendFn(IsSuper);
1009 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001010 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001011 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001012}
1013
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001014llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001015 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001016 // FIXME: I don't understand why gcc generates this, or where it is
1017 // resolved. Investigate. Its also wasteful to look this up over and
1018 // over.
1019 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1020
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001021 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1022 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001023}
1024
Fariborz Jahanianda320092009-01-29 19:24:30 +00001025void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001026 // FIXME: We shouldn't need this, the protocol decl should contain
1027 // enough information to tell us whether this was a declaration or a
1028 // definition.
1029 DefinedProtocols.insert(PD->getIdentifier());
1030
1031 // If we have generated a forward reference to this protocol, emit
1032 // it now. Otherwise do nothing, the protocol objects are lazily
1033 // emitted.
1034 if (Protocols.count(PD->getIdentifier()))
1035 GetOrEmitProtocol(PD);
1036}
1037
Fariborz Jahanianda320092009-01-29 19:24:30 +00001038llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001039 if (DefinedProtocols.count(PD->getIdentifier()))
1040 return GetOrEmitProtocol(PD);
1041 return GetOrEmitProtocolRef(PD);
1042}
1043
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001044/*
1045 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1046 struct _objc_protocol {
1047 struct _objc_protocol_extension *isa;
1048 char *protocol_name;
1049 struct _objc_protocol_list *protocol_list;
1050 struct _objc__method_prototype_list *instance_methods;
1051 struct _objc__method_prototype_list *class_methods
1052 };
1053
1054 See EmitProtocolExtension().
1055*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001056llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1057 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1058
1059 // Early exit if a defining object has already been generated.
1060 if (Entry && Entry->hasInitializer())
1061 return Entry;
1062
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001063 // FIXME: I don't understand why gcc generates this, or where it is
1064 // resolved. Investigate. Its also wasteful to look this up over and
1065 // over.
1066 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1067
Chris Lattner8ec03f52008-11-24 03:54:41 +00001068 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001069
1070 // Construct method lists.
1071 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1072 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1073 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1074 e = PD->instmeth_end(); i != e; ++i) {
1075 ObjCMethodDecl *MD = *i;
1076 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1077 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1078 OptInstanceMethods.push_back(C);
1079 } else {
1080 InstanceMethods.push_back(C);
1081 }
1082 }
1083
1084 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1085 e = PD->classmeth_end(); i != e; ++i) {
1086 ObjCMethodDecl *MD = *i;
1087 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1088 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1089 OptClassMethods.push_back(C);
1090 } else {
1091 ClassMethods.push_back(C);
1092 }
1093 }
1094
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001095 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001096 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001097 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001098 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001099 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001100 PD->protocol_begin(),
1101 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001102 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001103 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1104 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001105 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1106 InstanceMethods);
1107 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001108 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1109 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001110 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1111 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001112 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1113 Values);
1114
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001115 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001116 // Already created, fix the linkage and update the initializer.
1117 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001118 Entry->setInitializer(Init);
1119 } else {
1120 Entry =
1121 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1122 llvm::GlobalValue::InternalLinkage,
1123 Init,
1124 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1125 &CGM.getModule());
1126 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001127 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001128 UsedGlobals.push_back(Entry);
1129 // FIXME: Is this necessary? Why only for protocol?
1130 Entry->setAlignment(4);
1131 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001132
1133 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001134}
1135
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001136llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001137 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1138
1139 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001140 // We use the initializer as a marker of whether this is a forward
1141 // reference or not. At module finalization we add the empty
1142 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001143 Entry =
1144 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001145 llvm::GlobalValue::ExternalLinkage,
1146 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001147 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148 &CGM.getModule());
1149 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001150 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001151 UsedGlobals.push_back(Entry);
1152 // FIXME: Is this necessary? Why only for protocol?
1153 Entry->setAlignment(4);
1154 }
1155
1156 return Entry;
1157}
1158
1159/*
1160 struct _objc_protocol_extension {
1161 uint32_t size;
1162 struct objc_method_description_list *optional_instance_methods;
1163 struct objc_method_description_list *optional_class_methods;
1164 struct objc_property_list *instance_properties;
1165 };
1166*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001167llvm::Constant *
1168CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1169 const ConstantVector &OptInstanceMethods,
1170 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001172 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001173 std::vector<llvm::Constant*> Values(4);
1174 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001175 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001176 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1177 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001178 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1179 OptInstanceMethods);
1180 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001181 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1182 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001183 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1184 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001185 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1186 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001187 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001188
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001189 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001190 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1191 Values[3]->isNullValue())
1192 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1193
1194 llvm::Constant *Init =
1195 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001196
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001197 // No special section, but goes in llvm.used
1198 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1199 Init,
1200 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001201}
1202
1203/*
1204 struct objc_protocol_list {
1205 struct objc_protocol_list *next;
1206 long count;
1207 Protocol *list[];
1208 };
1209*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001210llvm::Constant *
1211CGObjCMac::EmitProtocolList(const std::string &Name,
1212 ObjCProtocolDecl::protocol_iterator begin,
1213 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001214 std::vector<llvm::Constant*> ProtocolRefs;
1215
Daniel Dunbardbc93372008-08-21 21:57:41 +00001216 for (; begin != end; ++begin)
1217 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001218
1219 // Just return null for empty protocol lists
1220 if (ProtocolRefs.empty())
1221 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1222
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001223 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001224 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1225
1226 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001227 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001228 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1229 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1230 Values[2] =
1231 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1232 ProtocolRefs.size()),
1233 ProtocolRefs);
1234
1235 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1236 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001237 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001238 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001239 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1240}
1241
1242/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001243 struct _objc_property {
1244 const char * const name;
1245 const char * const attributes;
1246 };
1247
1248 struct _objc_property_list {
1249 uint32_t entsize; // sizeof (struct _objc_property)
1250 uint32_t prop_count;
1251 struct _objc_property[prop_count];
1252 };
1253*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001254llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1255 const Decl *Container,
1256 const ObjCContainerDecl *OCD,
1257 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001258 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001259 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1260 E = OCD->prop_end(); I != E; ++I) {
1261 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001262 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001263 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001264 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1265 Prop));
1266 }
1267
1268 // Return null for empty list.
1269 if (Properties.empty())
1270 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1271
1272 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001273 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001274 std::vector<llvm::Constant*> Values(3);
1275 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1276 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1277 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1278 Properties.size());
1279 Values[2] = llvm::ConstantArray::get(AT, Properties);
1280 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1281
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001282 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001283 llvm::GlobalVariable *GV =
1284 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1285 0, true);
1286 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001287}
1288
1289/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001290 struct objc_method_description_list {
1291 int count;
1292 struct objc_method_description list[];
1293 };
1294*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001295llvm::Constant *
1296CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1297 std::vector<llvm::Constant*> Desc(2);
1298 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1299 ObjCTypes.SelectorPtrTy);
1300 Desc[1] = GetMethodVarType(MD);
1301 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1302 Desc);
1303}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001304
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001305llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1306 const char *Section,
1307 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001308 // Return null for empty list.
1309 if (Methods.empty())
1310 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1311
1312 std::vector<llvm::Constant*> Values(2);
1313 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1314 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1315 Methods.size());
1316 Values[1] = llvm::ConstantArray::get(AT, Methods);
1317 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1318
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001319 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001320 return llvm::ConstantExpr::getBitCast(GV,
1321 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001322}
1323
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001324/*
1325 struct _objc_category {
1326 char *category_name;
1327 char *class_name;
1328 struct _objc_method_list *instance_methods;
1329 struct _objc_method_list *class_methods;
1330 struct _objc_protocol_list *protocols;
1331 uint32_t size; // <rdar://4585769>
1332 struct _objc_property_list *instance_properties;
1333 };
1334 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001335void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001336 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001337
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001338 // FIXME: This is poor design, the OCD should have a pointer to the
1339 // category decl. Additionally, note that Category can be null for
1340 // the @implementation w/o an @interface case. Sema should just
1341 // create one for us as it does for @implementation so everyone else
1342 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001343 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001344 const ObjCCategoryDecl *Category =
1345 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001346 std::string ExtName(Interface->getNameAsString() + "_" +
1347 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001348
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001349 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1350 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1351 e = OCD->instmeth_end(); i != e; ++i) {
1352 // Instance methods should always be defined.
1353 InstanceMethods.push_back(GetMethodConstant(*i));
1354 }
1355 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1356 e = OCD->classmeth_end(); i != e; ++i) {
1357 // Class methods should always be defined.
1358 ClassMethods.push_back(GetMethodConstant(*i));
1359 }
1360
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001361 std::vector<llvm::Constant*> Values(7);
1362 Values[0] = GetClassName(OCD->getIdentifier());
1363 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001364 Values[2] =
1365 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1366 ExtName,
1367 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001368 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001369 Values[3] =
1370 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1371 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001372 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001373 if (Category) {
1374 Values[4] =
1375 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1376 Category->protocol_begin(),
1377 Category->protocol_end());
1378 } else {
1379 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1380 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001381 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001382
1383 // If there is no category @interface then there can be no properties.
1384 if (Category) {
1385 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001386 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001387 } else {
1388 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1389 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001390
1391 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1392 Values);
1393
1394 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001395 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1396 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001397 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001398 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001399}
1400
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001401// FIXME: Get from somewhere?
1402enum ClassFlags {
1403 eClassFlags_Factory = 0x00001,
1404 eClassFlags_Meta = 0x00002,
1405 // <rdr://5142207>
1406 eClassFlags_HasCXXStructors = 0x02000,
1407 eClassFlags_Hidden = 0x20000,
1408 eClassFlags_ABI2_Hidden = 0x00010,
1409 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1410};
1411
1412// <rdr://5142207&4705298&4843145>
1413static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1414 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1415 // FIXME: Support -fvisibility
1416 switch (attr->getVisibility()) {
1417 default:
1418 assert(0 && "Unknown visibility");
1419 return false;
1420 case VisibilityAttr::DefaultVisibility:
1421 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1422 return false;
1423 case VisibilityAttr::HiddenVisibility:
1424 return true;
1425 }
1426 } else {
1427 return false; // FIXME: Support -fvisibility
1428 }
1429}
1430
1431/*
1432 struct _objc_class {
1433 Class isa;
1434 Class super_class;
1435 const char *name;
1436 long version;
1437 long info;
1438 long instance_size;
1439 struct _objc_ivar_list *ivars;
1440 struct _objc_method_list *methods;
1441 struct _objc_cache *cache;
1442 struct _objc_protocol_list *protocols;
1443 // Objective-C 1.0 extensions (<rdr://4585769>)
1444 const char *ivar_layout;
1445 struct _objc_class_ext *ext;
1446 };
1447
1448 See EmitClassExtension();
1449 */
1450void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001451 DefinedSymbols.insert(ID->getIdentifier());
1452
Chris Lattner8ec03f52008-11-24 03:54:41 +00001453 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001454 // FIXME: Gross
1455 ObjCInterfaceDecl *Interface =
1456 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001457 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001458 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001459 Interface->protocol_begin(),
1460 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001461 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001462 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001463 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001464 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001465
1466 // FIXME: Set CXX-structors flag.
1467 if (IsClassHidden(ID->getClassInterface()))
1468 Flags |= eClassFlags_Hidden;
1469
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001470 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1471 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1472 e = ID->instmeth_end(); i != e; ++i) {
1473 // Instance methods should always be defined.
1474 InstanceMethods.push_back(GetMethodConstant(*i));
1475 }
1476 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1477 e = ID->classmeth_end(); i != e; ++i) {
1478 // Class methods should always be defined.
1479 ClassMethods.push_back(GetMethodConstant(*i));
1480 }
1481
1482 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1483 e = ID->propimpl_end(); i != e; ++i) {
1484 ObjCPropertyImplDecl *PID = *i;
1485
1486 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1487 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1488
1489 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1490 if (llvm::Constant *C = GetMethodConstant(MD))
1491 InstanceMethods.push_back(C);
1492 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1493 if (llvm::Constant *C = GetMethodConstant(MD))
1494 InstanceMethods.push_back(C);
1495 }
1496 }
1497
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001498 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001499 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001500 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001501 // Record a reference to the super class.
1502 LazySymbols.insert(Super->getIdentifier());
1503
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001504 Values[ 1] =
1505 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1506 ObjCTypes.ClassPtrTy);
1507 } else {
1508 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1509 }
1510 Values[ 2] = GetClassName(ID->getIdentifier());
1511 // Version is always 0.
1512 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1513 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1514 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001515 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001516 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001517 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001518 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001519 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001520 // cache is always NULL.
1521 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1522 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001523 // FIXME: Set ivar_layout
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001524 // Values[10] = BuildIvarLayout(ID, true);
1525 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001526 Values[11] = EmitClassExtension(ID);
1527 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1528 Values);
1529
1530 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001531 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1532 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001533 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534 DefinedClasses.push_back(GV);
1535}
1536
1537llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1538 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001539 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001540 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001541 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001542 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001543
1544 if (IsClassHidden(ID->getClassInterface()))
1545 Flags |= eClassFlags_Hidden;
1546
1547 std::vector<llvm::Constant*> Values(12);
1548 // The isa for the metaclass is the root of the hierarchy.
1549 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1550 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1551 Root = Super;
1552 Values[ 0] =
1553 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1554 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001555 // The super class for the metaclass is emitted as the name of the
1556 // super class. The runtime fixes this up to point to the
1557 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001558 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1559 Values[ 1] =
1560 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1561 ObjCTypes.ClassPtrTy);
1562 } else {
1563 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1564 }
1565 Values[ 2] = GetClassName(ID->getIdentifier());
1566 // Version is always 0.
1567 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1568 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1569 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001570 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001571 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001572 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001573 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001574 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001575 // cache is always NULL.
1576 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1577 Values[ 9] = Protocols;
1578 // ivar_layout for metaclass is always NULL.
1579 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1580 // The class extension is always unused for metaclasses.
1581 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1582 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1583 Values);
1584
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001585 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001586 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001587
1588 // Check for a forward reference.
1589 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1590 if (GV) {
1591 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1592 "Forward metaclass reference has incorrect type.");
1593 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1594 GV->setInitializer(Init);
1595 } else {
1596 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1597 llvm::GlobalValue::InternalLinkage,
1598 Init, Name,
1599 &CGM.getModule());
1600 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001601 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001602 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001603 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001604
1605 return GV;
1606}
1607
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001608llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001609 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001610
1611 // FIXME: Should we look these up somewhere other than the
1612 // module. Its a bit silly since we only generate these while
1613 // processing an implementation, so exactly one pointer would work
1614 // if know when we entered/exitted an implementation block.
1615
1616 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001617 // Previously, metaclass with internal linkage may have been defined.
1618 // pass 'true' as 2nd argument so it is returned.
1619 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001620 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1621 "Forward metaclass reference has incorrect type.");
1622 return GV;
1623 } else {
1624 // Generate as an external reference to keep a consistent
1625 // module. This will be patched up when we emit the metaclass.
1626 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1627 llvm::GlobalValue::ExternalLinkage,
1628 0,
1629 Name,
1630 &CGM.getModule());
1631 }
1632}
1633
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001634/*
1635 struct objc_class_ext {
1636 uint32_t size;
1637 const char *weak_ivar_layout;
1638 struct _objc_property_list *properties;
1639 };
1640*/
1641llvm::Constant *
1642CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1643 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001644 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001645
1646 std::vector<llvm::Constant*> Values(3);
1647 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001648 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00001649 // Values[1] = BuildIvarLayout(ID, false);
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001650 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001651 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001652 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001653
1654 // Return null if no extension bits are used.
1655 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1656 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1657
1658 llvm::Constant *Init =
1659 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001660 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1661 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001662}
1663
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001664/// countInheritedIvars - count number of ivars in class and its super class(s)
1665///
1666static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1667 int count = 0;
1668 if (!OI)
1669 return 0;
1670 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1671 if (SuperClass)
1672 count += countInheritedIvars(SuperClass);
1673 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1674 E = OI->ivar_end(); I != E; ++I)
1675 ++count;
Fariborz Jahanian18191882009-03-31 18:11:23 +00001676 // look into properties.
1677 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1678 E = OI->prop_end(); I != E; ++I) {
1679 if ((*I)->getPropertyIvarDecl())
1680 ++count;
1681 }
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001682 return count;
1683}
1684
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001685/// getInterfaceDeclForIvar - Get the interface declaration node where
1686/// this ivar is declared in.
1687/// FIXME. Ideally, this info should be in the ivar node. But currently
1688/// it is not and prevailing wisdom is that ASTs should not have more
1689/// info than is absolutely needed, even though this info reflects the
1690/// source language.
1691///
1692static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1693 const ObjCInterfaceDecl *OI,
1694 const ObjCIvarDecl *IVD) {
1695 if (!OI)
1696 return 0;
1697 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1698 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1699 E = OI->ivar_end(); I != E; ++I)
1700 if ((*I)->getIdentifier() == IVD->getIdentifier())
1701 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00001702 // look into properties.
1703 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1704 E = OI->prop_end(); I != E; ++I) {
1705 ObjCPropertyDecl *PDecl = (*I);
1706 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
1707 if (IV->getIdentifier() == IVD->getIdentifier())
1708 return OI;
1709 }
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001710 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1711}
1712
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001713/*
1714 struct objc_ivar {
1715 char *ivar_name;
1716 char *ivar_type;
1717 int ivar_offset;
1718 };
1719
1720 struct objc_ivar_list {
1721 int ivar_count;
1722 struct objc_ivar list[count];
1723 };
1724 */
1725llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001726 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001727 std::vector<llvm::Constant*> Ivars, Ivar(3);
1728
1729 // When emitting the root class GCC emits ivar entries for the
1730 // actual class structure. It is not clear if we need to follow this
1731 // behavior; for now lets try and get away with not doing it. If so,
1732 // the cleanest solution would be to make up an ObjCInterfaceDecl
1733 // for the class.
1734 if (ForClass)
1735 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001736
1737 ObjCInterfaceDecl *OID =
1738 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001739 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001740
1741 RecordDecl::field_iterator ifield, pfield;
1742 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001743 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1744 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001745 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001746 if (Field->getIdentifier())
1747 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1748 else
1749 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001750 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001751 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001752 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001753 }
1754
1755 // Return null for empty list.
1756 if (Ivars.empty())
1757 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1758
1759 std::vector<llvm::Constant*> Values(2);
1760 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1761 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1762 Ivars.size());
1763 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1764 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1765
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001766 llvm::GlobalVariable *GV;
1767 if (ForClass)
1768 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001769 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1770 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001771 else
1772 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1773 + ID->getNameAsString(),
1774 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1775 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001776 return llvm::ConstantExpr::getBitCast(GV,
1777 ObjCTypes.IvarListPtrTy);
1778}
1779
1780/*
1781 struct objc_method {
1782 SEL method_name;
1783 char *method_types;
1784 void *method;
1785 };
1786
1787 struct objc_method_list {
1788 struct objc_method_list *obsolete;
1789 int count;
1790 struct objc_method methods_list[count];
1791 };
1792*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001793
1794/// GetMethodConstant - Return a struct objc_method constant for the
1795/// given method if it has been defined. The result is null if the
1796/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001797llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001798 // FIXME: Use DenseMap::lookup
1799 llvm::Function *Fn = MethodDefinitions[MD];
1800 if (!Fn)
1801 return 0;
1802
1803 std::vector<llvm::Constant*> Method(3);
1804 Method[0] =
1805 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1806 ObjCTypes.SelectorPtrTy);
1807 Method[1] = GetMethodVarType(MD);
1808 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1809 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1810}
1811
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001812llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1813 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001814 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001815 // Return null for empty list.
1816 if (Methods.empty())
1817 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1818
1819 std::vector<llvm::Constant*> Values(3);
1820 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1821 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1822 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1823 Methods.size());
1824 Values[2] = llvm::ConstantArray::get(AT, Methods);
1825 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1826
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001827 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001828 return llvm::ConstantExpr::getBitCast(GV,
1829 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001830}
1831
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001832llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001833 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001834 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001835 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001836
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001837 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001838 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001839 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001840 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001841 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001842 llvm::GlobalValue::InternalLinkage,
1843 Name,
1844 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001845 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001846
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001847 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001848}
1849
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001850uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001851 const FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001852 if (!Field->isBitField())
1853 return Layout->getElementOffset(
1854 CGM.getTypes().getLLVMFieldNo(Field));
1855 // FIXME. Must be a better way of getting a bitfield base offset.
1856 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1857 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1858 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1859 offset = (offset*size)/8;
1860 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001861}
1862
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001863/// GetFieldBaseOffset - return's field byt offset.
1864uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1865 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00001866 const FieldDecl *Field) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001867 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Chris Lattnercd0ee142009-03-31 08:33:16 +00001868 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
1869 return GetIvarBaseOffset(Layout, FD);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001870}
1871
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001872llvm::GlobalVariable *
1873CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1874 llvm::Constant *Init,
1875 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001876 unsigned Align,
1877 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001878 const llvm::Type *Ty = Init->getType();
1879 llvm::GlobalVariable *GV =
1880 new llvm::GlobalVariable(Ty, false,
1881 llvm::GlobalValue::InternalLinkage,
1882 Init,
1883 Name,
1884 &CGM.getModule());
1885 if (Section)
1886 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001887 if (Align)
1888 GV->setAlignment(Align);
1889 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001890 UsedGlobals.push_back(GV);
1891 return GV;
1892}
1893
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001894llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001895 // Abuse this interface function as a place to finalize.
1896 FinishModule();
1897
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001898 return NULL;
1899}
1900
Chris Lattner74391b42009-03-22 21:03:39 +00001901llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001902 return ObjCTypes.GetPropertyFn;
1903}
1904
Chris Lattner74391b42009-03-22 21:03:39 +00001905llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Daniel Dunbar49f66022008-09-24 03:38:44 +00001906 return ObjCTypes.SetPropertyFn;
1907}
1908
Chris Lattner74391b42009-03-22 21:03:39 +00001909llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001910 return ObjCTypes.EnumerationMutationFn;
1911}
1912
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001913/*
1914
1915Objective-C setjmp-longjmp (sjlj) Exception Handling
1916--
1917
1918The basic framework for a @try-catch-finally is as follows:
1919{
1920 objc_exception_data d;
1921 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001922 bool _call_try_exit = true;
1923
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001924 objc_exception_try_enter(&d);
1925 if (!setjmp(d.jmp_buf)) {
1926 ... try body ...
1927 } else {
1928 // exception path
1929 id _caught = objc_exception_extract(&d);
1930
1931 // enter new try scope for handlers
1932 if (!setjmp(d.jmp_buf)) {
1933 ... match exception and execute catch blocks ...
1934
1935 // fell off end, rethrow.
1936 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001937 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001938 } else {
1939 // exception in catch block
1940 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001941 _call_try_exit = false;
1942 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001943 }
1944 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001945 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001946
1947finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001948 if (_call_try_exit)
1949 objc_exception_try_exit(&d);
1950
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001951 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001952 ... dispatch to finally destination ...
1953
1954finally_rethrow:
1955 objc_exception_throw(_rethrow);
1956
1957finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001958}
1959
1960This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001961uses _rethrow to determine if objc_exception_try_exit should be called
1962and if the object should be rethrown. This breaks in the face of
1963throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001964
1965We specialize this framework for a few particular circumstances:
1966
1967 - If there are no catch blocks, then we avoid emitting the second
1968 exception handling context.
1969
1970 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1971 e)) we avoid emitting the code to rethrow an uncaught exception.
1972
1973 - FIXME: If there is no @finally block we can do a few more
1974 simplifications.
1975
1976Rethrows and Jumps-Through-Finally
1977--
1978
1979Support for implicit rethrows and jumping through the finally block is
1980handled by storing the current exception-handling context in
1981ObjCEHStack.
1982
Daniel Dunbar898d5082008-09-30 01:06:03 +00001983In order to implement proper @finally semantics, we support one basic
1984mechanism for jumping through the finally block to an arbitrary
1985destination. Constructs which generate exits from a @try or @catch
1986block use this mechanism to implement the proper semantics by chaining
1987jumps, as necessary.
1988
1989This mechanism works like the one used for indirect goto: we
1990arbitrarily assign an ID to each destination and store the ID for the
1991destination in a variable prior to entering the finally block. At the
1992end of the finally block we simply create a switch to the proper
1993destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001994
1995Code gen for @synchronized(expr) stmt;
1996Effectively generating code for:
1997objc_sync_enter(expr);
1998@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001999*/
2000
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002001void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2002 const Stmt &S) {
2003 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002004 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002005 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002006 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002007 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2008 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2009 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002010
2011 // For @synchronized, call objc_sync_enter(sync.expr). The
2012 // evaluation of the expression must occur before we enter the
2013 // @synchronized. We can safely avoid a temp here because jumps into
2014 // @synchronized are illegal & this will dominate uses.
2015 llvm::Value *SyncArg = 0;
2016 if (!isTry) {
2017 SyncArg =
2018 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2019 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
2020 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
2021 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002022
2023 // Push an EH context entry, used for handling rethrows and jumps
2024 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002025 CGF.PushCleanupBlock(FinallyBlock);
2026
Anders Carlsson273558f2009-02-07 21:37:21 +00002027 CGF.ObjCEHValueStack.push_back(0);
2028
Daniel Dunbar898d5082008-09-30 01:06:03 +00002029 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002030 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2031 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002032 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2033 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002034 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2035 "_call_try_exit");
2036 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2037
Anders Carlsson80f25672008-09-09 17:59:25 +00002038 // Enter a new try block and call setjmp.
2039 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2040 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2041 "jmpbufarray");
2042 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2043 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2044 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002045
Daniel Dunbar55e87422008-11-11 02:29:29 +00002046 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2047 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002048 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002049 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002050
2051 // Emit the @try block.
2052 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002053 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2054 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002055 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002056
2057 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002058 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002059
2060 // Retrieve the exception object. We may emit multiple blocks but
2061 // nothing can cross this so the value is already in SSA form.
2062 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2063 ExceptionData,
2064 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002065 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002066 if (!isTry)
2067 {
2068 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002069 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002070 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002071 }
2072 else if (const ObjCAtCatchStmt* CatchStmt =
2073 cast<ObjCAtTryStmt>(S).getCatchStmts())
2074 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002075 // Enter a new exception try block (in case a @catch block throws
2076 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002077 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002078
Anders Carlsson80f25672008-09-09 17:59:25 +00002079 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2080 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002081 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002082
Daniel Dunbar55e87422008-11-11 02:29:29 +00002083 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2084 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002085 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002086
2087 CGF.EmitBlock(CatchBlock);
2088
Daniel Dunbar55e40722008-09-27 07:03:52 +00002089 // Handle catch list. As a special case we check if everything is
2090 // matched and avoid generating code for falling off the end if
2091 // so.
2092 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002093 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002094 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002095
Steve Naroff7ba138a2009-03-03 19:52:17 +00002096 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002097 const PointerType *PT = 0;
2098
Anders Carlsson80f25672008-09-09 17:59:25 +00002099 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002100 if (!CatchParam) {
2101 AllMatched = true;
2102 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002103 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002104
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002105 // catch(id e) always matches.
2106 // FIXME: For the time being we also match id<X>; this should
2107 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002108 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002109 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002110 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002111 }
2112
Daniel Dunbar55e40722008-09-27 07:03:52 +00002113 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002114 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002115 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002116 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002117 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002118 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002119
Anders Carlssondde0a942008-09-11 09:15:33 +00002120 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002121 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002122 break;
2123 }
2124
Daniel Dunbar129271a2008-09-27 07:36:24 +00002125 assert(PT && "Unexpected non-pointer type in @catch");
2126 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002127 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002128 assert(ObjCType && "Catch parameter must have Objective-C type!");
2129
2130 // Check if the @catch block matches the exception object.
2131 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2132
Anders Carlsson80f25672008-09-09 17:59:25 +00002133 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2134 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002135
Daniel Dunbar55e87422008-11-11 02:29:29 +00002136 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002137
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002138 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002139 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002140
2141 // Emit the @catch block.
2142 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002143 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002144 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002145
2146 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002147 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002148 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002149 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002150
2151 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002152 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002153
2154 CGF.EmitBlock(NextCatchBlock);
2155 }
2156
Daniel Dunbar55e40722008-09-27 07:03:52 +00002157 if (!AllMatched) {
2158 // None of the handlers caught the exception, so store it to be
2159 // rethrown at the end of the @finally block.
2160 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002161 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002162 }
2163
2164 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002165 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002166 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2167 ExceptionData),
2168 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002169 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002170 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002171 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002172 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002173 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002174 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002175 }
2176
Daniel Dunbar898d5082008-09-30 01:06:03 +00002177 // Pop the exception-handling stack entry. It is important to do
2178 // this now, because the code in the @finally block is not in this
2179 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002180 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2181
Anders Carlsson273558f2009-02-07 21:37:21 +00002182 CGF.ObjCEHValueStack.pop_back();
2183
Anders Carlsson80f25672008-09-09 17:59:25 +00002184 // Emit the @finally block.
2185 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002186 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2187
2188 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2189
2190 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002191 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002192
2193 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002194 if (isTry) {
2195 if (const ObjCAtFinallyStmt* FinallyStmt =
2196 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2197 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002198 } else {
2199 // Emit objc_sync_exit(expr); as finally's sole statement for
2200 // @synchronized.
2201 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002202 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002203
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002204 // Emit the switch block
2205 if (Info.SwitchBlock)
2206 CGF.EmitBlock(Info.SwitchBlock);
2207 if (Info.EndBlock)
2208 CGF.EmitBlock(Info.EndBlock);
2209
Daniel Dunbar898d5082008-09-30 01:06:03 +00002210 CGF.EmitBlock(FinallyRethrow);
2211 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2212 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002213 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002214
2215 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002216}
2217
2218void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002219 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002220 llvm::Value *ExceptionAsObject;
2221
2222 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2223 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2224 ExceptionAsObject =
2225 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2226 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002227 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002228 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002229 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002230 }
2231
2232 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002233 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002234
2235 // Clear the insertion point to indicate we are in unreachable code.
2236 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002237}
2238
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002239/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002240/// object: objc_read_weak (id *src)
2241///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002242llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002243 llvm::Value *AddrWeakObj)
2244{
Eli Friedman8339b352009-03-07 03:57:15 +00002245 const llvm::Type* DestTy =
2246 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002247 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002248 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002249 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002250 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002251 return read_weak;
2252}
2253
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002254/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2255/// objc_assign_weak (id src, id *dst)
2256///
2257void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2258 llvm::Value *src, llvm::Value *dst)
2259{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002260 const llvm::Type * SrcTy = src->getType();
2261 if (!isa<llvm::PointerType>(SrcTy)) {
2262 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2263 assert(Size <= 8 && "does not support size > 8");
2264 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2265 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002266 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2267 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002268 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2269 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002270 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2271 src, dst, "weakassign");
2272 return;
2273}
2274
Fariborz Jahanian58626502008-11-19 00:59:10 +00002275/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2276/// objc_assign_global (id src, id *dst)
2277///
2278void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2279 llvm::Value *src, llvm::Value *dst)
2280{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002281 const llvm::Type * SrcTy = src->getType();
2282 if (!isa<llvm::PointerType>(SrcTy)) {
2283 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2284 assert(Size <= 8 && "does not support size > 8");
2285 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2286 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002287 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2288 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002289 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2290 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002291 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2292 src, dst, "globalassign");
2293 return;
2294}
2295
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002296/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2297/// objc_assign_ivar (id src, id *dst)
2298///
2299void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2300 llvm::Value *src, llvm::Value *dst)
2301{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002302 const llvm::Type * SrcTy = src->getType();
2303 if (!isa<llvm::PointerType>(SrcTy)) {
2304 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2305 assert(Size <= 8 && "does not support size > 8");
2306 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2307 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002308 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2309 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002310 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2311 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2312 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2313 src, dst, "assignivar");
2314 return;
2315}
2316
Fariborz Jahanian58626502008-11-19 00:59:10 +00002317/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2318/// objc_assign_strongCast (id src, id *dst)
2319///
2320void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2321 llvm::Value *src, llvm::Value *dst)
2322{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002323 const llvm::Type * SrcTy = src->getType();
2324 if (!isa<llvm::PointerType>(SrcTy)) {
2325 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2326 assert(Size <= 8 && "does not support size > 8");
2327 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2328 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002329 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2330 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002331 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2332 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002333 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2334 src, dst, "weakassign");
2335 return;
2336}
2337
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002338/// EmitObjCValueForIvar - Code Gen for ivar reference.
2339///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002340LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2341 QualType ObjectTy,
2342 llvm::Value *BaseValue,
2343 const ObjCIvarDecl *Ivar,
2344 const FieldDecl *Field,
2345 unsigned CVRQualifiers) {
2346 if (Ivar->isBitField())
2347 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2348 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002349 // TODO: Add a special case for isa (index 0)
2350 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2351 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002352 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002353 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2354 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002355 LValue::SetObjCIvar(LV, true);
2356 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002357}
2358
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002359llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2360 ObjCInterfaceDecl *Interface,
2361 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002362 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002363 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002364 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002365 return llvm::ConstantInt::get(
2366 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2367 Offset);
2368}
2369
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002370/* *** Private Interface *** */
2371
2372/// EmitImageInfo - Emit the image info marker used to encode some module
2373/// level information.
2374///
2375/// See: <rdr://4810609&4810587&4810587>
2376/// struct IMAGE_INFO {
2377/// unsigned version;
2378/// unsigned flags;
2379/// };
2380enum ImageInfoFlags {
2381 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2382 eImageInfo_GarbageCollected = (1 << 1),
2383 eImageInfo_GCOnly = (1 << 2)
2384};
2385
2386void CGObjCMac::EmitImageInfo() {
2387 unsigned version = 0; // Version is unused?
2388 unsigned flags = 0;
2389
2390 // FIXME: Fix and continue?
2391 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2392 flags |= eImageInfo_GarbageCollected;
2393 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2394 flags |= eImageInfo_GCOnly;
2395
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002396 // Emitted as int[2];
2397 llvm::Constant *values[2] = {
2398 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2399 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2400 };
2401 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002402
2403 const char *Section;
2404 if (ObjCABI == 1)
2405 Section = "__OBJC, __image_info,regular";
2406 else
2407 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002408 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002409 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2410 llvm::ConstantArray::get(AT, values, 2),
2411 Section,
2412 0,
2413 true);
2414 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002415}
2416
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002417
2418// struct objc_module {
2419// unsigned long version;
2420// unsigned long size;
2421// const char *name;
2422// Symtab symtab;
2423// };
2424
2425// FIXME: Get from somewhere
2426static const int ModuleVersion = 7;
2427
2428void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002429 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430
2431 std::vector<llvm::Constant*> Values(4);
2432 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2433 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002434 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002435 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002436 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002437 CreateMetadataVar("\01L_OBJC_MODULES",
2438 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2439 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002440 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002441}
2442
2443llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002444 unsigned NumClasses = DefinedClasses.size();
2445 unsigned NumCategories = DefinedCategories.size();
2446
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002447 // Return null if no symbols were defined.
2448 if (!NumClasses && !NumCategories)
2449 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2450
2451 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002452 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2453 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2454 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2455 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2456
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002457 // The runtime expects exactly the list of defined classes followed
2458 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002459 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002460 for (unsigned i=0; i<NumClasses; i++)
2461 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2462 ObjCTypes.Int8PtrTy);
2463 for (unsigned i=0; i<NumCategories; i++)
2464 Symbols[NumClasses + i] =
2465 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2466 ObjCTypes.Int8PtrTy);
2467
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002468 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002469 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002470 NumClasses + NumCategories),
2471 Symbols);
2472
2473 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2474
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002475 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002476 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2477 "__OBJC,__symbols,regular,no_dead_strip",
2478 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002479 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2480}
2481
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002482llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002483 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002484 LazySymbols.insert(ID->getIdentifier());
2485
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002486 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2487
2488 if (!Entry) {
2489 llvm::Constant *Casted =
2490 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2491 ObjCTypes.ClassPtrTy);
2492 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002493 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2494 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2495 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002496 }
2497
2498 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002499}
2500
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002501llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002502 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2503
2504 if (!Entry) {
2505 llvm::Constant *Casted =
2506 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2507 ObjCTypes.SelectorPtrTy);
2508 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002509 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2510 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2511 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002512 }
2513
2514 return Builder.CreateLoad(Entry, false, "tmp");
2515}
2516
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002517llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002518 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002519
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002520 if (!Entry)
2521 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2522 llvm::ConstantArray::get(Ident->getName()),
2523 "__TEXT,__cstring,cstring_literals",
2524 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002525
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002526 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002527}
2528
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002529/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2530/// interface declaration.
2531const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2532 const ObjCInterfaceDecl *OID) const {
2533 const llvm::Type *InterfaceTy =
2534 CGM.getTypes().ConvertType(
2535 CGM.getContext().getObjCInterfaceType(
2536 const_cast<ObjCInterfaceDecl*>(OID)));
2537 const llvm::StructLayout *Layout =
2538 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2539 return Layout;
2540}
2541
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002542/// GetIvarLayoutName - Returns a unique constant for the given
2543/// ivar layout bitmap.
2544llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2545 const ObjCCommonTypesHelper &ObjCTypes) {
2546 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2547}
2548
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002549void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2550 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002551 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002552 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002553 unsigned int BytePos, bool ForStrongLayout,
2554 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002555 bool IsUnion = (RD && RD->isUnion());
2556 uint64_t MaxUnionIvarSize = 0;
2557 uint64_t MaxSkippedUnionIvarSize = 0;
2558 FieldDecl *MaxField = 0;
2559 FieldDecl *MaxSkippedField = 0;
Chris Lattnerf1690852009-03-31 08:48:01 +00002560 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002561 if (RecFields.empty())
2562 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002563 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002564 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002565 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2566 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2567
2568 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2569
2570 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002571 FieldDecl *Field = RecFields[i];
2572 // Skip over unnamed or bitfields
2573 if (!Field->getIdentifier() || Field->isBitField())
2574 continue;
2575 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002576 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002577 if (FQT->isUnionType())
2578 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002579 else
2580 assert(FQT->isRecordType() &&
2581 "only union/record is supported for ivar layout bitmap");
2582
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002583 const RecordType *RT = FQT->getAsRecordType();
2584 const RecordDecl *RD = RT->getDecl();
2585 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002586 TmpRecFields.append(RD->field_begin(), RD->field_end());
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002587 // FIXME - Is Layout correct?
Chris Lattnerf1690852009-03-31 08:48:01 +00002588 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002589 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002590 ForStrongLayout, Index, SkIndex,
2591 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002592 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002593 continue;
2594 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002595
2596 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002597 const ConstantArrayType *CArray =
2598 dyn_cast_or_null<ConstantArrayType>(Array);
2599 assert(CArray && "only array with know element size is supported");
2600 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002601 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2602 const ConstantArrayType *CArray =
2603 dyn_cast_or_null<ConstantArrayType>(Array);
2604 FQT = CArray->getElementType();
2605 }
2606
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002607 assert(!FQT->isUnionType() &&
2608 "layout for array of unions not supported");
2609 if (FQT->isRecordType()) {
2610 uint64_t ElCount = CArray->getSize().getZExtValue();
2611 int OldIndex = Index;
2612 int OldSkIndex = SkIndex;
2613
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002614 // FIXME - Use a common routine with the above!
2615 const RecordType *RT = FQT->getAsRecordType();
2616 const RecordDecl *RD = RT->getDecl();
2617 // FIXME - Find a more efficiant way of passing records down.
Chris Lattnerf1690852009-03-31 08:48:01 +00002618 TmpRecFields.append(RD->field_begin(), RD->field_end());
2619
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002620 BuildAggrIvarLayout(OI, Layout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002621 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002622 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002623 ForStrongLayout, Index, SkIndex,
2624 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002625 TmpRecFields.clear();
2626
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002627 // Replicate layout information for each array element. Note that
2628 // one element is already done.
2629 uint64_t ElIx = 1;
2630 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2631 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002632 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002633 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2634 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002635 GC_IVAR gcivar;
2636 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2637 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2638 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002639 }
2640
Chris Lattnerf1690852009-03-31 08:48:01 +00002641 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002642 GC_IVAR skivar;
2643 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2644 skivar.ivar_size = SkipIvars[i].ivar_size;
2645 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002646 }
2647 }
2648 continue;
2649 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002650 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002651 // At this point, we are done with Record/Union and array there of.
2652 // For other arrays we are down to its element type.
2653 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2654 do {
2655 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2656 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2657 break;
2658 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002659 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002660 GCAttr = QualType::Strong;
2661 break;
2662 }
2663 else if (const PointerType *PT = FQT->getAsPointerType()) {
2664 FQT = PT->getPointeeType();
2665 }
2666 else {
2667 break;
2668 }
2669 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00002670
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002671 if ((ForStrongLayout && GCAttr == QualType::Strong)
2672 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2673 if (IsUnion)
2674 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002675 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2676 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002677 if (UnionIvarSize > MaxUnionIvarSize)
2678 {
2679 MaxUnionIvarSize = UnionIvarSize;
2680 MaxField = Field;
2681 }
2682 }
2683 else
2684 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002685 GC_IVAR gcivar;
2686 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2687 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2688 WordSizeInBits;
2689 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002690 }
2691 }
2692 else if ((ForStrongLayout &&
2693 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2694 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2695 if (IsUnion)
2696 {
2697 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2698 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2699 {
2700 MaxSkippedUnionIvarSize = UnionIvarSize;
2701 MaxSkippedField = Field;
2702 }
2703 }
2704 else
2705 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002706 GC_IVAR skivar;
2707 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2708 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2709 WordSizeInBits;
2710 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002711 }
2712 }
2713 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002714 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002715 GC_IVAR gcivar;
2716 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2717 gcivar.ivar_size = MaxUnionIvarSize;
2718 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002719 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002720
2721 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002722 GC_IVAR skivar;
2723 skivar.ivar_bytepos = BytePos +
2724 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2725 skivar.ivar_size = MaxSkippedUnionIvarSize;
2726 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002727 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002728}
2729
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002730static int
Chris Lattnerf1690852009-03-31 08:48:01 +00002731IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002732{
2733 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2734 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2735
2736 if (sa < sb)
2737 return -1;
2738 if (sa > sb)
2739 return 1;
2740 return 0;
2741}
2742
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002743/// BuildIvarLayout - Builds ivar layout bitmap for the class
2744/// implementation for the __strong or __weak case.
2745/// The layout map displays which words in ivar list must be skipped
2746/// and which must be scanned by GC (see below). String is built of bytes.
2747/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2748/// of words to skip and right nibble is count of words to scan. So, each
2749/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2750/// represented by a 0x00 byte which also ends the string.
2751/// 1. when ForStrongLayout is true, following ivars are scanned:
2752/// - id, Class
2753/// - object *
2754/// - __strong anything
2755///
2756/// 2. When ForStrongLayout is false, following ivars are scanned:
2757/// - __weak anything
2758///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002759llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002760 const ObjCImplementationDecl *OMD,
2761 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002762 int Index = -1;
2763 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002764 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002765 int SkipScan;
2766 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002767 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2768 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2769 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002770
Chris Lattnerf1690852009-03-31 08:48:01 +00002771 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002772 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002773 CGM.getContext().CollectObjCIvars(OI, RecFields);
2774 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002775 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00002776
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002777 SkipIvars.clear();
2778 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002779
2780 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Chris Lattnerf1690852009-03-31 08:48:01 +00002781 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
2782 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002783 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002784 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002785
2786 // Sort on byte position in case we encounterred a union nested in
2787 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002788 if (hasUnion && !IvarsInfo.empty())
2789 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2790 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002791 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2792
2793 // Build the string of skip/scan nibbles
2794 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002795 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002796 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002797 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002798 if (IvarsInfo[0].ivar_bytepos == 0) {
2799 WordsToSkip = 0;
2800 WordsToScan = IvarsInfo[0].ivar_size;
2801 }
2802 else {
2803 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2804 WordsToScan = IvarsInfo[0].ivar_size;
2805 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002806 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002807 {
2808 unsigned int TailPrevGCObjC =
2809 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2810 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2811 {
2812 // consecutive 'scanned' object pointers.
2813 WordsToScan += IvarsInfo[i].ivar_size;
2814 }
2815 else
2816 {
2817 // Skip over 'gc'able object pointer which lay over each other.
2818 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2819 continue;
2820 // Must skip over 1 or more words. We save current skip/scan values
2821 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002822 SKIP_SCAN SkScan;
2823 SkScan.skip = WordsToSkip;
2824 SkScan.scan = WordsToScan;
2825 SkipScanIvars.push_back(SkScan); ++SkipScan;
2826
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002827 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002828 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2829 SkScan.scan = 0;
2830 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002831 WordsToSkip = 0;
2832 WordsToScan = IvarsInfo[i].ivar_size;
2833 }
2834 }
2835 if (WordsToScan > 0)
2836 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002837 SKIP_SCAN SkScan;
2838 SkScan.skip = WordsToSkip;
2839 SkScan.scan = WordsToScan;
2840 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002841 }
2842
2843 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002844 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002845 {
2846 int LastByteSkipped =
2847 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2848 int LastByteScanned =
2849 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2850 BytesSkipped = (LastByteSkipped > LastByteScanned);
2851 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2852 if (BytesSkipped)
2853 {
2854 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002855 SKIP_SCAN SkScan;
2856 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2857 SkScan.scan = 0;
2858 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002859 }
2860 }
2861 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2862 // as 0xMN.
2863 for (int i = 0; i <= SkipScan; i++)
2864 {
2865 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2866 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2867 // 0xM0 followed by 0x0N detected.
2868 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2869 for (int j = i+1; j < SkipScan; j++)
2870 SkipScanIvars[j] = SkipScanIvars[j+1];
2871 --SkipScan;
2872 }
2873 }
2874
2875 // Generate the string.
2876 std::string BitMap;
2877 for (int i = 0; i <= SkipScan; i++)
2878 {
2879 unsigned char byte;
2880 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2881 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2882 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2883 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2884
2885 if (skip_small > 0 || skip_big > 0)
2886 BytesSkipped = true;
2887 // first skip big.
2888 for (unsigned int ix = 0; ix < skip_big; ix++)
2889 BitMap += (unsigned char)(0xf0);
2890
2891 // next (skip small, scan)
2892 if (skip_small)
2893 {
2894 byte = skip_small << 4;
2895 if (scan_big > 0)
2896 {
2897 byte |= 0xf;
2898 --scan_big;
2899 }
2900 else if (scan_small)
2901 {
2902 byte |= scan_small;
2903 scan_small = 0;
2904 }
2905 BitMap += byte;
2906 }
2907 // next scan big
2908 for (unsigned int ix = 0; ix < scan_big; ix++)
2909 BitMap += (unsigned char)(0x0f);
2910 // last scan small
2911 if (scan_small)
2912 {
2913 byte = scan_small;
2914 BitMap += byte;
2915 }
2916 }
2917 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002918 unsigned char zero = 0;
2919 BitMap += zero;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002920 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2921 // final layout.
2922 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002923 return llvm::Constant::getNullValue(PtrTy);
2924 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2925 llvm::ConstantArray::get(BitMap.c_str()),
2926 "__TEXT,__cstring,cstring_literals",
2927 0, true);
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002928 // FIXME. Need a commomand-line option for this eventually.
2929 if (ForStrongLayout)
2930 printf("\nstrong ivar layout: ");
2931 else
2932 printf("\nweak ivar layout: ");
2933 const unsigned char *s = (unsigned char*)BitMap.c_str();
2934 for (unsigned i = 0; i < BitMap.size(); i++)
Fariborz Jahaniandbf15cb2009-03-26 19:10:36 +00002935 if (!(s[i] & 0xf0))
2936 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2937 else
2938 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002939 printf("\n");
2940
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002941 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002942}
2943
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002944llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002945 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2946
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002947 // FIXME: Avoid std::string copying.
2948 if (!Entry)
2949 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2950 llvm::ConstantArray::get(Sel.getAsString()),
2951 "__TEXT,__cstring,cstring_literals",
2952 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002953
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002954 return getConstantGEP(Entry, 0, 0);
2955}
2956
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002957// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002958llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002959 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2960}
2961
2962// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002963llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002964 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2965}
2966
Devang Patel7794bb82009-03-04 18:21:39 +00002967llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2968 std::string TypeStr;
2969 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2970
2971 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002972
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002973 if (!Entry)
2974 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2975 llvm::ConstantArray::get(TypeStr),
2976 "__TEXT,__cstring,cstring_literals",
2977 0, true);
2978
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002979 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002980}
2981
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002982llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002983 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002984 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2985 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002986
2987 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2988
2989 if (!Entry) {
2990 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2991 Entry =
2992 new llvm::GlobalVariable(C->getType(), false,
2993 llvm::GlobalValue::InternalLinkage,
2994 C, "\01L_OBJC_METH_VAR_TYPE_",
2995 &CGM.getModule());
2996 Entry->setSection("__TEXT,__cstring,cstring_literals");
2997 UsedGlobals.push_back(Entry);
2998 }
2999
3000 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003001}
3002
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003003// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003004llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003005 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3006
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003007 if (!Entry)
3008 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3009 llvm::ConstantArray::get(Ident->getName()),
3010 "__TEXT,__cstring,cstring_literals",
3011 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003012
3013 return getConstantGEP(Entry, 0, 0);
3014}
3015
3016// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003017// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003018llvm::Constant *
3019 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3020 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003021 std::string TypeStr;
3022 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003023 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3024}
3025
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003026void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3027 const ObjCContainerDecl *CD,
3028 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003029 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00003030 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00003031 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003032 assert (CD && "Missing container decl in GetNameForMethod");
3033 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00003034 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
3035 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00003036 NameOut += ' ';
3037 NameOut += D->getSelector().getAsString();
3038 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003039}
3040
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003041/// GetFirstIvarInRecord - This routine returns the record for the
3042/// implementation of the fiven class OID. It also returns field
3043/// corresponding to the first ivar in the class in FIV. It also
3044/// returns the one before the first ivar.
3045///
3046const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
3047 const ObjCInterfaceDecl *OID,
3048 RecordDecl::field_iterator &FIV,
3049 RecordDecl::field_iterator &PIV) {
3050 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3051 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3052 RecordDecl::field_iterator ifield = RD->field_begin();
3053 RecordDecl::field_iterator pfield = RD->field_end();
3054 while (countSuperClassIvars-- > 0) {
3055 pfield = ifield;
3056 ++ifield;
3057 }
3058 FIV = ifield;
3059 PIV = pfield;
3060 return RD;
3061}
3062
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003063void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003064 EmitModuleInfo();
3065
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003066 // Emit the dummy bodies for any protocols which were referenced but
3067 // never defined.
3068 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3069 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3070 if (i->second->hasInitializer())
3071 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003072
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003073 std::vector<llvm::Constant*> Values(5);
3074 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3075 Values[1] = GetClassName(i->first);
3076 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3077 Values[3] = Values[4] =
3078 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3079 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3080 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3081 Values));
3082 }
3083
3084 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003085 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003086 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003087 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003088 }
3089
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003090 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003091 llvm::GlobalValue *GV =
3092 new llvm::GlobalVariable(AT, false,
3093 llvm::GlobalValue::AppendingLinkage,
3094 llvm::ConstantArray::get(AT, Used),
3095 "llvm.used",
3096 &CGM.getModule());
3097
3098 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003099
3100 // Add assembler directives to add lazy undefined symbol references
3101 // for classes which are referenced but not defined. This is
3102 // important for correct linker interaction.
3103
3104 // FIXME: Uh, this isn't particularly portable.
3105 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003106
3107 if (!CGM.getModule().getModuleInlineAsm().empty())
3108 s << "\n";
3109
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003110 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3111 e = LazySymbols.end(); i != e; ++i) {
3112 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3113 }
3114 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3115 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003116 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003117 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3118 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003119
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003120 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003121}
3122
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003123CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003124 : CGObjCCommonMac(cgm),
3125 ObjCTypes(cgm)
3126{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003127 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003128 ObjCABI = 2;
3129}
3130
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003131/* *** */
3132
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003133ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3134: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003135{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003136 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3137 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003138
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003139 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003140 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003141 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003142 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003143 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3144
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003145 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003146 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003147 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003148
3149 // FIXME: It would be nice to unify this with the opaque type, so
3150 // that the IR comes out a bit cleaner.
3151 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3152 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003153
3154 // I'm not sure I like this. The implicit coordination is a bit
3155 // gross. We should solve this in a reasonable fashion because this
3156 // is a pretty common task (match some runtime data structure with
3157 // an LLVM data structure).
3158
3159 // FIXME: This is leaked.
3160 // FIXME: Merge with rewriter code?
3161
3162 // struct _objc_super {
3163 // id self;
3164 // Class cls;
3165 // }
3166 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3167 SourceLocation(),
3168 &Ctx.Idents.get("_objc_super"));
3169 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3170 Ctx.getObjCIdType(), 0, false));
3171 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3172 Ctx.getObjCClassType(), 0, false));
3173 RD->completeDefinition(Ctx);
3174
3175 SuperCTy = Ctx.getTagDeclType(RD);
3176 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3177
3178 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003179 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3180
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003181 // struct _prop_t {
3182 // char *name;
3183 // char *attributes;
3184 // }
3185 PropertyTy = llvm::StructType::get(Int8PtrTy,
3186 Int8PtrTy,
3187 NULL);
3188 CGM.getModule().addTypeName("struct._prop_t",
3189 PropertyTy);
3190
3191 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003192 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003193 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003194 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003195 // }
3196 PropertyListTy = llvm::StructType::get(IntTy,
3197 IntTy,
3198 llvm::ArrayType::get(PropertyTy, 0),
3199 NULL);
3200 CGM.getModule().addTypeName("struct._prop_list_t",
3201 PropertyListTy);
3202 // struct _prop_list_t *
3203 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3204
3205 // struct _objc_method {
3206 // SEL _cmd;
3207 // char *method_type;
3208 // char *_imp;
3209 // }
3210 MethodTy = llvm::StructType::get(SelectorPtrTy,
3211 Int8PtrTy,
3212 Int8PtrTy,
3213 NULL);
3214 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003215
3216 // struct _objc_cache *
3217 CacheTy = llvm::OpaqueType::get();
3218 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3219 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003220
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003221 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003222
3223 QualType IdType = Ctx.getObjCIdType();
3224 QualType SelType = Ctx.getObjCSelType();
3225 llvm::SmallVector<QualType,16> Params;
3226 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003227
3228 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003229 Params.push_back(IdType);
3230 Params.push_back(SelType);
3231 Params.push_back(Ctx.LongTy);
3232 Params.push_back(Ctx.BoolTy);
3233 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3234 false);
3235 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003236
3237 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3238 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003239 Params.push_back(IdType);
3240 Params.push_back(SelType);
3241 Params.push_back(Ctx.LongTy);
3242 Params.push_back(IdType);
3243 Params.push_back(Ctx.BoolTy);
3244 Params.push_back(Ctx.BoolTy);
3245 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3246 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3247
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003248 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003249
3250 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003251 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003252 Params.push_back(IdType);
3253 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3254 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3255 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003256
3257 // gc's API
3258 // id objc_read_weak (id *)
3259 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003260 Params.push_back(Ctx.getPointerType(IdType));
3261 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3262 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3263
3264 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003265 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003266 Params.push_back(IdType);
3267 Params.push_back(Ctx.getPointerType(IdType));
3268
3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3270 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3271 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3272 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3273 GcAssignStrongCastFn =
3274 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003275
3276 // void objc_exception_throw(id)
3277 Params.clear();
3278 Params.push_back(IdType);
3279
3280 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003281 ExceptionThrowFn =
3282 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003283
3284 // synchronized APIs
3285 // void objc_sync_enter (id)
3286 // void objc_sync_exit (id)
3287 Params.clear();
3288 Params.push_back(IdType);
3289
3290 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3291 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
3292 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003293}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003294
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003295ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3296 : ObjCCommonTypesHelper(cgm)
3297{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003298 // struct _objc_method_description {
3299 // SEL name;
3300 // char *types;
3301 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003302 MethodDescriptionTy =
3303 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003304 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003305 NULL);
3306 CGM.getModule().addTypeName("struct._objc_method_description",
3307 MethodDescriptionTy);
3308
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003309 // struct _objc_method_description_list {
3310 // int count;
3311 // struct _objc_method_description[1];
3312 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003313 MethodDescriptionListTy =
3314 llvm::StructType::get(IntTy,
3315 llvm::ArrayType::get(MethodDescriptionTy, 0),
3316 NULL);
3317 CGM.getModule().addTypeName("struct._objc_method_description_list",
3318 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003319
3320 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003321 MethodDescriptionListPtrTy =
3322 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3323
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003324 // Protocol description structures
3325
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003326 // struct _objc_protocol_extension {
3327 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3328 // struct _objc_method_description_list *optional_instance_methods;
3329 // struct _objc_method_description_list *optional_class_methods;
3330 // struct _objc_property_list *instance_properties;
3331 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003332 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003333 llvm::StructType::get(IntTy,
3334 MethodDescriptionListPtrTy,
3335 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003336 PropertyListPtrTy,
3337 NULL);
3338 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3339 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003340
3341 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003342 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3343
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003344 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003345
3346 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3347 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3348
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003349 const llvm::Type *T =
3350 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3351 LongTy,
3352 llvm::ArrayType::get(ProtocolTyHolder, 0),
3353 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003354 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3355
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003356 // struct _objc_protocol {
3357 // struct _objc_protocol_extension *isa;
3358 // char *protocol_name;
3359 // struct _objc_protocol **_objc_protocol_list;
3360 // struct _objc_method_description_list *instance_methods;
3361 // struct _objc_method_description_list *class_methods;
3362 // }
3363 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003364 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003365 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3366 MethodDescriptionListPtrTy,
3367 MethodDescriptionListPtrTy,
3368 NULL);
3369 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3370
3371 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3372 CGM.getModule().addTypeName("struct._objc_protocol_list",
3373 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003374 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003375 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3376
3377 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003378 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003379 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003380
3381 // Class description structures
3382
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003383 // struct _objc_ivar {
3384 // char *ivar_name;
3385 // char *ivar_type;
3386 // int ivar_offset;
3387 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003388 IvarTy = llvm::StructType::get(Int8PtrTy,
3389 Int8PtrTy,
3390 IntTy,
3391 NULL);
3392 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3393
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003394 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003395 IvarListTy = llvm::OpaqueType::get();
3396 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3397 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3398
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003399 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003400 MethodListTy = llvm::OpaqueType::get();
3401 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3402 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3403
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003404 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003405 ClassExtensionTy =
3406 llvm::StructType::get(IntTy,
3407 Int8PtrTy,
3408 PropertyListPtrTy,
3409 NULL);
3410 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3411 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3412
3413 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3414
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003415 // struct _objc_class {
3416 // Class isa;
3417 // Class super_class;
3418 // char *name;
3419 // long version;
3420 // long info;
3421 // long instance_size;
3422 // struct _objc_ivar_list *ivars;
3423 // struct _objc_method_list *methods;
3424 // struct _objc_cache *cache;
3425 // struct _objc_protocol_list *protocols;
3426 // char *ivar_layout;
3427 // struct _objc_class_ext *ext;
3428 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003429 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3430 llvm::PointerType::getUnqual(ClassTyHolder),
3431 Int8PtrTy,
3432 LongTy,
3433 LongTy,
3434 LongTy,
3435 IvarListPtrTy,
3436 MethodListPtrTy,
3437 CachePtrTy,
3438 ProtocolListPtrTy,
3439 Int8PtrTy,
3440 ClassExtensionPtrTy,
3441 NULL);
3442 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3443
3444 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3445 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3446 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3447
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003448 // struct _objc_category {
3449 // char *category_name;
3450 // char *class_name;
3451 // struct _objc_method_list *instance_method;
3452 // struct _objc_method_list *class_method;
3453 // uint32_t size; // sizeof(struct _objc_category)
3454 // struct _objc_property_list *instance_properties;// category's @property
3455 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003456 CategoryTy = llvm::StructType::get(Int8PtrTy,
3457 Int8PtrTy,
3458 MethodListPtrTy,
3459 MethodListPtrTy,
3460 ProtocolListPtrTy,
3461 IntTy,
3462 PropertyListPtrTy,
3463 NULL);
3464 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3465
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003466 // Global metadata structures
3467
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003468 // struct _objc_symtab {
3469 // long sel_ref_cnt;
3470 // SEL *refs;
3471 // short cls_def_cnt;
3472 // short cat_def_cnt;
3473 // char *defs[cls_def_cnt + cat_def_cnt];
3474 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003475 SymtabTy = llvm::StructType::get(LongTy,
3476 SelectorPtrTy,
3477 ShortTy,
3478 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003479 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003480 NULL);
3481 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3482 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3483
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003484 // struct _objc_module {
3485 // long version;
3486 // long size; // sizeof(struct _objc_module)
3487 // char *name;
3488 // struct _objc_symtab* symtab;
3489 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003490 ModuleTy =
3491 llvm::StructType::get(LongTy,
3492 LongTy,
3493 Int8PtrTy,
3494 SymtabPtrTy,
3495 NULL);
3496 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003497
Daniel Dunbar49f66022008-09-24 03:38:44 +00003498 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003499
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003500 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003501 std::vector<const llvm::Type*> Params;
3502 Params.push_back(ObjectPtrTy);
3503 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003504 MessageSendFn =
3505 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3506 Params,
3507 true),
3508 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003509
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003510 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003511 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003512 Params.push_back(ObjectPtrTy);
3513 Params.push_back(SelectorPtrTy);
3514 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003515 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3516 Params,
3517 true),
3518 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003519
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003520 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003521 Params.clear();
3522 Params.push_back(ObjectPtrTy);
3523 Params.push_back(SelectorPtrTy);
3524 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003525 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003526 MessageSendFpretFn =
3527 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3528 Params,
3529 true),
3530 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003531
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003532 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003533 Params.clear();
3534 Params.push_back(SuperPtrTy);
3535 Params.push_back(SelectorPtrTy);
3536 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003537 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3538 Params,
3539 true),
3540 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003541
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003542 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3543 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003544 Params.clear();
3545 Params.push_back(Int8PtrTy);
3546 Params.push_back(SuperPtrTy);
3547 Params.push_back(SelectorPtrTy);
3548 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003549 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3550 Params,
3551 true),
3552 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003553
3554 // There is no objc_msgSendSuper_fpret? How can that work?
3555 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003556
Anders Carlsson124526b2008-09-09 10:10:21 +00003557 // FIXME: This is the size of the setjmp buffer and should be
3558 // target specific. 18 is what's used on 32-bit X86.
3559 uint64_t SetJmpBufferSize = 18;
3560
3561 // Exceptions
3562 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003563 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003564
3565 ExceptionDataTy =
3566 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3567 SetJmpBufferSize),
3568 StackPtrTy, NULL);
3569 CGM.getModule().addTypeName("struct._objc_exception_data",
3570 ExceptionDataTy);
3571
3572 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003573 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3574 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003575 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3576 Params,
3577 false),
3578 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003579 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3581 Params,
3582 false),
3583 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003584 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003585 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3586 Params,
3587 false),
3588 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003589
3590 Params.clear();
3591 Params.push_back(ClassPtrTy);
3592 Params.push_back(ObjectPtrTy);
3593 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003594 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3595 Params,
3596 false),
3597 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003598
Anders Carlsson124526b2008-09-09 10:10:21 +00003599 Params.clear();
3600 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3601 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003602 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3603 Params,
3604 false),
3605 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003606
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003607}
3608
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003609ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003610: ObjCCommonTypesHelper(cgm)
3611{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003612 // struct _method_list_t {
3613 // uint32_t entsize; // sizeof(struct _objc_method)
3614 // uint32_t method_count;
3615 // struct _objc_method method_list[method_count];
3616 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003617 MethodListnfABITy = llvm::StructType::get(IntTy,
3618 IntTy,
3619 llvm::ArrayType::get(MethodTy, 0),
3620 NULL);
3621 CGM.getModule().addTypeName("struct.__method_list_t",
3622 MethodListnfABITy);
3623 // struct method_list_t *
3624 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003625
3626 // struct _protocol_t {
3627 // id isa; // NULL
3628 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003629 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003630 // const struct method_list_t * const instance_methods;
3631 // const struct method_list_t * const class_methods;
3632 // const struct method_list_t *optionalInstanceMethods;
3633 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003634 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003635 // const uint32_t size; // sizeof(struct _protocol_t)
3636 // const uint32_t flags; // = 0
3637 // }
3638
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003639 // Holder for struct _protocol_list_t *
3640 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3641
3642 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3643 Int8PtrTy,
3644 llvm::PointerType::getUnqual(
3645 ProtocolListTyHolder),
3646 MethodListnfABIPtrTy,
3647 MethodListnfABIPtrTy,
3648 MethodListnfABIPtrTy,
3649 MethodListnfABIPtrTy,
3650 PropertyListPtrTy,
3651 IntTy,
3652 IntTy,
3653 NULL);
3654 CGM.getModule().addTypeName("struct._protocol_t",
3655 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003656
3657 // struct _protocol_t*
3658 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003659
Fariborz Jahanianda320092009-01-29 19:24:30 +00003660 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003661 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003662 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003663 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003664 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3665 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003666 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003667 NULL);
3668 CGM.getModule().addTypeName("struct._objc_protocol_list",
3669 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003670 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3671 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003672
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003673 // struct _objc_protocol_list*
3674 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003675
3676 // struct _ivar_t {
3677 // unsigned long int *offset; // pointer to ivar offset location
3678 // char *name;
3679 // char *type;
3680 // uint32_t alignment;
3681 // uint32_t size;
3682 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003683 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3684 Int8PtrTy,
3685 Int8PtrTy,
3686 IntTy,
3687 IntTy,
3688 NULL);
3689 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3690
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003691 // struct _ivar_list_t {
3692 // uint32 entsize; // sizeof(struct _ivar_t)
3693 // uint32 count;
3694 // struct _iver_t list[count];
3695 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003696 IvarListnfABITy = llvm::StructType::get(IntTy,
3697 IntTy,
3698 llvm::ArrayType::get(
3699 IvarnfABITy, 0),
3700 NULL);
3701 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3702
3703 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003704
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003705 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003706 // uint32_t const flags;
3707 // uint32_t const instanceStart;
3708 // uint32_t const instanceSize;
3709 // uint32_t const reserved; // only when building for 64bit targets
3710 // const uint8_t * const ivarLayout;
3711 // const char *const name;
3712 // const struct _method_list_t * const baseMethods;
3713 // const struct _objc_protocol_list *const baseProtocols;
3714 // const struct _ivar_list_t *const ivars;
3715 // const uint8_t * const weakIvarLayout;
3716 // const struct _prop_list_t * const properties;
3717 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003718
3719 // FIXME. Add 'reserved' field in 64bit abi mode!
3720 ClassRonfABITy = llvm::StructType::get(IntTy,
3721 IntTy,
3722 IntTy,
3723 Int8PtrTy,
3724 Int8PtrTy,
3725 MethodListnfABIPtrTy,
3726 ProtocolListnfABIPtrTy,
3727 IvarListnfABIPtrTy,
3728 Int8PtrTy,
3729 PropertyListPtrTy,
3730 NULL);
3731 CGM.getModule().addTypeName("struct._class_ro_t",
3732 ClassRonfABITy);
3733
3734 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3735 std::vector<const llvm::Type*> Params;
3736 Params.push_back(ObjectPtrTy);
3737 Params.push_back(SelectorPtrTy);
3738 ImpnfABITy = llvm::PointerType::getUnqual(
3739 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3740
3741 // struct _class_t {
3742 // struct _class_t *isa;
3743 // struct _class_t * const superclass;
3744 // void *cache;
3745 // IMP *vtable;
3746 // struct class_ro_t *ro;
3747 // }
3748
3749 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3750 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3751 llvm::PointerType::getUnqual(ClassTyHolder),
3752 CachePtrTy,
3753 llvm::PointerType::getUnqual(ImpnfABITy),
3754 llvm::PointerType::getUnqual(
3755 ClassRonfABITy),
3756 NULL);
3757 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3758
3759 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3760 ClassnfABITy);
3761
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003762 // LLVM for struct _class_t *
3763 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3764
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003765 // struct _category_t {
3766 // const char * const name;
3767 // struct _class_t *const cls;
3768 // const struct _method_list_t * const instance_methods;
3769 // const struct _method_list_t * const class_methods;
3770 // const struct _protocol_list_t * const protocols;
3771 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003772 // }
3773 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003774 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003775 MethodListnfABIPtrTy,
3776 MethodListnfABIPtrTy,
3777 ProtocolListnfABIPtrTy,
3778 PropertyListPtrTy,
3779 NULL);
3780 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003781
3782 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003783 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3784 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003785
3786 // MessageRefTy - LLVM for:
3787 // struct _message_ref_t {
3788 // IMP messenger;
3789 // SEL name;
3790 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003791
3792 // First the clang type for struct _message_ref_t
3793 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3794 SourceLocation(),
3795 &Ctx.Idents.get("_message_ref_t"));
3796 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3797 Ctx.VoidPtrTy, 0, false));
3798 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3799 Ctx.getObjCSelType(), 0, false));
3800 RD->completeDefinition(Ctx);
3801
3802 MessageRefCTy = Ctx.getTagDeclType(RD);
3803 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3804 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003805
3806 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3807 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3808
3809 // SuperMessageRefTy - LLVM for:
3810 // struct _super_message_ref_t {
3811 // SUPER_IMP messenger;
3812 // SEL name;
3813 // };
3814 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3815 SelectorPtrTy,
3816 NULL);
3817 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3818
3819 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3820 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3821
3822 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3823 Params.clear();
3824 Params.push_back(ObjectPtrTy);
3825 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003826 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3827 Params,
3828 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003829 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003830 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003831 "objc_msgSend_fixup");
3832
3833 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3834 MessageSendFpretFixupFn =
3835 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3836 Params,
3837 true),
3838 "objc_msgSend_fpret_fixup");
3839
3840 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3841 MessageSendStretFixupFn =
3842 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3843 Params,
3844 true),
3845 "objc_msgSend_stret_fixup");
3846
3847 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3848 MessageSendIdFixupFn =
3849 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3850 Params,
3851 true),
3852 "objc_msgSendId_fixup");
3853
3854
3855 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3856 MessageSendIdStretFixupFn =
3857 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3858 Params,
3859 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003860 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003861
3862 // id objc_msgSendSuper2_fixup (struct objc_super *,
3863 // struct _super_message_ref_t*, ...)
3864 Params.clear();
3865 Params.push_back(SuperPtrTy);
3866 Params.push_back(SuperMessageRefPtrTy);
3867 MessageSendSuper2FixupFn =
3868 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3869 Params,
3870 true),
3871 "objc_msgSendSuper2_fixup");
3872
3873
3874 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3875 // struct _super_message_ref_t*, ...)
3876 MessageSendSuper2StretFixupFn =
3877 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3878 Params,
3879 true),
3880 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003881
3882 Params.clear();
3883 llvm::Constant *Personality =
3884 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3885 Params,
3886 true),
3887 "__objc_personality_v0");
3888 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3889
3890 Params.clear();
3891 Params.push_back(Int8PtrTy);
3892 UnwindResumeOrRethrowFn =
3893 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3894 Params,
3895 false),
3896 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003897 ObjCBeginCatchFn =
3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3899 Params,
3900 false),
3901 "objc_begin_catch");
3902
3903 Params.clear();
3904 ObjCEndCatchFn =
3905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3906 Params,
3907 false),
3908 "objc_end_catch");
3909
3910 // struct objc_typeinfo {
3911 // const void** vtable; // objc_ehtype_vtable + 2
3912 // const char* name; // c++ typeinfo string
3913 // Class cls;
3914 // };
3915 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3916 Int8PtrTy,
3917 ClassnfABIPtrTy,
3918 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003919 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003920 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003921}
3922
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003923llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3924 FinishNonFragileABIModule();
3925
3926 return NULL;
3927}
3928
3929void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3930 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003931
3932 // Build list of all implemented classe addresses in array
3933 // L_OBJC_LABEL_CLASS_$.
3934 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3935 // list of 'nonlazy' implementations (defined as those with a +load{}
3936 // method!!).
3937 unsigned NumClasses = DefinedClasses.size();
3938 if (NumClasses) {
3939 std::vector<llvm::Constant*> Symbols(NumClasses);
3940 for (unsigned i=0; i<NumClasses; i++)
3941 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3942 ObjCTypes.Int8PtrTy);
3943 llvm::Constant* Init =
3944 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3945 NumClasses),
3946 Symbols);
3947
3948 llvm::GlobalVariable *GV =
3949 new llvm::GlobalVariable(Init->getType(), false,
3950 llvm::GlobalValue::InternalLinkage,
3951 Init,
3952 "\01L_OBJC_LABEL_CLASS_$",
3953 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003954 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003955 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3956 UsedGlobals.push_back(GV);
3957 }
3958
3959 // Build list of all implemented category addresses in array
3960 // L_OBJC_LABEL_CATEGORY_$.
3961 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3962 // list of 'nonlazy' category implementations (defined as those with a +load{}
3963 // method!!).
3964 unsigned NumCategory = DefinedCategories.size();
3965 if (NumCategory) {
3966 std::vector<llvm::Constant*> Symbols(NumCategory);
3967 for (unsigned i=0; i<NumCategory; i++)
3968 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3969 ObjCTypes.Int8PtrTy);
3970 llvm::Constant* Init =
3971 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3972 NumCategory),
3973 Symbols);
3974
3975 llvm::GlobalVariable *GV =
3976 new llvm::GlobalVariable(Init->getType(), false,
3977 llvm::GlobalValue::InternalLinkage,
3978 Init,
3979 "\01L_OBJC_LABEL_CATEGORY_$",
3980 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003981 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003982 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3983 UsedGlobals.push_back(GV);
3984 }
3985
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003986 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3987 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3988 std::vector<llvm::Constant*> Values(2);
3989 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003990 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003991 // FIXME: Fix and continue?
3992 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3993 flags |= eImageInfo_GarbageCollected;
3994 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3995 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003996 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003997 llvm::Constant* Init = llvm::ConstantArray::get(
3998 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3999 Values);
4000 llvm::GlobalVariable *IMGV =
4001 new llvm::GlobalVariable(Init->getType(), false,
4002 llvm::GlobalValue::InternalLinkage,
4003 Init,
4004 "\01L_OBJC_IMAGE_INFO",
4005 &CGM.getModule());
4006 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4007 UsedGlobals.push_back(IMGV);
4008
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004009 std::vector<llvm::Constant*> Used;
4010 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4011 e = UsedGlobals.end(); i != e; ++i) {
4012 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4013 }
4014
4015 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4016 llvm::GlobalValue *GV =
4017 new llvm::GlobalVariable(AT, false,
4018 llvm::GlobalValue::AppendingLinkage,
4019 llvm::ConstantArray::get(AT, Used),
4020 "llvm.used",
4021 &CGM.getModule());
4022
4023 GV->setSection("llvm.metadata");
4024
4025}
4026
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004027// Metadata flags
4028enum MetaDataDlags {
4029 CLS = 0x0,
4030 CLS_META = 0x1,
4031 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004032 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004033 CLS_EXCEPTION = 0x20
4034};
4035/// BuildClassRoTInitializer - generate meta-data for:
4036/// struct _class_ro_t {
4037/// uint32_t const flags;
4038/// uint32_t const instanceStart;
4039/// uint32_t const instanceSize;
4040/// uint32_t const reserved; // only when building for 64bit targets
4041/// const uint8_t * const ivarLayout;
4042/// const char *const name;
4043/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004044/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004045/// const struct _ivar_list_t *const ivars;
4046/// const uint8_t * const weakIvarLayout;
4047/// const struct _prop_list_t * const properties;
4048/// }
4049///
4050llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4051 unsigned flags,
4052 unsigned InstanceStart,
4053 unsigned InstanceSize,
4054 const ObjCImplementationDecl *ID) {
4055 std::string ClassName = ID->getNameAsString();
4056 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4057 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4058 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4059 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4060 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004061 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004062 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004063 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004064 // const struct _method_list_t * const baseMethods;
4065 std::vector<llvm::Constant*> Methods;
4066 std::string MethodListName("\01l_OBJC_$_");
4067 if (flags & CLS_META) {
4068 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4069 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4070 e = ID->classmeth_end(); i != e; ++i) {
4071 // Class methods should always be defined.
4072 Methods.push_back(GetMethodConstant(*i));
4073 }
4074 } else {
4075 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4076 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4077 e = ID->instmeth_end(); i != e; ++i) {
4078 // Instance methods should always be defined.
4079 Methods.push_back(GetMethodConstant(*i));
4080 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004081 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4082 e = ID->propimpl_end(); i != e; ++i) {
4083 ObjCPropertyImplDecl *PID = *i;
4084
4085 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4086 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4087
4088 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4089 if (llvm::Constant *C = GetMethodConstant(MD))
4090 Methods.push_back(C);
4091 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4092 if (llvm::Constant *C = GetMethodConstant(MD))
4093 Methods.push_back(C);
4094 }
4095 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004096 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004097 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004098 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004099
4100 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4101 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4102 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4103 + OID->getNameAsString(),
4104 OID->protocol_begin(),
4105 OID->protocol_end());
4106
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004107 if (flags & CLS_META)
4108 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4109 else
4110 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004111 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004112 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004113 if (flags & CLS_META)
4114 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4115 else
4116 Values[ 9] =
4117 EmitPropertyList(
4118 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4119 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004120 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4121 Values);
4122 llvm::GlobalVariable *CLASS_RO_GV =
4123 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4124 llvm::GlobalValue::InternalLinkage,
4125 Init,
4126 (flags & CLS_META) ?
4127 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4128 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4129 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004130 CLASS_RO_GV->setAlignment(
4131 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004132 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004133 UsedGlobals.push_back(CLASS_RO_GV);
4134 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004135
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004136}
4137
4138/// BuildClassMetaData - This routine defines that to-level meta-data
4139/// for the given ClassName for:
4140/// struct _class_t {
4141/// struct _class_t *isa;
4142/// struct _class_t * const superclass;
4143/// void *cache;
4144/// IMP *vtable;
4145/// struct class_ro_t *ro;
4146/// }
4147///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004148llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4149 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004150 llvm::Constant *IsAGV,
4151 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004152 llvm::Constant *ClassRoGV,
4153 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004154 std::vector<llvm::Constant*> Values(5);
4155 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004156 Values[1] = SuperClassGV
4157 ? SuperClassGV
4158 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004159 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4160 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4161 Values[4] = ClassRoGV; // &CLASS_RO_GV
4162 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4163 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004164 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4165 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004166 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004167 GV->setAlignment(
4168 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004169 if (HiddenVisibility)
4170 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004171 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004172 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004173}
4174
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004175void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4176 std::string ClassName = ID->getNameAsString();
4177 if (!ObjCEmptyCacheVar) {
4178 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004179 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004180 false,
4181 llvm::GlobalValue::ExternalLinkage,
4182 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004183 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004184 &CGM.getModule());
4185 UsedGlobals.push_back(ObjCEmptyCacheVar);
4186
4187 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004188 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004189 false,
4190 llvm::GlobalValue::ExternalLinkage,
4191 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004192 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004193 &CGM.getModule());
4194 UsedGlobals.push_back(ObjCEmptyVtableVar);
4195 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004196 assert(ID->getClassInterface() &&
4197 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004198 uint32_t InstanceStart =
4199 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4200 uint32_t InstanceSize = InstanceStart;
4201 uint32_t flags = CLS_META;
4202 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
4203 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004204
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004205 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004206
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004207 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4208 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004209 flags |= OBJC2_CLS_HIDDEN;
4210 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004211 // class is root
4212 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004213 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4214 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004215 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004216 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004217 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4218 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4219 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004220 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004221 // work on super class metadata symbol.
4222 std::string SuperClassName =
4223 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004224 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004225 }
4226 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4227 InstanceStart,
4228 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004229 std::string TClassName = ObjCMetaClassName + ClassName;
4230 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004231 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4232 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004233
4234 // Metadata for the class
4235 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004236 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004237 flags |= OBJC2_CLS_HIDDEN;
4238 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004239 flags |= CLS_ROOT;
4240 SuperClassGV = 0;
4241 }
4242 else {
4243 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004244 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004245 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004246 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004247 }
Fariborz Jahanianebf9ed32009-03-20 20:48:19 +00004248 // FIXME: Gross
4249 ObjCInterfaceDecl *Interface =
4250 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
4251 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004252 InstanceStart = InstanceSize = 0;
4253 if (ObjCInterfaceDecl *OID =
4254 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4255 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004256 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004257
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004258 RecordDecl::field_iterator firstField, lastField;
4259 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004260
4261 for (RecordDecl::field_iterator e = RD->field_end(),
4262 ifield = firstField; ifield != e; ++ifield)
4263 lastField = ifield;
4264
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004265 if (lastField != RD->field_end()) {
4266 FieldDecl *Field = *lastField;
4267 const llvm::Type *FieldTy =
4268 CGM.getTypes().ConvertTypeForMem(Field->getType());
4269 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004270 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004271 if (firstField == RD->field_end())
4272 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004273 else {
4274 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004275 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004276 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004277 }
4278 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004279 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004280 InstanceStart,
4281 InstanceSize,
4282 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004283
4284 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004285 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004286 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4287 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004288 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004289}
4290
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004291/// GenerateProtocolRef - This routine is called to generate code for
4292/// a protocol reference expression; as in:
4293/// @code
4294/// @protocol(Proto1);
4295/// @endcode
4296/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4297/// which will hold address of the protocol meta-data.
4298///
4299llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4300 const ObjCProtocolDecl *PD) {
4301
4302 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4303 ObjCTypes.ExternalProtocolPtrTy);
4304
4305 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4306 ProtocolName += PD->getNameAsCString();
4307
4308 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4309 if (PTGV)
4310 return Builder.CreateLoad(PTGV, false, "tmp");
4311 PTGV = new llvm::GlobalVariable(
4312 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004313 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004314 Init,
4315 ProtocolName,
4316 &CGM.getModule());
4317 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4318 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4319 UsedGlobals.push_back(PTGV);
4320 return Builder.CreateLoad(PTGV, false, "tmp");
4321}
4322
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004323/// GenerateCategory - Build metadata for a category implementation.
4324/// struct _category_t {
4325/// const char * const name;
4326/// struct _class_t *const cls;
4327/// const struct _method_list_t * const instance_methods;
4328/// const struct _method_list_t * const class_methods;
4329/// const struct _protocol_list_t * const protocols;
4330/// const struct _prop_list_t * const properties;
4331/// }
4332///
4333void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4334{
4335 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004336 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4337 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004338 "_$_" + OCD->getNameAsString());
4339 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
4340
4341 std::vector<llvm::Constant*> Values(6);
4342 Values[0] = GetClassName(OCD->getIdentifier());
4343 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004344 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004345 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004346 std::vector<llvm::Constant*> Methods;
4347 std::string MethodListName(Prefix);
4348 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4349 "_$_" + OCD->getNameAsString();
4350
4351 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4352 e = OCD->instmeth_end(); i != e; ++i) {
4353 // Instance methods should always be defined.
4354 Methods.push_back(GetMethodConstant(*i));
4355 }
4356
4357 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004358 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004359 Methods);
4360
4361 MethodListName = Prefix;
4362 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4363 OCD->getNameAsString();
4364 Methods.clear();
4365 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4366 e = OCD->classmeth_end(); i != e; ++i) {
4367 // Class methods should always be defined.
4368 Methods.push_back(GetMethodConstant(*i));
4369 }
4370
4371 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004372 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004373 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004374 const ObjCCategoryDecl *Category =
4375 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004376 if (Category) {
4377 std::string ExtName(Interface->getNameAsString() + "_$_" +
4378 OCD->getNameAsString());
4379 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4380 + Interface->getNameAsString() + "_$_"
4381 + Category->getNameAsString(),
4382 Category->protocol_begin(),
4383 Category->protocol_end());
4384 Values[5] =
4385 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4386 OCD, Category, ObjCTypes);
4387 }
4388 else {
4389 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4390 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4391 }
4392
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004393 llvm::Constant *Init =
4394 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4395 Values);
4396 llvm::GlobalVariable *GCATV
4397 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4398 false,
4399 llvm::GlobalValue::InternalLinkage,
4400 Init,
4401 ExtCatName,
4402 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004403 GCATV->setAlignment(
4404 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004405 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004406 UsedGlobals.push_back(GCATV);
4407 DefinedCategories.push_back(GCATV);
4408}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004409
4410/// GetMethodConstant - Return a struct objc_method constant for the
4411/// given method if it has been defined. The result is null if the
4412/// method has not been defined. The return value has type MethodPtrTy.
4413llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4414 const ObjCMethodDecl *MD) {
4415 // FIXME: Use DenseMap::lookup
4416 llvm::Function *Fn = MethodDefinitions[MD];
4417 if (!Fn)
4418 return 0;
4419
4420 std::vector<llvm::Constant*> Method(3);
4421 Method[0] =
4422 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4423 ObjCTypes.SelectorPtrTy);
4424 Method[1] = GetMethodVarType(MD);
4425 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4426 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4427}
4428
4429/// EmitMethodList - Build meta-data for method declarations
4430/// struct _method_list_t {
4431/// uint32_t entsize; // sizeof(struct _objc_method)
4432/// uint32_t method_count;
4433/// struct _objc_method method_list[method_count];
4434/// }
4435///
4436llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4437 const std::string &Name,
4438 const char *Section,
4439 const ConstantVector &Methods) {
4440 // Return null for empty list.
4441 if (Methods.empty())
4442 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4443
4444 std::vector<llvm::Constant*> Values(3);
4445 // sizeof(struct _objc_method)
4446 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4447 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4448 // method_count
4449 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4450 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4451 Methods.size());
4452 Values[2] = llvm::ConstantArray::get(AT, Methods);
4453 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4454
4455 llvm::GlobalVariable *GV =
4456 new llvm::GlobalVariable(Init->getType(), false,
4457 llvm::GlobalValue::InternalLinkage,
4458 Init,
4459 Name,
4460 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004461 GV->setAlignment(
4462 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004463 GV->setSection(Section);
4464 UsedGlobals.push_back(GV);
4465 return llvm::ConstantExpr::getBitCast(GV,
4466 ObjCTypes.MethodListnfABIPtrTy);
4467}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004468
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004469/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4470/// the given ivar.
4471///
4472llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4473 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004474 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004475 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004476 Name += "\01_OBJC_IVAR_$_" +
4477 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004478 + Ivar->getNameAsString();
4479 llvm::GlobalVariable *IvarOffsetGV =
4480 CGM.getModule().getGlobalVariable(Name);
4481 if (!IvarOffsetGV)
4482 IvarOffsetGV =
4483 new llvm::GlobalVariable(ObjCTypes.LongTy,
4484 false,
4485 llvm::GlobalValue::ExternalLinkage,
4486 0,
4487 Name,
4488 &CGM.getModule());
4489 return IvarOffsetGV;
4490}
4491
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004492llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004493 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004494 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004495 unsigned long int Offset) {
4496
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004497 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004498 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004499 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004500 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004501
4502 llvm::GlobalVariable *IvarOffsetGV =
4503 CGM.getModule().getGlobalVariable(ExternalName);
4504 if (IvarOffsetGV) {
4505 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004506 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004507 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004508 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004509 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004510 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004511 return IvarOffsetGV;
4512 }
4513
4514 IvarOffsetGV =
4515 new llvm::GlobalVariable(Init->getType(),
4516 false,
4517 llvm::GlobalValue::ExternalLinkage,
4518 Init,
4519 ExternalName,
4520 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004521 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004522 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004523 // @private and @package have hidden visibility.
4524 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4525 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4526 if (!globalVisibility)
4527 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004528 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004529 if (IsClassHidden(ID))
4530 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004531
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004532 IvarOffsetGV->setSection("__DATA, __objc_const");
4533 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004534 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004535}
4536
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004537/// EmitIvarList - Emit the ivar list for the given
4538/// implementation. If ForClass is true the list of class ivars
4539/// (i.e. metaclass ivars) is emitted, otherwise the list of
4540/// interface ivars will be emitted. The return value has type
4541/// IvarListnfABIPtrTy.
4542/// struct _ivar_t {
4543/// unsigned long int *offset; // pointer to ivar offset location
4544/// char *name;
4545/// char *type;
4546/// uint32_t alignment;
4547/// uint32_t size;
4548/// }
4549/// struct _ivar_list_t {
4550/// uint32 entsize; // sizeof(struct _ivar_t)
4551/// uint32 count;
4552/// struct _iver_t list[count];
4553/// }
4554///
4555llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4556 const ObjCImplementationDecl *ID) {
4557
4558 std::vector<llvm::Constant*> Ivars, Ivar(5);
4559
4560 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4561 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4562
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004563 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004564 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004565
4566 RecordDecl::field_iterator i,p;
4567 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004568 // collect declared and synthesized ivars in a small vector.
4569 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4570 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4571 E = OID->ivar_end(); I != E; ++I)
4572 OIvars.push_back(*I);
4573 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(),
4574 E = OID->prop_end(); I != E; ++I)
4575 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4576 OIvars.push_back(IV);
4577 unsigned iv = 0;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004578 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004579 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004580 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian18191882009-03-31 18:11:23 +00004581 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004582 if (Field->getIdentifier())
4583 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4584 else
4585 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004586 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004587 const llvm::Type *FieldTy =
4588 CGM.getTypes().ConvertTypeForMem(Field->getType());
4589 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4590 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4591 Field->getType().getTypePtr()) >> 3;
4592 Align = llvm::Log2_32(Align);
4593 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004594 // NOTE. Size of a bitfield does not match gcc's, because of the way
4595 // bitfields are treated special in each. But I am told that 'size'
4596 // for bitfield ivars is ignored by the runtime so it does not matter.
4597 // (even if it matters, some day, there is enough info. to get the bitfield
4598 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004599 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4600 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4601 }
4602 // Return null for empty list.
4603 if (Ivars.empty())
4604 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4605 std::vector<llvm::Constant*> Values(3);
4606 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4607 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4608 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4609 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4610 Ivars.size());
4611 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4612 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4613 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4614 llvm::GlobalVariable *GV =
4615 new llvm::GlobalVariable(Init->getType(), false,
4616 llvm::GlobalValue::InternalLinkage,
4617 Init,
4618 Prefix + OID->getNameAsString(),
4619 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004620 GV->setAlignment(
4621 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004622 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004623
4624 UsedGlobals.push_back(GV);
4625 return llvm::ConstantExpr::getBitCast(GV,
4626 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004627}
4628
4629llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4630 const ObjCProtocolDecl *PD) {
4631 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4632
4633 if (!Entry) {
4634 // We use the initializer as a marker of whether this is a forward
4635 // reference or not. At module finalization we add the empty
4636 // contents for protocols which were referenced but never defined.
4637 Entry =
4638 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4639 llvm::GlobalValue::ExternalLinkage,
4640 0,
4641 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4642 &CGM.getModule());
4643 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4644 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004645 }
4646
4647 return Entry;
4648}
4649
4650/// GetOrEmitProtocol - Generate the protocol meta-data:
4651/// @code
4652/// struct _protocol_t {
4653/// id isa; // NULL
4654/// const char * const protocol_name;
4655/// const struct _protocol_list_t * protocol_list; // super protocols
4656/// const struct method_list_t * const instance_methods;
4657/// const struct method_list_t * const class_methods;
4658/// const struct method_list_t *optionalInstanceMethods;
4659/// const struct method_list_t *optionalClassMethods;
4660/// const struct _prop_list_t * properties;
4661/// const uint32_t size; // sizeof(struct _protocol_t)
4662/// const uint32_t flags; // = 0
4663/// }
4664/// @endcode
4665///
4666
4667llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4668 const ObjCProtocolDecl *PD) {
4669 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4670
4671 // Early exit if a defining object has already been generated.
4672 if (Entry && Entry->hasInitializer())
4673 return Entry;
4674
4675 const char *ProtocolName = PD->getNameAsCString();
4676
4677 // Construct method lists.
4678 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4679 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4680 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4681 e = PD->instmeth_end(); i != e; ++i) {
4682 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004683 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004684 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4685 OptInstanceMethods.push_back(C);
4686 } else {
4687 InstanceMethods.push_back(C);
4688 }
4689 }
4690
4691 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4692 e = PD->classmeth_end(); i != e; ++i) {
4693 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004694 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004695 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4696 OptClassMethods.push_back(C);
4697 } else {
4698 ClassMethods.push_back(C);
4699 }
4700 }
4701
4702 std::vector<llvm::Constant*> Values(10);
4703 // isa is NULL
4704 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4705 Values[1] = GetClassName(PD->getIdentifier());
4706 Values[2] = EmitProtocolList(
4707 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4708 PD->protocol_begin(),
4709 PD->protocol_end());
4710
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004711 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004712 + PD->getNameAsString(),
4713 "__DATA, __objc_const",
4714 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004715 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004716 + PD->getNameAsString(),
4717 "__DATA, __objc_const",
4718 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004719 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004720 + PD->getNameAsString(),
4721 "__DATA, __objc_const",
4722 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004723 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004724 + PD->getNameAsString(),
4725 "__DATA, __objc_const",
4726 OptClassMethods);
4727 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4728 0, PD, ObjCTypes);
4729 uint32_t Size =
4730 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4731 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4732 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4733 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4734 Values);
4735
4736 if (Entry) {
4737 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004738 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004739 Entry->setInitializer(Init);
4740 } else {
4741 Entry =
4742 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004743 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004744 Init,
4745 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4746 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004747 Entry->setAlignment(
4748 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004750 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004751 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4752
4753 // Use this protocol meta-data to build protocol list table in section
4754 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004755 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004756 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004757 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004758 Entry,
4759 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4760 +ProtocolName,
4761 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004762 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004763 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004764 PTGV->setSection("__DATA, __objc_protolist");
4765 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4766 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004767 return Entry;
4768}
4769
4770/// EmitProtocolList - Generate protocol list meta-data:
4771/// @code
4772/// struct _protocol_list_t {
4773/// long protocol_count; // Note, this is 32/64 bit
4774/// struct _protocol_t[protocol_count];
4775/// }
4776/// @endcode
4777///
4778llvm::Constant *
4779CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4780 ObjCProtocolDecl::protocol_iterator begin,
4781 ObjCProtocolDecl::protocol_iterator end) {
4782 std::vector<llvm::Constant*> ProtocolRefs;
4783
Fariborz Jahanianda320092009-01-29 19:24:30 +00004784 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004785 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004786 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4787
Daniel Dunbar948e2582009-02-15 07:36:20 +00004788 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004789 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4790 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004791 return llvm::ConstantExpr::getBitCast(GV,
4792 ObjCTypes.ProtocolListnfABIPtrTy);
4793
4794 for (; begin != end; ++begin)
4795 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4796
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 // This list is null terminated.
4798 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004799 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004800
4801 std::vector<llvm::Constant*> Values(2);
4802 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4803 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004804 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004805 ProtocolRefs.size()),
4806 ProtocolRefs);
4807
4808 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4809 GV = new llvm::GlobalVariable(Init->getType(), false,
4810 llvm::GlobalValue::InternalLinkage,
4811 Init,
4812 Name,
4813 &CGM.getModule());
4814 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004815 GV->setAlignment(
4816 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004817 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004818 return llvm::ConstantExpr::getBitCast(GV,
4819 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004820}
4821
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004822/// GetMethodDescriptionConstant - This routine build following meta-data:
4823/// struct _objc_method {
4824/// SEL _cmd;
4825/// char *method_type;
4826/// char *_imp;
4827/// }
4828
4829llvm::Constant *
4830CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4831 std::vector<llvm::Constant*> Desc(3);
4832 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4833 ObjCTypes.SelectorPtrTy);
4834 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004835 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004836 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4837 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4838}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004839
4840/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4841/// This code gen. amounts to generating code for:
4842/// @code
4843/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4844/// @encode
4845///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004846LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004847 CodeGen::CodeGenFunction &CGF,
4848 QualType ObjectTy,
4849 llvm::Value *BaseValue,
4850 const ObjCIvarDecl *Ivar,
4851 const FieldDecl *Field,
4852 unsigned CVRQualifiers) {
4853 assert(ObjectTy->isObjCInterfaceType() &&
4854 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004855 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004856 std::string ExternalName;
4857 llvm::GlobalVariable *IvarOffsetGV =
4858 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004859
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004860 // (char *) BaseValue
4861 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4862 ObjCTypes.Int8PtrTy);
4863 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4864 // (char*)BaseValue + Offset_symbol
4865 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4866 // (type *)((char*)BaseValue + Offset_symbol)
4867 const llvm::Type *IvarTy =
4868 CGM.getTypes().ConvertType(Ivar->getType());
4869 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4870 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004871
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004872 if (Ivar->isBitField()) {
4873 CodeGenTypes::BitFieldInfo bitFieldInfo =
4874 CGM.getTypes().getBitFieldInfo(Field);
4875 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4876 Field->getType()->isSignedIntegerType(),
4877 Field->getType().getCVRQualifiers()|CVRQualifiers);
4878 }
4879
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004880 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004881 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4882 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004883 LValue::SetObjCIvar(LV, true);
4884 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004885}
4886
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004887llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4888 CodeGen::CodeGenFunction &CGF,
4889 ObjCInterfaceDecl *Interface,
4890 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004891 std::string ExternalName;
4892 llvm::GlobalVariable *IvarOffsetGV =
4893 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4894
4895 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004896}
4897
Fariborz Jahanian46551122009-02-04 00:22:57 +00004898CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4899 CodeGen::CodeGenFunction &CGF,
4900 QualType ResultType,
4901 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004902 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004903 QualType Arg0Ty,
4904 bool IsSuper,
4905 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004906 // FIXME. Even though IsSuper is passes. This function doese not
4907 // handle calls to 'super' receivers.
4908 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004909 llvm::Value *Arg0 = Receiver;
4910 if (!IsSuper)
4911 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004912
4913 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004914 // FIXME. This is too much work to get the ABI-specific result type
4915 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004916 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4917 llvm::SmallVector<QualType, 16>());
4918 llvm::Constant *Fn;
4919 std::string Name("\01l_");
4920 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004921#if 0
4922 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004923 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4924 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4925 // FIXME. Is there a better way of getting these names.
4926 // They are available in RuntimeFunctions vector pair.
4927 Name += "objc_msgSendId_stret_fixup";
4928 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004929 else
4930#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004931 if (IsSuper) {
4932 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4933 Name += "objc_msgSendSuper2_stret_fixup";
4934 }
4935 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004936 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004937 Fn = ObjCTypes.MessageSendStretFixupFn;
4938 Name += "objc_msgSend_stret_fixup";
4939 }
4940 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004941 else if (ResultType->isFloatingType() &&
4942 // Selection of frret API only happens in 32bit nonfragile ABI.
4943 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004944 Fn = ObjCTypes.MessageSendFpretFixupFn;
4945 Name += "objc_msgSend_fpret_fixup";
4946 }
4947 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004948#if 0
4949// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4951 Fn = ObjCTypes.MessageSendIdFixupFn;
4952 Name += "objc_msgSendId_fixup";
4953 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004954 else
4955#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004956 if (IsSuper) {
4957 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4958 Name += "objc_msgSendSuper2_fixup";
4959 }
4960 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004961 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004962 Fn = ObjCTypes.MessageSendFixupFn;
4963 Name += "objc_msgSend_fixup";
4964 }
4965 }
4966 Name += '_';
4967 std::string SelName(Sel.getAsString());
4968 // Replace all ':' in selector name with '_' ouch!
4969 for(unsigned i = 0; i < SelName.size(); i++)
4970 if (SelName[i] == ':')
4971 SelName[i] = '_';
4972 Name += SelName;
4973 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4974 if (!GV) {
4975 // Build messafe ref table entry.
4976 std::vector<llvm::Constant*> Values(2);
4977 Values[0] = Fn;
4978 Values[1] = GetMethodVarName(Sel);
4979 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4980 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004981 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004982 Init,
4983 Name,
4984 &CGM.getModule());
4985 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4986 GV->setAlignment(
4987 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4988 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4989 UsedGlobals.push_back(GV);
4990 }
4991 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004992
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004993 CallArgList ActualArgs;
4994 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4995 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4996 ObjCTypes.MessageRefCPtrTy));
4997 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004998 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4999 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5000 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005001 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005002 Callee = CGF.Builder.CreateBitCast(Callee,
5003 llvm::PointerType::getUnqual(FTy));
5004 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005005}
5006
5007/// Generate code for a message send expression in the nonfragile abi.
5008CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5009 CodeGen::CodeGenFunction &CGF,
5010 QualType ResultType,
5011 Selector Sel,
5012 llvm::Value *Receiver,
5013 bool IsClassMessage,
5014 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005015 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005017 false, CallArgs);
5018}
5019
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005020llvm::GlobalVariable *
5021CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
5022 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5023
Daniel Dunbardfff2302009-03-02 05:18:14 +00005024 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005025 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5026 llvm::GlobalValue::ExternalLinkage,
5027 0, Name, &CGM.getModule());
5028 UsedGlobals.push_back(GV);
5029 }
5030
5031 return GV;
5032}
5033
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005034llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005035 const ObjCInterfaceDecl *ID,
5036 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005037
5038 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5039
5040 if (!Entry) {
5041 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005042 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005043 Entry =
5044 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5045 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005046 ClassGV,
5047 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
5048 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005049 &CGM.getModule());
5050 Entry->setAlignment(
5051 CGM.getTargetData().getPrefTypeAlignment(
5052 ObjCTypes.ClassnfABIPtrTy));
5053
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005054 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005055 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005056 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00005057 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005058 UsedGlobals.push_back(Entry);
5059 }
5060
5061 return Builder.CreateLoad(Entry, false, "tmp");
5062}
5063
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005064/// EmitMetaClassRef - Return a Value * of the address of _class_t
5065/// meta-data
5066///
5067llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5068 const ObjCInterfaceDecl *ID) {
5069 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5070 if (Entry)
5071 return Builder.CreateLoad(Entry, false, "tmp");
5072
5073 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00005074 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005075 Entry =
5076 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5077 llvm::GlobalValue::InternalLinkage,
5078 MetaClassGV,
5079 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5080 &CGM.getModule());
5081 Entry->setAlignment(
5082 CGM.getTargetData().getPrefTypeAlignment(
5083 ObjCTypes.ClassnfABIPtrTy));
5084
5085 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5086 UsedGlobals.push_back(Entry);
5087
5088 return Builder.CreateLoad(Entry, false, "tmp");
5089}
5090
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005091/// GetClass - Return a reference to the class for the given interface
5092/// decl.
5093llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5094 const ObjCInterfaceDecl *ID) {
5095 return EmitClassRef(Builder, ID);
5096}
5097
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005098/// Generates a message send where the super is the receiver. This is
5099/// a message send to self with special delivery semantics indicating
5100/// which class's method should be called.
5101CodeGen::RValue
5102CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5103 QualType ResultType,
5104 Selector Sel,
5105 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005106 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005107 llvm::Value *Receiver,
5108 bool IsClassMessage,
5109 const CodeGen::CallArgList &CallArgs) {
5110 // ...
5111 // Create and init a super structure; this is a (receiver, class)
5112 // pair we will pass to objc_msgSendSuper.
5113 llvm::Value *ObjCSuper =
5114 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5115
5116 llvm::Value *ReceiverAsObject =
5117 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5118 CGF.Builder.CreateStore(ReceiverAsObject,
5119 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5120
5121 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005122 llvm::Value *Target;
5123 if (IsClassMessage) {
5124 if (isCategoryImpl) {
5125 // Message sent to "super' in a class method defined in
5126 // a category implementation.
5127 Target = EmitClassRef(CGF.Builder, Class, false);
5128 Target = CGF.Builder.CreateStructGEP(Target, 0);
5129 Target = CGF.Builder.CreateLoad(Target);
5130 }
5131 else
5132 Target = EmitMetaClassRef(CGF.Builder, Class);
5133 }
5134 else
5135 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005136
5137 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5138 // and ObjCTypes types.
5139 const llvm::Type *ClassTy =
5140 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5141 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5142 CGF.Builder.CreateStore(Target,
5143 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5144
5145 return EmitMessageSend(CGF, ResultType, Sel,
5146 ObjCSuper, ObjCTypes.SuperPtrCTy,
5147 true, CallArgs);
5148}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005149
5150llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5151 Selector Sel) {
5152 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5153
5154 if (!Entry) {
5155 llvm::Constant *Casted =
5156 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5157 ObjCTypes.SelectorPtrTy);
5158 Entry =
5159 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5160 llvm::GlobalValue::InternalLinkage,
5161 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5162 &CGM.getModule());
5163 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5164 UsedGlobals.push_back(Entry);
5165 }
5166
5167 return Builder.CreateLoad(Entry, false, "tmp");
5168}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005169/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5170/// objc_assign_ivar (id src, id *dst)
5171///
5172void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5173 llvm::Value *src, llvm::Value *dst)
5174{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005175 const llvm::Type * SrcTy = src->getType();
5176 if (!isa<llvm::PointerType>(SrcTy)) {
5177 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5178 assert(Size <= 8 && "does not support size > 8");
5179 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5180 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005181 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5182 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005183 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5184 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5185 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5186 src, dst, "assignivar");
5187 return;
5188}
5189
5190/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5191/// objc_assign_strongCast (id src, id *dst)
5192///
5193void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5194 CodeGen::CodeGenFunction &CGF,
5195 llvm::Value *src, llvm::Value *dst)
5196{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005197 const llvm::Type * SrcTy = src->getType();
5198 if (!isa<llvm::PointerType>(SrcTy)) {
5199 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5200 assert(Size <= 8 && "does not support size > 8");
5201 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5202 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005203 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5204 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005205 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5206 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5207 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5208 src, dst, "weakassign");
5209 return;
5210}
5211
5212/// EmitObjCWeakRead - Code gen for loading value of a __weak
5213/// object: objc_read_weak (id *src)
5214///
5215llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5216 CodeGen::CodeGenFunction &CGF,
5217 llvm::Value *AddrWeakObj)
5218{
Eli Friedman8339b352009-03-07 03:57:15 +00005219 const llvm::Type* DestTy =
5220 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005221 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5222 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5223 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005224 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005225 return read_weak;
5226}
5227
5228/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5229/// objc_assign_weak (id src, id *dst)
5230///
5231void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5232 llvm::Value *src, llvm::Value *dst)
5233{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005234 const llvm::Type * SrcTy = src->getType();
5235 if (!isa<llvm::PointerType>(SrcTy)) {
5236 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5237 assert(Size <= 8 && "does not support size > 8");
5238 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5239 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005240 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5241 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005242 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5243 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5244 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5245 src, dst, "weakassign");
5246 return;
5247}
5248
5249/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5250/// objc_assign_global (id src, id *dst)
5251///
5252void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5253 llvm::Value *src, llvm::Value *dst)
5254{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005255 const llvm::Type * SrcTy = src->getType();
5256 if (!isa<llvm::PointerType>(SrcTy)) {
5257 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5258 assert(Size <= 8 && "does not support size > 8");
5259 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5260 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005261 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5262 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005263 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5264 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5265 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5266 src, dst, "globalassign");
5267 return;
5268}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005269
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005270void
5271CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5272 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005273 bool isTry = isa<ObjCAtTryStmt>(S);
5274 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5275 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005276 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005277 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005278 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005279 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5280
5281 // For @synchronized, call objc_sync_enter(sync.expr). The
5282 // evaluation of the expression must occur before we enter the
5283 // @synchronized. We can safely avoid a temp here because jumps into
5284 // @synchronized are illegal & this will dominate uses.
5285 llvm::Value *SyncArg = 0;
5286 if (!isTry) {
5287 SyncArg =
5288 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5289 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
5290 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
5291 }
5292
5293 // Push an EH context entry, used for handling rethrows and jumps
5294 // through finally.
5295 CGF.PushCleanupBlock(FinallyBlock);
5296
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005297 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005298
5299 CGF.EmitBlock(TryBlock);
5300 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5301 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5302 CGF.EmitBranchThroughCleanup(FinallyEnd);
5303
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005304 // Emit the exception handler.
5305
5306 CGF.EmitBlock(TryHandler);
5307
5308 llvm::Value *llvm_eh_exception =
5309 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5310 llvm::Value *llvm_eh_selector_i64 =
5311 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5312 llvm::Value *llvm_eh_typeid_for_i64 =
5313 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5314 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5315 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5316
5317 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5318 SelectorArgs.push_back(Exc);
5319 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
5320
5321 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005322 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005323 bool HasCatchAll = false;
5324 if (isTry) {
5325 if (const ObjCAtCatchStmt* CatchStmt =
5326 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5327 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005328 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005329 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005330
5331 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005332 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005333 // Use i8* null here to signal this is a catch all, not a cleanup.
5334 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5335 SelectorArgs.push_back(Null);
5336 HasCatchAll = true;
5337 break;
5338 }
5339
Daniel Dunbarede8de92009-03-06 00:01:21 +00005340 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5341 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005342 llvm::Value *IDEHType =
5343 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5344 if (!IDEHType)
5345 IDEHType =
5346 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5347 llvm::GlobalValue::ExternalLinkage,
5348 0, "OBJC_EHTYPE_id", &CGM.getModule());
5349 SelectorArgs.push_back(IDEHType);
5350 HasCatchAll = true;
5351 break;
5352 }
5353
5354 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005355 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005356 assert(PT && "Invalid @catch type.");
5357 const ObjCInterfaceType *IT =
5358 PT->getPointeeType()->getAsObjCInterfaceType();
5359 assert(IT && "Invalid @catch type.");
5360 llvm::Value *EHType = GetInterfaceEHType(IT);
5361 SelectorArgs.push_back(EHType);
5362 }
5363 }
5364 }
5365
5366 // We use a cleanup unless there was already a catch all.
5367 if (!HasCatchAll) {
5368 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005369 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005370 }
5371
5372 llvm::Value *Selector =
5373 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5374 SelectorArgs.begin(), SelectorArgs.end(),
5375 "selector");
5376 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005377 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005378 const Stmt *CatchBody = Handlers[i].second;
5379
5380 llvm::BasicBlock *Next = 0;
5381
5382 // The last handler always matches.
5383 if (i + 1 != e) {
5384 assert(CatchParam && "Only last handler can be a catch all.");
5385
5386 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5387 Next = CGF.createBasicBlock("catch.next");
5388 llvm::Value *Id =
5389 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5390 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5391 ObjCTypes.Int8PtrTy));
5392 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5393 Match, Next);
5394
5395 CGF.EmitBlock(Match);
5396 }
5397
5398 if (CatchBody) {
5399 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5400 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5401
5402 // Cleanups must call objc_end_catch.
5403 //
5404 // FIXME: It seems incorrect for objc_begin_catch to be inside
5405 // this context, but this matches gcc.
5406 CGF.PushCleanupBlock(MatchEnd);
5407 CGF.setInvokeDest(MatchHandler);
5408
5409 llvm::Value *ExcObject =
5410 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5411
5412 // Bind the catch parameter if it exists.
5413 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005414 ExcObject =
5415 CGF.Builder.CreateBitCast(ExcObject,
5416 CGF.ConvertType(CatchParam->getType()));
5417 // CatchParam is a ParmVarDecl because of the grammar
5418 // construction used to handle this, but for codegen purposes
5419 // we treat this as a local decl.
5420 CGF.EmitLocalBlockVarDecl(*CatchParam);
5421 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005422 }
5423
5424 CGF.ObjCEHValueStack.push_back(ExcObject);
5425 CGF.EmitStmt(CatchBody);
5426 CGF.ObjCEHValueStack.pop_back();
5427
5428 CGF.EmitBranchThroughCleanup(FinallyEnd);
5429
5430 CGF.EmitBlock(MatchHandler);
5431
5432 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5433 // We are required to emit this call to satisfy LLVM, even
5434 // though we don't use the result.
5435 llvm::SmallVector<llvm::Value*, 8> Args;
5436 Args.push_back(Exc);
5437 Args.push_back(ObjCTypes.EHPersonalityPtr);
5438 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5439 0));
5440 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5441 CGF.Builder.CreateStore(Exc, RethrowPtr);
5442 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5443
5444 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5445
5446 CGF.EmitBlock(MatchEnd);
5447
5448 // Unfortunately, we also have to generate another EH frame here
5449 // in case this throws.
5450 llvm::BasicBlock *MatchEndHandler =
5451 CGF.createBasicBlock("match.end.handler");
5452 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5453 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5454 Cont, MatchEndHandler,
5455 Args.begin(), Args.begin());
5456
5457 CGF.EmitBlock(Cont);
5458 if (Info.SwitchBlock)
5459 CGF.EmitBlock(Info.SwitchBlock);
5460 if (Info.EndBlock)
5461 CGF.EmitBlock(Info.EndBlock);
5462
5463 CGF.EmitBlock(MatchEndHandler);
5464 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5465 // We are required to emit this call to satisfy LLVM, even
5466 // though we don't use the result.
5467 Args.clear();
5468 Args.push_back(Exc);
5469 Args.push_back(ObjCTypes.EHPersonalityPtr);
5470 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5471 0));
5472 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5473 CGF.Builder.CreateStore(Exc, RethrowPtr);
5474 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5475
5476 if (Next)
5477 CGF.EmitBlock(Next);
5478 } else {
5479 assert(!Next && "catchup should be last handler.");
5480
5481 CGF.Builder.CreateStore(Exc, RethrowPtr);
5482 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5483 }
5484 }
5485
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005486 // Pop the cleanup entry, the @finally is outside this cleanup
5487 // scope.
5488 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5489 CGF.setInvokeDest(PrevLandingPad);
5490
5491 CGF.EmitBlock(FinallyBlock);
5492
5493 if (isTry) {
5494 if (const ObjCAtFinallyStmt* FinallyStmt =
5495 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5496 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5497 } else {
5498 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5499 // @synchronized.
5500 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005501 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005502
5503 if (Info.SwitchBlock)
5504 CGF.EmitBlock(Info.SwitchBlock);
5505 if (Info.EndBlock)
5506 CGF.EmitBlock(Info.EndBlock);
5507
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005508 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005509 CGF.EmitBranch(FinallyEnd);
5510
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005511 CGF.EmitBlock(FinallyRethrow);
5512 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5513 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005514 CGF.Builder.CreateUnreachable();
5515
5516 CGF.EmitBlock(FinallyEnd);
5517}
5518
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005519/// EmitThrowStmt - Generate code for a throw statement.
5520void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5521 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005522 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005523 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005524 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005525 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005526 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5527 "Unexpected rethrow outside @catch block.");
5528 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005529 }
5530
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005531 llvm::Value *ExceptionAsObject =
5532 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5533 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5534 if (InvokeDest) {
5535 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5536 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5537 Cont, InvokeDest,
5538 &ExceptionAsObject, &ExceptionAsObject + 1);
5539 CGF.EmitBlock(Cont);
5540 } else
5541 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5542 CGF.Builder.CreateUnreachable();
5543
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005544 // Clear the insertion point to indicate we are in unreachable code.
5545 CGF.Builder.ClearInsertionPoint();
5546}
Daniel Dunbare588b992009-03-01 04:46:24 +00005547
5548llvm::Value *
5549CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5550 const ObjCInterfaceDecl *ID = IT->getDecl();
5551 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5552 if (Entry)
5553 return Entry;
5554
5555 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5556 std::string VTableName = "objc_ehtype_vtable";
5557 llvm::GlobalVariable *VTableGV =
5558 CGM.getModule().getGlobalVariable(VTableName);
5559 if (!VTableGV)
5560 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5561 llvm::GlobalValue::ExternalLinkage,
5562 0, VTableName, &CGM.getModule());
5563
5564 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5565
5566 std::vector<llvm::Constant*> Values(3);
5567 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5568 Values[1] = GetClassName(ID->getIdentifier());
5569 Values[2] = GetClassGlobal(ClassName);
5570 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5571
5572 Entry =
5573 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005574 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005575 Init,
5576 (std::string("OBJC_EHTYPE_$_") +
5577 ID->getIdentifier()->getName()),
5578 &CGM.getModule());
5579
5580 return Entry;
5581}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005582
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005583/* *** */
5584
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005585CodeGen::CGObjCRuntime *
5586CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005587 return new CGObjCMac(CGM);
5588}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005589
5590CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005591CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005592 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005593}