blob: 97e9925fcd86b3f95c8d50187e28930156df8949 [file] [log] [blame]
Daniel Dunbar303e2c22008-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//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the Apple runtime.
Daniel Dunbar303e2c22008-08-11 02:45:11 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
John McCallad7c5c12011-02-08 08:22:06 +000015#include "CGBlocks.h"
John McCalled1ae862011-01-28 11:13:47 +000016#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Decl.h"
Daniel Dunbarb036db82008-08-13 03:21:16 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtObjC.h"
Daniel Dunbar3ad53482008-08-11 21:35:06 +000025#include "clang/Basic/LangOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000026#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000027#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallString.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/InlineAsm.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Module.h"
Daniel Dunbard027a922009-09-07 00:20:42 +000038#include "llvm/Support/raw_ostream.h"
Torok Edwindb714922009-08-24 13:25:12 +000039#include <cstdio>
Daniel Dunbar303e2c22008-08-11 02:45:11 +000040
41using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000042using namespace CodeGen;
Daniel Dunbar303e2c22008-08-11 02:45:11 +000043
44namespace {
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000045
Daniel Dunbar59e476b2009-08-03 17:06:42 +000046// FIXME: We should find a nicer way to make the labels for metadata, string
47// concatenation is lame.
Daniel Dunbarb036db82008-08-13 03:21:16 +000048
Fariborz Jahanian279eda62009-01-21 22:04:16 +000049class ObjCCommonTypesHelper {
Owen Anderson170229f2009-07-14 23:10:40 +000050protected:
51 llvm::LLVMContext &VMContext;
Daniel Dunbar59e476b2009-08-03 17:06:42 +000052
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000053private:
John McCall9dc0db22011-05-15 01:53:33 +000054 // The types of these functions don't really matter because we
55 // should always bitcast before calling them.
56
57 /// id objc_msgSend (id, SEL, ...)
58 ///
59 /// The default messenger, used for sends whose ABI is unchanged from
60 /// the all-integer/pointer case.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000061 llvm::Constant *getMessageSendFn() const {
John McCall31168b02011-06-15 23:02:42 +000062 // Add the non-lazy-bind attribute, since objc_msgSend is likely to
63 // be called a lot.
Chris Lattnera5f58b02011-07-09 17:41:47 +000064 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Bill Wendling8594fcb2013-01-31 00:30:05 +000065 return
66 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
67 params, true),
68 "objc_msgSend",
69 llvm::AttributeSet::get(CGM.getLLVMContext(),
70 llvm::AttributeSet::FunctionIndex,
71 llvm::Attribute::NonLazyBind));
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000072 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000073
John McCall9dc0db22011-05-15 01:53:33 +000074 /// void objc_msgSend_stret (id, SEL, ...)
75 ///
76 /// The messenger used when the return value is an aggregate returned
77 /// by indirect reference in the first argument, and therefore the
78 /// self and selector parameters are shifted over by one.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000079 llvm::Constant *getMessageSendStretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +000080 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +000081 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
82 params, true),
83 "objc_msgSend_stret");
Daniel Dunbar59e476b2009-08-03 17:06:42 +000084
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000085 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000086
John McCall9dc0db22011-05-15 01:53:33 +000087 /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
88 ///
89 /// The messenger used when the return value is returned on the x87
90 /// floating-point stack; without a special entrypoint, the nil case
91 /// would be unbalanced.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000092 llvm::Constant *getMessageSendFpretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +000093 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Chris Lattnerece04092012-02-07 00:39:47 +000094 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
95 params, true),
John McCall9dc0db22011-05-15 01:53:33 +000096 "objc_msgSend_fpret");
Daniel Dunbar59e476b2009-08-03 17:06:42 +000097
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000098 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000099
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000100 /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
101 ///
102 /// The messenger used when the return value is returned in two values on the
103 /// x87 floating point stack; without a special entrypoint, the nil case
104 /// would be unbalanced. Only used on 64-bit X86.
105 llvm::Constant *getMessageSendFp2retFn() const {
106 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
107 llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
108 llvm::Type *resultType =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000109 llvm::StructType::get(longDoubleType, longDoubleType, nullptr);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000110
111 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
112 params, true),
113 "objc_msgSend_fp2ret");
114 }
115
John McCall9dc0db22011-05-15 01:53:33 +0000116 /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
117 ///
118 /// The messenger used for super calls, which have different dispatch
119 /// semantics. The class passed is the superclass of the current
120 /// class.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000121 llvm::Constant *getMessageSendSuperFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000123 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000124 params, true),
125 "objc_msgSendSuper");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000126 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000127
John McCall9dc0db22011-05-15 01:53:33 +0000128 /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
129 ///
130 /// A slightly different messenger used for super calls. The class
131 /// passed is the current class.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000132 llvm::Constant *getMessageSendSuperFn2() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000133 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000134 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000135 params, true),
136 "objc_msgSendSuper2");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000137 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000138
John McCall9dc0db22011-05-15 01:53:33 +0000139 /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
140 /// SEL op, ...)
141 ///
142 /// The messenger used for super calls which return an aggregate indirectly.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000143 llvm::Constant *getMessageSendSuperStretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000144 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000145 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000146 llvm::FunctionType::get(CGM.VoidTy, params, true),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000147 "objc_msgSendSuper_stret");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000148 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000149
John McCall9dc0db22011-05-15 01:53:33 +0000150 /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
151 /// SEL op, ...)
152 ///
153 /// objc_msgSendSuper_stret with the super2 semantics.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000154 llvm::Constant *getMessageSendSuperStretFn2() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000155 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000156 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000157 llvm::FunctionType::get(CGM.VoidTy, params, true),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000158 "objc_msgSendSuper2_stret");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000159 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000160
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000161 llvm::Constant *getMessageSendSuperFpretFn() const {
162 // There is no objc_msgSendSuper_fpret? How can that work?
163 return getMessageSendSuperFn();
164 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000165
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000166 llvm::Constant *getMessageSendSuperFpretFn2() const {
167 // There is no objc_msgSendSuper_fpret? How can that work?
168 return getMessageSendSuperFn2();
169 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000170
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000171protected:
172 CodeGen::CodeGenModule &CGM;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000173
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000174public:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000175 llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000176 llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
Tim Northover238b5082014-03-29 13:42:40 +0000177 llvm::Type *IvarOffsetVarTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000178
Daniel Dunbar5d715592008-08-12 05:28:47 +0000179 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000180 llvm::Type *ObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000181
Fariborz Jahanian406b1172008-11-18 20:18:11 +0000182 /// PtrObjectPtrTy - LLVM type for id *
Chris Lattnera5f58b02011-07-09 17:41:47 +0000183 llvm::Type *PtrObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000184
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000185 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000186 llvm::Type *SelectorPtrTy;
Douglas Gregor020de322012-01-17 18:36:30 +0000187
188private:
Daniel Dunbarb036db82008-08-13 03:21:16 +0000189 /// ProtocolPtrTy - LLVM type for external protocol handles
190 /// (typeof(Protocol))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000191 llvm::Type *ExternalProtocolPtrTy;
Douglas Gregor020de322012-01-17 18:36:30 +0000192
193public:
194 llvm::Type *getExternalProtocolPtrTy() {
195 if (!ExternalProtocolPtrTy) {
196 // FIXME: It would be nice to unify this with the opaque type, so that the
197 // IR comes out a bit cleaner.
198 CodeGen::CodeGenTypes &Types = CGM.getTypes();
199 ASTContext &Ctx = CGM.getContext();
200 llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
201 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
202 }
203
204 return ExternalProtocolPtrTy;
205 }
206
Daniel Dunbarc722b852008-08-30 03:02:31 +0000207 // SuperCTy - clang type for struct objc_super.
208 QualType SuperCTy;
209 // SuperPtrCTy - clang type for struct objc_super *.
210 QualType SuperPtrCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000211
Daniel Dunbarf6397fe2008-08-23 04:28:29 +0000212 /// SuperTy - LLVM type for struct objc_super.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000213 llvm::StructType *SuperTy;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +0000214 /// SuperPtrTy - LLVM type for struct objc_super *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000215 llvm::Type *SuperPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000216
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000217 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
218 /// in GCC parlance).
Chris Lattnera5f58b02011-07-09 17:41:47 +0000219 llvm::StructType *PropertyTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000220
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000221 /// PropertyListTy - LLVM type for struct objc_property_list
222 /// (_prop_list_t in GCC parlance).
Chris Lattnera5f58b02011-07-09 17:41:47 +0000223 llvm::StructType *PropertyListTy;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000224 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000225 llvm::Type *PropertyListPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000226
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000227 // MethodTy - LLVM type for struct objc_method.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000228 llvm::StructType *MethodTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000229
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000230 /// CacheTy - LLVM type for struct objc_cache.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000231 llvm::Type *CacheTy;
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000232 /// CachePtrTy - LLVM type for struct objc_cache *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000233 llvm::Type *CachePtrTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000234
Chris Lattnerce8754e2009-04-22 02:44:54 +0000235 llvm::Constant *getGetPropertyFn() {
236 CodeGen::CodeGenTypes &Types = CGM.getTypes();
237 ASTContext &Ctx = CGM.getContext();
238 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
John McCall2da83a32010-02-26 00:48:12 +0000239 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
240 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
Benjamin Kramer30934732016-07-02 11:41:41 +0000241 CanQualType Params[] = {
242 IdType, SelType,
243 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy};
Chris Lattner2192fe52011-07-18 04:24:23 +0000244 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000245 Types.GetFunctionType(
246 Types.arrangeBuiltinFunctionDeclaration(IdType, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000247 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
248 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000249
Chris Lattnerce8754e2009-04-22 02:44:54 +0000250 llvm::Constant *getSetPropertyFn() {
251 CodeGen::CodeGenTypes &Types = CGM.getTypes();
252 ASTContext &Ctx = CGM.getContext();
253 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
John McCall2da83a32010-02-26 00:48:12 +0000254 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
255 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
Benjamin Kramer30934732016-07-02 11:41:41 +0000256 CanQualType Params[] = {
257 IdType,
258 SelType,
259 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(),
260 IdType,
261 Ctx.BoolTy,
262 Ctx.BoolTy};
Chris Lattner2192fe52011-07-18 04:24:23 +0000263 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000264 Types.GetFunctionType(
265 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000266 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
267 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000268
Ted Kremeneke65b0862012-03-06 20:05:56 +0000269 llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
270 CodeGen::CodeGenTypes &Types = CGM.getTypes();
271 ASTContext &Ctx = CGM.getContext();
272 // void objc_setProperty_atomic(id self, SEL _cmd,
273 // id newValue, ptrdiff_t offset);
274 // void objc_setProperty_nonatomic(id self, SEL _cmd,
275 // id newValue, ptrdiff_t offset);
276 // void objc_setProperty_atomic_copy(id self, SEL _cmd,
277 // id newValue, ptrdiff_t offset);
278 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
279 // id newValue, ptrdiff_t offset);
280
281 SmallVector<CanQualType,4> Params;
282 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
283 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
284 Params.push_back(IdType);
285 Params.push_back(SelType);
286 Params.push_back(IdType);
287 Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
288 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000289 Types.GetFunctionType(
290 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000291 const char *name;
292 if (atomic && copy)
293 name = "objc_setProperty_atomic_copy";
294 else if (atomic && !copy)
295 name = "objc_setProperty_atomic";
296 else if (!atomic && copy)
297 name = "objc_setProperty_nonatomic_copy";
298 else
299 name = "objc_setProperty_nonatomic";
300
301 return CGM.CreateRuntimeFunction(FTy, name);
302 }
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000303
304 llvm::Constant *getCopyStructFn() {
305 CodeGen::CodeGenTypes &Types = CGM.getTypes();
306 ASTContext &Ctx = CGM.getContext();
307 // void objc_copyStruct (void *, const void *, size_t, bool, bool)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000308 SmallVector<CanQualType,5> Params;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000309 Params.push_back(Ctx.VoidPtrTy);
310 Params.push_back(Ctx.VoidPtrTy);
311 Params.push_back(Ctx.LongTy);
312 Params.push_back(Ctx.BoolTy);
313 Params.push_back(Ctx.BoolTy);
Chris Lattner2192fe52011-07-18 04:24:23 +0000314 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000315 Types.GetFunctionType(
316 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000317 return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
318 }
319
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000320 /// This routine declares and returns address of:
321 /// void objc_copyCppObjectAtomic(
322 /// void *dest, const void *src,
323 /// void (*copyHelper) (void *dest, const void *source));
324 llvm::Constant *getCppAtomicObjectFunction() {
325 CodeGen::CodeGenTypes &Types = CGM.getTypes();
326 ASTContext &Ctx = CGM.getContext();
327 /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
328 SmallVector<CanQualType,3> Params;
329 Params.push_back(Ctx.VoidPtrTy);
330 Params.push_back(Ctx.VoidPtrTy);
331 Params.push_back(Ctx.VoidPtrTy);
332 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000333 Types.GetFunctionType(
334 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000335 return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
336 }
337
Chris Lattnerce8754e2009-04-22 02:44:54 +0000338 llvm::Constant *getEnumerationMutationFn() {
Daniel Dunbar9d82da42009-07-11 20:32:50 +0000339 CodeGen::CodeGenTypes &Types = CGM.getTypes();
340 ASTContext &Ctx = CGM.getContext();
Chris Lattnerce8754e2009-04-22 02:44:54 +0000341 // void objc_enumerationMutation (id)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 SmallVector<CanQualType,1> Params;
John McCall2da83a32010-02-26 00:48:12 +0000343 Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
Chris Lattner2192fe52011-07-18 04:24:23 +0000344 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000345 Types.GetFunctionType(
346 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000347 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
348 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000349
Douglas Gregor24ae22c2016-04-01 23:23:52 +0000350 llvm::Constant *getLookUpClassFn() {
351 CodeGen::CodeGenTypes &Types = CGM.getTypes();
352 ASTContext &Ctx = CGM.getContext();
353 // Class objc_lookUpClass (const char *)
354 SmallVector<CanQualType,1> Params;
355 Params.push_back(
356 Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst())));
357 llvm::FunctionType *FTy =
358 Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration(
359 Ctx.getCanonicalType(Ctx.getObjCClassType()),
360 Params));
361 return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass");
362 }
363
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000364 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattnerce8754e2009-04-22 02:44:54 +0000365 llvm::Constant *getGcReadWeakFn() {
366 // id objc_read_weak (id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000367 llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000368 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000369 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattnerce8754e2009-04-22 02:44:54 +0000370 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000371 }
372
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000373 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000374 llvm::Constant *getGcAssignWeakFn() {
375 // id objc_assign_weak (id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000376 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000377 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000378 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000379 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
380 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000381
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000382 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000383 llvm::Constant *getGcAssignGlobalFn() {
384 // id objc_assign_global(id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000385 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000386 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000387 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000388 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
389 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000390
Fariborz Jahanian217af242010-07-20 20:30:03 +0000391 /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
392 llvm::Constant *getGcAssignThreadLocalFn() {
393 // id objc_assign_threadlocal(id src, id * dest)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000394 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Fariborz Jahanian217af242010-07-20 20:30:03 +0000395 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000396 llvm::FunctionType::get(ObjectPtrTy, args, false);
Fariborz Jahanian217af242010-07-20 20:30:03 +0000397 return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
398 }
399
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000400 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000401 llvm::Constant *getGcAssignIvarFn() {
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000402 // id objc_assign_ivar(id, id *, ptrdiff_t)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000403 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
404 CGM.PtrDiffTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000405 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000406 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000407 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
408 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000409
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000410 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
411 llvm::Constant *GcMemmoveCollectableFn() {
412 // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000413 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
John McCall9dc0db22011-05-15 01:53:33 +0000414 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000415 return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
416 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000417
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000418 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000419 llvm::Constant *getGcAssignStrongCastFn() {
Fariborz Jahanian217af242010-07-20 20:30:03 +0000420 // id objc_assign_strongCast(id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000421 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000422 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000423 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000424 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
425 }
Anders Carlsson9ab53d12009-02-16 22:59:18 +0000426
427 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000428 llvm::Constant *getExceptionThrowFn() {
429 // void objc_exception_throw(id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000430 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattner0a696a422009-04-22 02:38:11 +0000431 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000432 llvm::FunctionType::get(CGM.VoidTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000433 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
434 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000435
Fariborz Jahanian3336de12010-05-28 17:34:43 +0000436 /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
437 llvm::Constant *getExceptionRethrowFn() {
438 // void objc_exception_rethrow(void)
John McCall9dc0db22011-05-15 01:53:33 +0000439 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
Fariborz Jahanian3336de12010-05-28 17:34:43 +0000440 return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
441 }
442
Daniel Dunbar94ceb612009-02-24 01:43:46 +0000443 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerdcceee72009-04-06 16:53:45 +0000444 llvm::Constant *getSyncEnterFn() {
Aaron Ballman9c004462012-09-06 16:44:16 +0000445 // int objc_sync_enter (id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000446 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattnerdcceee72009-04-06 16:53:45 +0000447 llvm::FunctionType *FTy =
Aaron Ballman9c004462012-09-06 16:44:16 +0000448 llvm::FunctionType::get(CGM.IntTy, args, false);
Chris Lattnerdcceee72009-04-06 16:53:45 +0000449 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
450 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000451
Daniel Dunbar94ceb612009-02-24 01:43:46 +0000452 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000453 llvm::Constant *getSyncExitFn() {
Aaron Ballman9c004462012-09-06 16:44:16 +0000454 // int objc_sync_exit (id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000455 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattner0a696a422009-04-22 02:38:11 +0000456 llvm::FunctionType *FTy =
Aaron Ballman9c004462012-09-06 16:44:16 +0000457 llvm::FunctionType::get(CGM.IntTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000458 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
459 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000460
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000461 llvm::Constant *getSendFn(bool IsSuper) const {
462 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
463 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000464
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000465 llvm::Constant *getSendFn2(bool IsSuper) const {
466 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
467 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000468
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000469 llvm::Constant *getSendStretFn(bool IsSuper) const {
470 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
471 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000472
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000473 llvm::Constant *getSendStretFn2(bool IsSuper) const {
474 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
475 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000476
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000477 llvm::Constant *getSendFpretFn(bool IsSuper) const {
478 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
479 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000480
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000481 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
482 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
483 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000484
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000485 llvm::Constant *getSendFp2retFn(bool IsSuper) const {
486 return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
487 }
488
489 llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
490 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
491 }
492
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000493 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000494};
Daniel Dunbarf6397fe2008-08-23 04:28:29 +0000495
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000496/// ObjCTypesHelper - Helper class that encapsulates lazy
497/// construction of varies types used during ObjC generation.
498class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000499public:
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000500 /// SymtabTy - LLVM type for struct objc_symtab.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000501 llvm::StructType *SymtabTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000502 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000503 llvm::Type *SymtabPtrTy;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000504 /// ModuleTy - LLVM type for struct objc_module.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000505 llvm::StructType *ModuleTy;
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000506
Daniel Dunbarb036db82008-08-13 03:21:16 +0000507 /// ProtocolTy - LLVM type for struct objc_protocol.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000508 llvm::StructType *ProtocolTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000509 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000510 llvm::Type *ProtocolPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000511 /// ProtocolExtensionTy - LLVM type for struct
512 /// objc_protocol_extension.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000513 llvm::StructType *ProtocolExtensionTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000514 /// ProtocolExtensionTy - LLVM type for struct
515 /// objc_protocol_extension *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000516 llvm::Type *ProtocolExtensionPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000517 /// MethodDescriptionTy - LLVM type for struct
518 /// objc_method_description.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000519 llvm::StructType *MethodDescriptionTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000520 /// MethodDescriptionListTy - LLVM type for struct
521 /// objc_method_description_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000522 llvm::StructType *MethodDescriptionListTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000523 /// MethodDescriptionListPtrTy - LLVM type for struct
524 /// objc_method_description_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000525 llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000526 /// ProtocolListTy - LLVM type for struct objc_property_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000527 llvm::StructType *ProtocolListTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000528 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000529 llvm::Type *ProtocolListPtrTy;
Daniel Dunbar938a77f2008-08-22 20:34:54 +0000530 /// CategoryTy - LLVM type for struct objc_category.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000531 llvm::StructType *CategoryTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000532 /// ClassTy - LLVM type for struct objc_class.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000533 llvm::StructType *ClassTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000534 /// ClassPtrTy - LLVM type for struct objc_class *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000535 llvm::Type *ClassPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000536 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000537 llvm::StructType *ClassExtensionTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000538 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000539 llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000540 // IvarTy - LLVM type for struct objc_ivar.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000541 llvm::StructType *IvarTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000542 /// IvarListTy - LLVM type for struct objc_ivar_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000543 llvm::Type *IvarListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000544 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000545 llvm::Type *IvarListPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000546 /// MethodListTy - LLVM type for struct objc_method_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000547 llvm::Type *MethodListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000548 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000549 llvm::Type *MethodListPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000550
Anders Carlsson9ff22482008-09-09 10:10:21 +0000551 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000552 llvm::Type *ExceptionDataTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000553
Anders Carlsson9ff22482008-09-09 10:10:21 +0000554 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000555 llvm::Constant *getExceptionTryEnterFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000556 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000557 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000558 llvm::FunctionType::get(CGM.VoidTy, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000559 "objc_exception_try_enter");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000560 }
Anders Carlsson9ff22482008-09-09 10:10:21 +0000561
562 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000563 llvm::Constant *getExceptionTryExitFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000564 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000565 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000566 llvm::FunctionType::get(CGM.VoidTy, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000567 "objc_exception_try_exit");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000568 }
Anders Carlsson9ff22482008-09-09 10:10:21 +0000569
570 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000571 llvm::Constant *getExceptionExtractFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000572 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000573 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000574 params, false),
Chris Lattnerc6406db2009-04-22 02:26:14 +0000575 "objc_exception_extract");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000576 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000577
Anders Carlsson9ff22482008-09-09 10:10:21 +0000578 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000579 llvm::Constant *getExceptionMatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000580 llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000581 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000582 llvm::FunctionType::get(CGM.Int32Ty, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000583 "objc_exception_match");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000584 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000585
Anders Carlsson9ff22482008-09-09 10:10:21 +0000586 /// SetJmpFn - LLVM _setjmp function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000587 llvm::Constant *getSetJmpFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000588 // This is specifically the prototype for x86.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000589 llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
Bill Wendling8594fcb2013-01-31 00:30:05 +0000590 return
591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
592 params, false),
593 "_setjmp",
594 llvm::AttributeSet::get(CGM.getLLVMContext(),
595 llvm::AttributeSet::FunctionIndex,
596 llvm::Attribute::NonLazyBind));
Chris Lattnerc6406db2009-04-22 02:26:14 +0000597 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000598
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000599public:
600 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000601};
602
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000603/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000604/// modern abi
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000605class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000606public:
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000607 // MethodListnfABITy - LLVM for struct _method_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000608 llvm::StructType *MethodListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000609
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000610 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000611 llvm::Type *MethodListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000612
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000613 // ProtocolnfABITy = LLVM for struct _protocol_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000614 llvm::StructType *ProtocolnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000615
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000616 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000617 llvm::Type *ProtocolnfABIPtrTy;
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000618
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000619 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
Chris Lattnera5f58b02011-07-09 17:41:47 +0000620 llvm::StructType *ProtocolListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000621
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000622 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000623 llvm::Type *ProtocolListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000624
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000625 // ClassnfABITy - LLVM for struct _class_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000626 llvm::StructType *ClassnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000627
Fariborz Jahanian71394042009-01-23 23:53:38 +0000628 // ClassnfABIPtrTy - LLVM for struct _class_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000629 llvm::Type *ClassnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000630
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000631 // IvarnfABITy - LLVM for struct _ivar_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000632 llvm::StructType *IvarnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000633
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000634 // IvarListnfABITy - LLVM for struct _ivar_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000635 llvm::StructType *IvarListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000636
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000637 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000638 llvm::Type *IvarListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000639
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000640 // ClassRonfABITy - LLVM for struct _class_ro_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000641 llvm::StructType *ClassRonfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000642
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000643 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000644 llvm::Type *ImpnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000645
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000646 // CategorynfABITy - LLVM for struct _category_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000647 llvm::StructType *CategorynfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000648
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000649 // New types for nonfragile abi messaging.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000650
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000651 // MessageRefTy - LLVM for:
652 // struct _message_ref_t {
653 // IMP messenger;
654 // SEL name;
655 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000656 llvm::StructType *MessageRefTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000657 // MessageRefCTy - clang type for struct _message_ref_t
658 QualType MessageRefCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000659
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000660 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000661 llvm::Type *MessageRefPtrTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000662 // MessageRefCPtrTy - clang type for struct _message_ref_t*
663 QualType MessageRefCPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000664
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000665 // SuperMessageRefTy - LLVM for:
666 // struct _super_message_ref_t {
667 // SUPER_IMP messenger;
668 // SEL name;
669 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000670 llvm::StructType *SuperMessageRefTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000671
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000672 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000673 llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +0000674
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000675 llvm::Constant *getMessageSendFixupFn() {
676 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000677 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000678 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000679 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000680 "objc_msgSend_fixup");
681 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000682
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000683 llvm::Constant *getMessageSendFpretFixupFn() {
684 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000685 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000686 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000687 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000688 "objc_msgSend_fpret_fixup");
689 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000690
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000691 llvm::Constant *getMessageSendStretFixupFn() {
692 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000693 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000694 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000695 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000696 "objc_msgSend_stret_fixup");
697 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000698
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000699 llvm::Constant *getMessageSendSuper2FixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000700 // id objc_msgSendSuper2_fixup (struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000701 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000702 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000703 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000704 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000705 "objc_msgSendSuper2_fixup");
706 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000707
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000708 llvm::Constant *getMessageSendSuper2StretFixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000709 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000710 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000711 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000712 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000713 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000714 "objc_msgSendSuper2_stret_fixup");
715 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000716
Chris Lattnera7c00b42009-04-22 02:15:23 +0000717 llvm::Constant *getObjCEndCatchFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000718 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000719 "objc_end_catch");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000720
Chris Lattnera7c00b42009-04-22 02:15:23 +0000721 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000722
Chris Lattnera7c00b42009-04-22 02:15:23 +0000723 llvm::Constant *getObjCBeginCatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000724 llvm::Type *params[] = { Int8PtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000725 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000726 params, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000727 "objc_begin_catch");
728 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +0000729
Chris Lattnera5f58b02011-07-09 17:41:47 +0000730 llvm::StructType *EHTypeTy;
731 llvm::Type *EHTypePtrTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000732
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000733 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000734};
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000735
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000736class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000737public:
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000738 class SKIP_SCAN {
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000739 public:
740 unsigned skip;
741 unsigned scan;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000742 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000743 : skip(_skip), scan(_scan) {}
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000744 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000745
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000746 /// opcode for captured block variables layout 'instructions'.
747 /// In the following descriptions, 'I' is the value of the immediate field.
748 /// (field following the opcode).
749 ///
750 enum BLOCK_LAYOUT_OPCODE {
751 /// An operator which affects how the following layout should be
752 /// interpreted.
753 /// I == 0: Halt interpretation and treat everything else as
754 /// a non-pointer. Note that this instruction is equal
755 /// to '\0'.
756 /// I != 0: Currently unused.
757 BLOCK_LAYOUT_OPERATOR = 0,
758
759 /// The next I+1 bytes do not contain a value of object pointer type.
760 /// Note that this can leave the stream unaligned, meaning that
761 /// subsequent word-size instructions do not begin at a multiple of
762 /// the pointer size.
763 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
764
765 /// The next I+1 words do not contain a value of object pointer type.
766 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
767 /// when the required skip quantity is a multiple of the pointer size.
768 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
769
770 /// The next I+1 words are __strong pointers to Objective-C
771 /// objects or blocks.
772 BLOCK_LAYOUT_STRONG = 3,
773
774 /// The next I+1 words are pointers to __block variables.
775 BLOCK_LAYOUT_BYREF = 4,
776
777 /// The next I+1 words are __weak pointers to Objective-C
778 /// objects or blocks.
779 BLOCK_LAYOUT_WEAK = 5,
780
781 /// The next I+1 words are __unsafe_unretained pointers to
782 /// Objective-C objects or blocks.
783 BLOCK_LAYOUT_UNRETAINED = 6
784
785 /// The next I+1 words are block or object pointers with some
786 /// as-yet-unspecified ownership semantics. If we add more
787 /// flavors of ownership semantics, values will be taken from
788 /// this range.
789 ///
790 /// This is included so that older tools can at least continue
791 /// processing the layout past such things.
792 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
793
794 /// All other opcodes are reserved. Halt interpretation and
795 /// treat everything else as opaque.
796 };
797
798 class RUN_SKIP {
799 public:
800 enum BLOCK_LAYOUT_OPCODE opcode;
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000801 CharUnits block_var_bytepos;
802 CharUnits block_var_size;
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000803 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000804 CharUnits BytePos = CharUnits::Zero(),
805 CharUnits Size = CharUnits::Zero())
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000806 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000807
808 // Allow sorting based on byte pos.
809 bool operator<(const RUN_SKIP &b) const {
810 return block_var_bytepos < b.block_var_bytepos;
811 }
812 };
813
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000814protected:
Owen Andersonae86c192009-07-13 04:10:07 +0000815 llvm::LLVMContext &VMContext;
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000816 // FIXME! May not be needing this after all.
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000817 unsigned ObjCABI;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000818
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000819 // arc/mrr layout of captured block literal variables.
820 SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000821
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000822 /// LazySymbols - Symbols to generate a lazy reference for. See
823 /// DefinedSymbols and FinishModule().
Daniel Dunbard027a922009-09-07 00:20:42 +0000824 llvm::SetVector<IdentifierInfo*> LazySymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000825
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000826 /// DefinedSymbols - External symbols which are defined by this
827 /// module. The symbols in this list and LazySymbols are used to add
828 /// special linker symbols which ensure that Objective-C modules are
829 /// linked properly.
Daniel Dunbard027a922009-09-07 00:20:42 +0000830 llvm::SetVector<IdentifierInfo*> DefinedSymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000831
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000832 /// ClassNames - uniqued class names.
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000833 llvm::StringMap<llvm::GlobalVariable*> ClassNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000834
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000835 /// MethodVarNames - uniqued method variable names.
836 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000837
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000838 /// DefinedCategoryNames - list of category names in form Class_Category.
Rafael Espindolacd676622015-11-18 06:54:13 +0000839 llvm::SmallSetVector<std::string, 16> DefinedCategoryNames;
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000840
Daniel Dunbarb036db82008-08-13 03:21:16 +0000841 /// MethodVarTypes - uniqued method type signatures. We have to use
842 /// a StringMap here because have no other unique reference.
843 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000844
Daniel Dunbar3c76cb52008-08-26 21:51:14 +0000845 /// MethodDefinitions - map of methods which have been defined in
846 /// this translation unit.
847 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000848
Daniel Dunbar80a840b2008-08-23 00:19:03 +0000849 /// PropertyNames - uniqued method variable names.
850 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000851
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000852 /// ClassReferences - uniqued class references.
853 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000854
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000855 /// SelectorReferences - uniqued selector references.
856 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000857
Daniel Dunbarb036db82008-08-13 03:21:16 +0000858 /// Protocols - Protocols for which an objc_protocol structure has
859 /// been emitted. Forward declarations are handled by creating an
860 /// empty structure whose initializer is filled in when/if defined.
861 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000862
Daniel Dunbarc475d422008-10-29 22:36:39 +0000863 /// DefinedProtocols - Protocols which have actually been
864 /// defined. We should not need this, see FIXME in GenerateProtocol.
865 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000866
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000867 /// DefinedClasses - List of defined classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000868 SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +0000869
870 /// ImplementedClasses - List of @implemented classes.
871 SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000872
873 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000874 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000875
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000876 /// DefinedCategories - List of defined categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000877 SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000878
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000879 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000880 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000881
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000882 /// GetNameForMethod - Return a name for the given method.
883 /// \param[out] NameOut - The return value.
884 void GetNameForMethod(const ObjCMethodDecl *OMD,
885 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000886 SmallVectorImpl<char> &NameOut);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000887
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000888 /// GetMethodVarName - Return a unique constant for the given
889 /// selector's name. The return value has type char *.
890 llvm::Constant *GetMethodVarName(Selector Sel);
891 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000892
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000893 /// GetMethodVarType - Return a unique constant for the given
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000894 /// method's type encoding string. The return value has type char *.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000895
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000896 // FIXME: This is a horrible name.
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000897 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
898 bool Extended = false);
Daniel Dunbarf5c18462009-04-20 06:54:31 +0000899 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000900
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000901 /// GetPropertyName - Return a unique constant for the given
902 /// name. The return value has type char *.
903 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000904
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000905 // FIXME: This can be dropped once string functions are unified.
906 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
907 const Decl *Container);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000908
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +0000909 /// GetClassName - Return a unique constant for the given selector's
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000910 /// runtime name (which may change via use of objc_runtime_name attribute on
911 /// class or protocol definition. The return value has type char *.
912 llvm::Constant *GetClassName(StringRef RuntimeName);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000913
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +0000914 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
915
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +0000916 /// BuildIvarLayout - Builds ivar layout bitmap for the class
917 /// implementation for the __strong or __weak case.
918 ///
John McCall460ce582015-10-22 18:38:17 +0000919 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there
920 /// are any weak ivars defined directly in the class. Meaningless unless
921 /// building a weak layout. Does not guarantee that the layout will
922 /// actually have any entries, because the ivar might be under-aligned.
Fariborz Jahanian1bf72882009-03-12 22:50:49 +0000923 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
John McCall3fd13f062015-10-21 18:06:47 +0000924 CharUnits beginOffset,
925 CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +0000926 bool forStrongLayout,
927 bool hasMRCWeakIvars);
928
929 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,
930 CharUnits beginOffset,
931 CharUnits endOffset) {
932 return BuildIvarLayout(OI, beginOffset, endOffset, true, false);
933 }
934
935 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,
936 CharUnits beginOffset,
937 CharUnits endOffset,
938 bool hasMRCWeakIvars) {
939 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);
940 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +0000941
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000942 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
Fariborz Jahanian2dd78192012-11-02 22:51:18 +0000943
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000944 void UpdateRunSkipBlockVars(bool IsByref,
945 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000946 CharUnits FieldOffset,
947 CharUnits FieldSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000948
949 void BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000950 CharUnits BytePos, bool &HasUnion,
951 bool ByrefLayout=false);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000952
953 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
954 const RecordDecl *RD,
955 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000956 CharUnits BytePos, bool &HasUnion,
957 bool ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000958
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000959 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
960
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000961 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
962
Fariborz Jahanian01dff422009-03-05 19:17:31 +0000963 /// GetIvarLayoutName - Returns a unique constant for the given
964 /// ivar layout bitmap.
965 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
966 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000967
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000968 /// EmitPropertyList - Emit the given property list. The return
969 /// value has type PropertyListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000970 llvm::Constant *EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000971 const Decl *Container,
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000972 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +0000973 const ObjCCommonTypesHelper &ObjCTypes,
974 bool IsClassProperty);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000975
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000976 /// EmitProtocolMethodTypes - Generate the array of extended method type
977 /// strings. The return value has type Int8PtrPtrTy.
978 llvm::Constant *EmitProtocolMethodTypes(Twine Name,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +0000979 ArrayRef<llvm::Constant*> MethodTypes,
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000980 const ObjCCommonTypesHelper &ObjCTypes);
981
Fariborz Jahanian751c1e72009-12-12 21:26:21 +0000982 /// PushProtocolProperties - Push protocol's property on the input stack.
Bill Wendlinga515b582012-02-09 22:16:49 +0000983 void PushProtocolProperties(
984 llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000985 SmallVectorImpl<llvm::Constant*> &Properties,
Bill Wendlinga515b582012-02-09 22:16:49 +0000986 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000987 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +0000988 const ObjCCommonTypesHelper &ObjCTypes,
989 bool IsClassProperty);
Fariborz Jahanian751c1e72009-12-12 21:26:21 +0000990
Fariborz Jahanian56b3b772009-01-29 19:24:30 +0000991 /// GetProtocolRef - Return a reference to the internal protocol
992 /// description, creating an empty one if it has not been
993 /// defined. The return value has type ProtocolPtrTy.
994 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanian67726212009-03-08 20:18:37 +0000995
Douglas Gregor24ae22c2016-04-01 23:23:52 +0000996 /// Return a reference to the given Class using runtime calls rather than
997 /// by a symbol reference.
998 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,
999 const ObjCInterfaceDecl *ID,
1000 ObjCCommonTypesHelper &ObjCTypes);
1001
John McCall3fd13f062015-10-21 18:06:47 +00001002public:
Daniel Dunbar30c65362009-03-09 20:09:19 +00001003 /// CreateMetadataVar - Create a global variable with internal
1004 /// linkage for use by the Objective-C runtime.
1005 ///
1006 /// This is a convenience wrapper which not only creates the
1007 /// variable, but also sets the section and alignment and adds the
Chris Lattnerf56501c2009-07-17 23:57:13 +00001008 /// global to the "llvm.used" list.
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001009 ///
1010 /// \param Name - The variable name.
1011 /// \param Init - The variable initializer; this is also used to
1012 /// define the type of the variable.
Alp Toker541d5072014-06-07 23:30:53 +00001013 /// \param Section - The section the variable should go into, or empty.
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001014 /// \param Align - The alignment for the variable, or 0.
1015 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar4527d302009-04-14 17:42:51 +00001016 /// "llvm.used".
Alp Toker541d5072014-06-07 23:30:53 +00001017 llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init,
John McCall7f416cc2015-09-08 08:05:57 +00001018 StringRef Section, CharUnits Align,
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001019 bool AddToUsed);
Daniel Dunbar30c65362009-03-09 20:09:19 +00001020
John McCall3fd13f062015-10-21 18:06:47 +00001021protected:
John McCall9e8bb002011-05-14 03:10:52 +00001022 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1023 ReturnValueSlot Return,
1024 QualType ResultType,
1025 llvm::Value *Sel,
1026 llvm::Value *Arg0,
1027 QualType Arg0Ty,
1028 bool IsSuper,
1029 const CallArgList &CallArgs,
1030 const ObjCMethodDecl *OMD,
John McCall1e3157b2015-09-10 22:27:50 +00001031 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001032 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbarf5c18462009-04-20 06:54:31 +00001033
Daniel Dunbar5e639272010-04-25 20:39:01 +00001034 /// EmitImageInfo - Emit the image info marker used to encode some module
1035 /// level information.
1036 void EmitImageInfo();
1037
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001038public:
Owen Andersonae86c192009-07-13 04:10:07 +00001039 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
John McCalla729c622012-02-17 03:33:10 +00001040 CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001041
John McCall3fd13f062015-10-21 18:06:47 +00001042 bool isNonFragileABI() const {
1043 return ObjCABI == 2;
1044 }
1045
John McCall7f416cc2015-09-08 08:05:57 +00001046 ConstantAddress GenerateConstantString(const StringLiteral *SL) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001047
Craig Topper4f12f102014-03-12 06:41:41 +00001048 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Craig Topper8a13c412014-05-21 05:09:00 +00001049 const ObjCContainerDecl *CD=nullptr) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001050
1051 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001052
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001053 /// GetOrEmitProtocol - Get the protocol object for the given
1054 /// declaration, emitting it if necessary. The return value has type
1055 /// ProtocolPtrTy.
1056 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001057
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001058 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1059 /// object for the given declaration, emitting it if needed. These
1060 /// forward references will be filled in with empty bodies if no
1061 /// definition is seen. The return value has type ProtocolPtrTy.
1062 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Craig Topper4f12f102014-03-12 06:41:41 +00001063 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1064 const CGBlockInfo &blockInfo) override;
1065 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1066 const CGBlockInfo &blockInfo) override;
1067
1068 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1069 QualType T) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001070};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001071
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001072class CGObjCMac : public CGObjCCommonMac {
1073private:
1074 ObjCTypesHelper ObjCTypes;
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001075
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001076 /// EmitModuleInfo - Another marker encoding module level
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001077 /// information.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001078 void EmitModuleInfo();
1079
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001080 /// EmitModuleSymols - Emit module symbols, the list of defined
1081 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001082 llvm::Constant *EmitModuleSymbols();
1083
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001084 /// FinishModule - Write out global data structures at the end of
1085 /// processing a translation unit.
1086 void FinishModule();
Daniel Dunbarb036db82008-08-13 03:21:16 +00001087
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001088 /// EmitClassExtension - Generate the class extension structure used
1089 /// to store the weak ivar layout and properties. The return value
1090 /// has type ClassExtensionPtrTy.
John McCall3fd13f062015-10-21 18:06:47 +00001091 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,
John McCall460ce582015-10-22 18:38:17 +00001092 CharUnits instanceSize,
Manman Renad0e7912016-01-29 19:22:54 +00001093 bool hasMRCWeakIvars,
1094 bool isClassProperty);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001095
1096 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1097 /// for the given class.
John McCall882987f2013-02-28 19:01:20 +00001098 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001099 const ObjCInterfaceDecl *ID);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001100
John McCall882987f2013-02-28 19:01:20 +00001101 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00001102 IdentifierInfo *II);
Craig Topper4f12f102014-03-12 06:41:41 +00001103
1104 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1105
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001106 /// EmitSuperClassRef - Emits reference to class's main metadata class.
1107 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001108
1109 /// EmitIvarList - Emit the ivar list for the given
1110 /// implementation. If ForClass is true the list of class ivars
1111 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1112 /// interface ivars will be emitted. The return value has type
1113 /// IvarListPtrTy.
1114 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00001115 bool ForClass);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001116
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001117 /// EmitMetaClass - Emit a forward reference to the class structure
1118 /// for the metaclass of the given interface. The return value has
1119 /// type ClassPtrTy.
1120 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1121
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001122 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001123 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001124 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1125 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00001126 ArrayRef<llvm::Constant*> Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001127
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001128 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001129
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001130 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001131
1132 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001133 /// implementation. The return value has type MethodListPtrTy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001134 llvm::Constant *EmitMethodList(Twine Name, StringRef Section,
1135 ArrayRef<llvm::Constant *> Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001136
1137 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001138 /// method declarations.
Daniel Dunbarb036db82008-08-13 03:21:16 +00001139 /// - TypeName: The name for the type containing the methods.
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001140 /// - IsProtocol: True iff these methods are for a protocol.
1141 /// - ClassMethds: True iff these are class methods.
Daniel Dunbarb036db82008-08-13 03:21:16 +00001142 /// - Required: When true, only "required" methods are
1143 /// listed. Similarly, when false only "optional" methods are
1144 /// listed. For classes this should always be true.
1145 /// - begin, end: The method list to output.
1146 ///
1147 /// The return value has type MethodDescriptionListPtrTy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001148 llvm::Constant *EmitMethodDescList(Twine Name, StringRef Section,
1149 ArrayRef<llvm::Constant *> Methods);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001150
Daniel Dunbarc475d422008-10-29 22:36:39 +00001151 /// GetOrEmitProtocol - Get the protocol object for the given
1152 /// declaration, emitting it if necessary. The return value has type
1153 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001154 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001155
1156 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1157 /// object for the given declaration, emitting it if needed. These
1158 /// forward references will be filled in with empty bodies if no
1159 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001160 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001161
Daniel Dunbarb036db82008-08-13 03:21:16 +00001162 /// EmitProtocolExtension - Generate the protocol extension
1163 /// structure used to store optional instance and class methods, and
1164 /// protocol properties. The return value has type
1165 /// ProtocolExtensionPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001166 llvm::Constant *
1167 EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00001168 ArrayRef<llvm::Constant*> OptInstanceMethods,
1169 ArrayRef<llvm::Constant*> OptClassMethods,
1170 ArrayRef<llvm::Constant*> MethodTypesExt);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001171
1172 /// EmitProtocolList - Generate the list of referenced
1173 /// protocols. The return value has type ProtocolListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001174 llvm::Constant *EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00001175 ObjCProtocolDecl::protocol_iterator begin,
1176 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001177
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001178 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1179 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001180 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1181 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001182
1183public:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001184 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001185
Craig Topper4f12f102014-03-12 06:41:41 +00001186 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001187
Craig Topper4f12f102014-03-12 06:41:41 +00001188 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1189 ReturnValueSlot Return,
1190 QualType ResultType,
1191 Selector Sel, llvm::Value *Receiver,
1192 const CallArgList &CallArgs,
1193 const ObjCInterfaceDecl *Class,
1194 const ObjCMethodDecl *Method) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001195
Craig Topper4f12f102014-03-12 06:41:41 +00001196 CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001197 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001198 ReturnValueSlot Return, QualType ResultType,
1199 Selector Sel, const ObjCInterfaceDecl *Class,
1200 bool isCategoryImpl, llvm::Value *Receiver,
1201 bool IsClassMessage, const CallArgList &CallArgs,
1202 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001203
Craig Topper4f12f102014-03-12 06:41:41 +00001204 llvm::Value *GetClass(CodeGenFunction &CGF,
1205 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001206
John McCall7f416cc2015-09-08 08:05:57 +00001207 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
1208 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001209
1210 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1211 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001212 llvm::Value *GetSelector(CodeGenFunction &CGF,
1213 const ObjCMethodDecl *Method) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001214
Craig Topper4f12f102014-03-12 06:41:41 +00001215 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001216
Craig Topper4f12f102014-03-12 06:41:41 +00001217 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001218
Craig Topper4f12f102014-03-12 06:41:41 +00001219 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001220
Craig Topper4f12f102014-03-12 06:41:41 +00001221 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001222
Craig Topper4f12f102014-03-12 06:41:41 +00001223 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1224 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001225
Craig Topper4f12f102014-03-12 06:41:41 +00001226 llvm::Constant *GetPropertyGetFunction() override;
1227 llvm::Constant *GetPropertySetFunction() override;
1228 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1229 bool copy) override;
1230 llvm::Constant *GetGetStructFunction() override;
1231 llvm::Constant *GetSetStructFunction() override;
1232 llvm::Constant *GetCppAtomicObjectGetFunction() override;
1233 llvm::Constant *GetCppAtomicObjectSetFunction() override;
1234 llvm::Constant *EnumerationMutationFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001235
Craig Topper4f12f102014-03-12 06:41:41 +00001236 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1237 const ObjCAtTryStmt &S) override;
1238 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1239 const ObjCAtSynchronizedStmt &S) override;
John McCallbd309292010-07-06 01:34:17 +00001240 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
Craig Topper4f12f102014-03-12 06:41:41 +00001241 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1242 bool ClearInsertionPoint=true) override;
1243 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001244 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001245 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001246 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001247 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001248 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001249 bool threadlocal = false) override;
1250 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001251 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001252 llvm::Value *ivarOffset) override;
1253 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001254 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001255 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001256 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001257 llvm::Value *size) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001258
Craig Topper4f12f102014-03-12 06:41:41 +00001259 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1260 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1261 unsigned CVRQualifiers) override;
1262 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1263 const ObjCInterfaceDecl *Interface,
1264 const ObjCIvarDecl *Ivar) override;
1265
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001266 /// GetClassGlobal - Return the global variable for the Objective-C
1267 /// class of the given name.
Benjamin Kramer0772c422016-02-13 13:42:54 +00001268 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +00001269 bool Weak = false) override {
David Blaikie83d382b2011-09-23 05:06:16 +00001270 llvm_unreachable("CGObjCMac::GetClassGlobal");
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001271 }
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001272};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001273
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001274class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001275private:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001276 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanian71394042009-01-23 23:53:38 +00001277 llvm::GlobalVariable* ObjCEmptyCacheVar;
1278 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001279
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001280 /// SuperClassReferences - uniqued super class references.
1281 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001282
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001283 /// MetaClassReferences - uniqued meta class references.
1284 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001285
1286 /// EHTypeReferences - uniqued class ehtype references.
1287 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001288
John McCall9e8bb002011-05-14 03:10:52 +00001289 /// VTableDispatchMethods - List of methods for which we generate
1290 /// vtable-based message dispatch.
1291 llvm::DenseSet<Selector> VTableDispatchMethods;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001292
Fariborz Jahanian67260552009-11-17 21:37:35 +00001293 /// DefinedMetaClasses - List of defined meta-classes.
1294 std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1295
John McCall9e8bb002011-05-14 03:10:52 +00001296 /// isVTableDispatchedSelector - Returns true if SEL is a
1297 /// vtable-based selector.
1298 bool isVTableDispatchedSelector(Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001299
Fariborz Jahanian71394042009-01-23 23:53:38 +00001300 /// FinishNonFragileABIModule - Write out global data structures at the end of
1301 /// processing a translation unit.
1302 void FinishNonFragileABIModule();
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001303
Daniel Dunbar19573e72009-05-15 21:48:48 +00001304 /// AddModuleClassList - Add the given list of class pointers to the
1305 /// module with the provided symbol and section names.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001306 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,
1307 StringRef SymbolName, StringRef SectionName);
Daniel Dunbar19573e72009-05-15 21:48:48 +00001308
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001309 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1310 unsigned InstanceStart,
1311 unsigned InstanceSize,
1312 const ObjCImplementationDecl *ID);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001313 llvm::GlobalVariable * BuildClassMetaData(const std::string &ClassName,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001314 llvm::Constant *IsAGV,
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00001315 llvm::Constant *SuperClassGV,
Fariborz Jahanian82208252009-01-31 00:59:10 +00001316 llvm::Constant *ClassRoGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00001317 bool HiddenVisibility,
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00001318 bool Weak);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001319
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00001320 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001321
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00001322 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001323
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00001324 /// EmitMethodList - Emit the method list for the given
1325 /// implementation. The return value has type MethodListnfABITy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001326 llvm::Constant *EmitMethodList(Twine Name, StringRef Section,
1327 ArrayRef<llvm::Constant *> Methods);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00001328 /// EmitIvarList - Emit the ivar list for the given
1329 /// implementation. If ForClass is true the list of class ivars
1330 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1331 /// interface ivars will be emitted. The return value has type
1332 /// IvarListnfABIPtrTy.
1333 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001334
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001335 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian3d3426f2009-01-28 01:36:42 +00001336 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00001337 unsigned long int offset);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001338
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001339 /// GetOrEmitProtocol - Get the protocol object for the given
1340 /// declaration, emitting it if necessary. The return value has type
1341 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001342 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001343
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001344 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1345 /// object for the given declaration, emitting it if needed. These
1346 /// forward references will be filled in with empty bodies if no
1347 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001348 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001349
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001350 /// EmitProtocolList - Generate the list of referenced
1351 /// protocols. The return value has type ProtocolListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001352 llvm::Constant *EmitProtocolList(Twine Name,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001353 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00001354 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001355
John McCall9e8bb002011-05-14 03:10:52 +00001356 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1357 ReturnValueSlot Return,
1358 QualType ResultType,
1359 Selector Sel,
1360 llvm::Value *Receiver,
1361 QualType Arg0Ty,
1362 bool IsSuper,
1363 const CallArgList &CallArgs,
1364 const ObjCMethodDecl *Method);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001365
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00001366 /// GetClassGlobal - Return the global variable for the Objective-C
1367 /// class of the given name.
Benjamin Kramer0772c422016-02-13 13:42:54 +00001368 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +00001369 bool Weak = false) override;
Rafael Espindola554256c2014-02-26 22:25:45 +00001370
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00001371 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001372 /// for the given class reference.
John McCall882987f2013-02-28 19:01:20 +00001373 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001374 const ObjCInterfaceDecl *ID);
John McCall31168b02011-06-15 23:02:42 +00001375
John McCall882987f2013-02-28 19:01:20 +00001376 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001377 IdentifierInfo *II, bool Weak,
1378 const ObjCInterfaceDecl *ID);
Craig Topper4f12f102014-03-12 06:41:41 +00001379
1380 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001381
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001382 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1383 /// for the given super class reference.
John McCall882987f2013-02-28 19:01:20 +00001384 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001385 const ObjCInterfaceDecl *ID);
1386
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001387 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1388 /// meta-data
John McCall882987f2013-02-28 19:01:20 +00001389 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00001390 const ObjCInterfaceDecl *ID, bool Weak);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001391
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001392 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1393 /// the given ivar.
1394 ///
Daniel Dunbara1060522009-04-19 00:31:15 +00001395 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001396 const ObjCInterfaceDecl *ID,
1397 const ObjCIvarDecl *Ivar);
1398
Fariborz Jahanian74b77222009-02-11 20:51:17 +00001399 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1400 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001401 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1402 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001403
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001404 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001405 /// interface. The return value has type EHTypePtrTy.
John McCall2ca705e2010-07-24 00:37:23 +00001406 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001407 bool ForDefinition);
Daniel Dunbar15894b72009-04-07 05:48:37 +00001408
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001409 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001410
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001411 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }
Daniel Dunbar15894b72009-04-07 05:48:37 +00001412
Daniel Dunbar961202372009-05-03 12:57:56 +00001413 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00001414 uint32_t &InstanceStart,
1415 uint32_t &InstanceSize);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001416
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001417 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001418 Selector GetNullarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001419 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1420 return CGM.getContext().Selectors.getSelector(0, &II);
1421 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001422
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001423 Selector GetUnarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001424 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1425 return CGM.getContext().Selectors.getSelector(1, &II);
1426 }
Daniel Dunbar554fd792009-04-19 23:41:48 +00001427
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001428 /// ImplementationIsNonLazy - Check whether the given category or
1429 /// class implementation is "non-lazy".
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00001430 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001431
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001432 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001433 const ObjCIvarDecl *IV) {
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001434 // Annotate the load as an invariant load iff inside an instance method
1435 // and ivar belongs to instance method's class and one of its super class.
1436 // This check is needed because the ivar offset is a lazily
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001437 // initialised value that may depend on objc_msgSend to perform a fixup on
1438 // the first message dispatch.
1439 //
1440 // An additional opportunity to mark the load as invariant arises when the
1441 // base of the ivar access is a parameter to an Objective C method.
1442 // However, because the parameters are not available in the current
1443 // interface, we cannot perform this check.
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001444 if (const ObjCMethodDecl *MD =
1445 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
Fariborz Jahanian7a583022014-03-04 22:57:32 +00001446 if (MD->isInstanceMethod())
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001447 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1448 return IV->getContainingInterface()->isSuperClassOf(ID);
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001449 return false;
1450 }
1451
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001452public:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001453 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian71394042009-01-23 23:53:38 +00001454 // FIXME. All stubs for now!
Craig Topper4f12f102014-03-12 06:41:41 +00001455 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001456
Craig Topper4f12f102014-03-12 06:41:41 +00001457 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1458 ReturnValueSlot Return,
1459 QualType ResultType, Selector Sel,
1460 llvm::Value *Receiver,
1461 const CallArgList &CallArgs,
1462 const ObjCInterfaceDecl *Class,
1463 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001464
Craig Topper4f12f102014-03-12 06:41:41 +00001465 CodeGen::RValue
Fariborz Jahanian71394042009-01-23 23:53:38 +00001466 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001467 ReturnValueSlot Return, QualType ResultType,
1468 Selector Sel, const ObjCInterfaceDecl *Class,
1469 bool isCategoryImpl, llvm::Value *Receiver,
1470 bool IsClassMessage, const CallArgList &CallArgs,
1471 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001472
Craig Topper4f12f102014-03-12 06:41:41 +00001473 llvm::Value *GetClass(CodeGenFunction &CGF,
1474 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001475
John McCall7f416cc2015-09-08 08:05:57 +00001476 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override
1477 { return EmitSelector(CGF, Sel); }
1478 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override
1479 { return EmitSelectorAddr(CGF, Sel); }
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001480
1481 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1482 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001483 llvm::Value *GetSelector(CodeGenFunction &CGF,
1484 const ObjCMethodDecl *Method) override
John McCall882987f2013-02-28 19:01:20 +00001485 { return EmitSelector(CGF, Method->getSelector()); }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001486
Craig Topper4f12f102014-03-12 06:41:41 +00001487 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001488
Craig Topper4f12f102014-03-12 06:41:41 +00001489 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
David Chisnall92d436b2012-01-31 18:59:20 +00001490
Craig Topper4f12f102014-03-12 06:41:41 +00001491 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001492
Craig Topper4f12f102014-03-12 06:41:41 +00001493 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1494 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001495
Craig Topper4f12f102014-03-12 06:41:41 +00001496 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001497
Craig Topper4f12f102014-03-12 06:41:41 +00001498 llvm::Constant *GetPropertyGetFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001499 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001500 }
Craig Topper4f12f102014-03-12 06:41:41 +00001501 llvm::Constant *GetPropertySetFunction() override {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001502 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001503 }
Craig Topper4f12f102014-03-12 06:41:41 +00001504
1505 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1506 bool copy) override {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001507 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1508 }
Craig Topper4f12f102014-03-12 06:41:41 +00001509
1510 llvm::Constant *GetSetStructFunction() override {
David Chisnall168b80f2010-12-26 22:13:16 +00001511 return ObjCTypes.getCopyStructFn();
1512 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001513
Craig Topper4f12f102014-03-12 06:41:41 +00001514 llvm::Constant *GetGetStructFunction() override {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001515 return ObjCTypes.getCopyStructFn();
1516 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001517
Craig Topper4f12f102014-03-12 06:41:41 +00001518 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +00001519 return ObjCTypes.getCppAtomicObjectFunction();
1520 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001521
Craig Topper4f12f102014-03-12 06:41:41 +00001522 llvm::Constant *GetCppAtomicObjectGetFunction() override {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00001523 return ObjCTypes.getCppAtomicObjectFunction();
1524 }
Craig Topper4f12f102014-03-12 06:41:41 +00001525
1526 llvm::Constant *EnumerationMutationFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001527 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbard73ea8162009-02-16 18:48:45 +00001528 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001529
Craig Topper4f12f102014-03-12 06:41:41 +00001530 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1531 const ObjCAtTryStmt &S) override;
1532 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1533 const ObjCAtSynchronizedStmt &S) override;
1534 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1535 bool ClearInsertionPoint=true) override;
1536 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001537 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001538 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001539 llvm::Value *src, Address edst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001540 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001541 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001542 bool threadlocal = false) override;
1543 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001544 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001545 llvm::Value *ivarOffset) override;
1546 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001547 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001548 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001549 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001550 llvm::Value *size) override;
1551 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1552 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1553 unsigned CVRQualifiers) override;
1554 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1555 const ObjCInterfaceDecl *Interface,
1556 const ObjCIvarDecl *Ivar) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001557};
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001558
1559/// A helper class for performing the null-initialization of a return
1560/// value.
1561struct NullReturnState {
1562 llvm::BasicBlock *NullBB;
Craig Topper8a13c412014-05-21 05:09:00 +00001563 NullReturnState() : NullBB(nullptr) {}
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001564
John McCall3d1e2c92013-02-12 05:53:35 +00001565 /// Perform a null-check of the given receiver.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001566 void init(CodeGenFunction &CGF, llvm::Value *receiver) {
John McCall3d1e2c92013-02-12 05:53:35 +00001567 // Make blocks for the null-receiver and call edges.
1568 NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1569 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001570
1571 // Check for a null receiver and, if there is one, jump to the
John McCall3d1e2c92013-02-12 05:53:35 +00001572 // null-receiver block. There's no point in trying to avoid it:
1573 // we're always going to put *something* there, because otherwise
1574 // we shouldn't have done this null-check in the first place.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001575 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1576 CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1577
1578 // Otherwise, start performing the call.
1579 CGF.EmitBlock(callBB);
1580 }
1581
John McCall3d1e2c92013-02-12 05:53:35 +00001582 /// Complete the null-return operation. It is valid to call this
1583 /// regardless of whether 'init' has been called.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001584 RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
1585 const CallArgList &CallArgs,
1586 const ObjCMethodDecl *Method) {
John McCall3d1e2c92013-02-12 05:53:35 +00001587 // If we never had to do a null-check, just use the raw result.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001588 if (!NullBB) return result;
John McCall3d1e2c92013-02-12 05:53:35 +00001589
1590 // The continuation block. This will be left null if we don't have an
1591 // IP, which can happen if the method we're calling is marked noreturn.
Craig Topper8a13c412014-05-21 05:09:00 +00001592 llvm::BasicBlock *contBB = nullptr;
1593
John McCall3d1e2c92013-02-12 05:53:35 +00001594 // Finish the call path.
1595 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1596 if (callBB) {
1597 contBB = CGF.createBasicBlock("msgSend.cont");
1598 CGF.Builder.CreateBr(contBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001599 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001600
John McCall3d1e2c92013-02-12 05:53:35 +00001601 // Okay, start emitting the null-receiver block.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001602 CGF.EmitBlock(NullBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001603
John McCall3d1e2c92013-02-12 05:53:35 +00001604 // Release any consumed arguments we've got.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001605 if (Method) {
1606 CallArgList::const_iterator I = CallArgs.begin();
1607 for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1608 e = Method->param_end(); i != e; ++i, ++I) {
1609 const ParmVarDecl *ParamDecl = (*i);
1610 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1611 RValue RV = I->RV;
1612 assert(RV.isScalar() &&
1613 "NullReturnState::complete - arg not on object");
John McCallcdda29c2013-03-13 03:10:54 +00001614 CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001615 }
1616 }
1617 }
John McCall3d1e2c92013-02-12 05:53:35 +00001618
1619 // The phi code below assumes that we haven't needed any control flow yet.
1620 assert(CGF.Builder.GetInsertBlock() == NullBB);
1621
1622 // If we've got a void return, just jump to the continuation block.
1623 if (result.isScalar() && resultType->isVoidType()) {
1624 // No jumps required if the message-send was noreturn.
1625 if (contBB) CGF.EmitBlock(contBB);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001626 return result;
1627 }
1628
John McCall3d1e2c92013-02-12 05:53:35 +00001629 // If we've got a scalar return, build a phi.
1630 if (result.isScalar()) {
1631 // Derive the null-initialization value.
1632 llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
1633
1634 // If no join is necessary, just flow out.
1635 if (!contBB) return RValue::get(null);
1636
1637 // Otherwise, build a phi.
1638 CGF.EmitBlock(contBB);
1639 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1640 phi->addIncoming(result.getScalarVal(), callBB);
1641 phi->addIncoming(null, NullBB);
1642 return RValue::get(phi);
1643 }
1644
1645 // If we've got an aggregate return, null the buffer out.
1646 // FIXME: maybe we should be doing things differently for all the
1647 // cases where the ABI has us returning (1) non-agg values in
1648 // memory or (2) agg values in registers.
1649 if (result.isAggregate()) {
1650 assert(result.isAggregate() && "null init of non-aggregate result?");
John McCall7f416cc2015-09-08 08:05:57 +00001651 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);
John McCall3d1e2c92013-02-12 05:53:35 +00001652 if (contBB) CGF.EmitBlock(contBB);
1653 return result;
1654 }
1655
1656 // Complex types.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001657 CGF.EmitBlock(contBB);
John McCall3d1e2c92013-02-12 05:53:35 +00001658 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1659
1660 // Find the scalar type and its zero value.
1661 llvm::Type *scalarTy = callResult.first->getType();
1662 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1663
1664 // Build phis for both coordinates.
1665 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1666 real->addIncoming(callResult.first, callBB);
1667 real->addIncoming(scalarZero, NullBB);
1668 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1669 imag->addIncoming(callResult.second, callBB);
1670 imag->addIncoming(scalarZero, NullBB);
1671 return RValue::getComplex(real, imag);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001672 }
1673};
1674
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001675} // end anonymous namespace
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001676
1677/* *** Helper Functions *** */
1678
1679/// getConstantGEP() - Help routine to construct simple GEPs.
Owen Anderson170229f2009-07-14 23:10:40 +00001680static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
David Blaikiee3b172a2015-04-02 18:55:21 +00001681 llvm::GlobalVariable *C, unsigned idx0,
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001682 unsigned idx1) {
1683 llvm::Value *Idxs[] = {
Owen Anderson41a75022009-08-13 21:57:51 +00001684 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1685 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001686 };
David Blaikiee3b172a2015-04-02 18:55:21 +00001687 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001688}
1689
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001690/// hasObjCExceptionAttribute - Return true if this class or any super
1691/// class has the __objc_exception__ attribute.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001692static bool hasObjCExceptionAttribute(ASTContext &Context,
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001693 const ObjCInterfaceDecl *OID) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001694 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001695 return true;
1696 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001697 return hasObjCExceptionAttribute(Context, Super);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001698 return false;
1699}
1700
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001701/* *** CGObjCMac Public Interface *** */
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001702
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001703CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
Mike Stump11289f42009-09-09 15:08:12 +00001704 ObjCTypes(cgm) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001705 ObjCABI = 1;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001706 EmitImageInfo();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001707}
1708
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001709/// GetClass - Return a reference to the class for the given interface
1710/// decl.
John McCall882987f2013-02-28 19:01:20 +00001711llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001712 const ObjCInterfaceDecl *ID) {
John McCall882987f2013-02-28 19:01:20 +00001713 return EmitClassRef(CGF, ID);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001714}
1715
1716/// GetSelector - Return the pointer to the unique'd string for this selector.
John McCall7f416cc2015-09-08 08:05:57 +00001717llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1718 return EmitSelector(CGF, Sel);
1719}
1720Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1721 return EmitSelectorAddr(CGF, Sel);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001722}
John McCall882987f2013-02-28 19:01:20 +00001723llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001724 *Method) {
John McCall882987f2013-02-28 19:01:20 +00001725 return EmitSelector(CGF, Method->getSelector());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001726}
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001727
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001728llvm::Constant *CGObjCMac::GetEHType(QualType T) {
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001729 if (T->isObjCIdType() ||
1730 T->isObjCQualifiedIdType()) {
1731 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001732 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001733 }
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001734 if (T->isObjCClassType() ||
1735 T->isObjCQualifiedClassType()) {
1736 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001737 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001738 }
1739 if (T->isObjCObjectPointerType())
1740 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
1741
John McCall2ca705e2010-07-24 00:37:23 +00001742 llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
John McCall2ca705e2010-07-24 00:37:23 +00001743}
1744
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001745/// Generate a constant CFString object.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001746/*
1747 struct __builtin_CFString {
1748 const int *isa; // point to __CFConstantStringClassReference
1749 int flags;
1750 const char *str;
1751 long length;
1752 };
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001753*/
1754
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001755/// or Generate a constant NSString object.
1756/*
1757 struct __builtin_NSString {
1758 const int *isa; // point to __NSConstantStringClassReference
1759 const char *str;
1760 unsigned int length;
1761 };
1762*/
1763
John McCall7f416cc2015-09-08 08:05:57 +00001764ConstantAddress CGObjCCommonMac::GenerateConstantString(
David Chisnall481e3a82010-01-23 02:40:42 +00001765 const StringLiteral *SL) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001766 return (CGM.getLangOpts().NoConstantCFStrings == 0 ?
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001767 CGM.GetAddrOfConstantCFString(SL) :
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001768 CGM.GetAddrOfConstantString(SL));
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001769}
1770
Ted Kremeneke65b0862012-03-06 20:05:56 +00001771enum {
1772 kCFTaggedObjectID_Integer = (1 << 1) + 1
1773};
1774
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001775/// Generates a message send where the super is the receiver. This is
1776/// a message send to self with special delivery semantics indicating
1777/// which class's method should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001778CodeGen::RValue
1779CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001780 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001781 QualType ResultType,
1782 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001783 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001784 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001785 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001786 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001787 const CodeGen::CallArgList &CallArgs,
1788 const ObjCMethodDecl *Method) {
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001789 // Create and init a super structure; this is a (receiver, class)
1790 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00001791 Address ObjCSuper =
1792 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
1793 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001794 llvm::Value *ReceiverAsObject =
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001795 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001796 CGF.Builder.CreateStore(
1797 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00001798 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001799
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001800 // If this is a class message the metaclass is passed as the target.
1801 llvm::Value *Target;
1802 if (IsClassMessage) {
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001803 if (isCategoryImpl) {
1804 // Message sent to 'super' in a class method defined in a category
1805 // implementation requires an odd treatment.
1806 // If we are in a class method, we must retrieve the
1807 // _metaclass_ for the current class, pointed at by
1808 // the class's "isa" pointer. The following assumes that
1809 // isa" is the first ivar in a class (which it must be).
John McCall882987f2013-02-28 19:01:20 +00001810 Target = EmitClassRef(CGF, Class->getSuperClass());
David Blaikie1ed728c2015-04-05 22:45:47 +00001811 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001812 Target = CGF.Builder.CreateAlignedLoad(Target, CGF.getPointerAlign());
Mike Stump658fe022009-07-30 22:28:39 +00001813 } else {
David Blaikie1ed728c2015-04-05 22:45:47 +00001814 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
1815 llvm::Value *SuperPtr =
1816 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00001817 llvm::Value *Super =
1818 CGF.Builder.CreateAlignedLoad(SuperPtr, CGF.getPointerAlign());
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001819 Target = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001820 }
David Blaikie1ed728c2015-04-05 22:45:47 +00001821 } else if (isCategoryImpl)
John McCall882987f2013-02-28 19:01:20 +00001822 Target = EmitClassRef(CGF, Class->getSuperClass());
Fariborz Jahanianda2efb02009-11-14 02:18:31 +00001823 else {
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001824 llvm::Value *ClassPtr = EmitSuperClassRef(Class);
David Blaikie1ed728c2015-04-05 22:45:47 +00001825 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00001826 Target = CGF.Builder.CreateAlignedLoad(ClassPtr, CGF.getPointerAlign());
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001827 }
Mike Stump18bb9282009-05-16 07:57:57 +00001828 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1829 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00001830 llvm::Type *ClassTy =
Daniel Dunbarc722b852008-08-30 03:02:31 +00001831 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbarc475d422008-10-29 22:36:39 +00001832 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
John McCall7f416cc2015-09-08 08:05:57 +00001833 CGF.Builder.CreateStore(Target,
1834 CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
John McCall9e8bb002011-05-14 03:10:52 +00001835 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00001836 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00001837 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00001838 true, CallArgs, Method, Class, ObjCTypes);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001839}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001840
1841/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001842CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001843 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001844 QualType ResultType,
1845 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001846 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001847 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001848 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001849 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00001850 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00001851 EmitSelector(CGF, Sel),
John McCall9e8bb002011-05-14 03:10:52 +00001852 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00001853 false, CallArgs, Method, Class, ObjCTypes);
1854}
1855
1856static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
1857 do {
1858 if (ID->isWeakImported())
1859 return true;
1860 } while ((ID = ID->getSuperClass()));
1861
1862 return false;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00001863}
1864
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001865CodeGen::RValue
John McCall9e8bb002011-05-14 03:10:52 +00001866CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1867 ReturnValueSlot Return,
1868 QualType ResultType,
1869 llvm::Value *Sel,
1870 llvm::Value *Arg0,
1871 QualType Arg0Ty,
1872 bool IsSuper,
1873 const CallArgList &CallArgs,
1874 const ObjCMethodDecl *Method,
John McCall1e3157b2015-09-10 22:27:50 +00001875 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001876 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc722b852008-08-30 03:02:31 +00001877 CallArgList ActualArgs;
Fariborz Jahanian969bc682009-04-24 21:07:43 +00001878 if (!IsSuper)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001879 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001880 ActualArgs.add(RValue::get(Arg0), Arg0Ty);
1881 ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001882 ActualArgs.addFrom(CallArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001883
John McCalla729c622012-02-17 03:33:10 +00001884 // If we're calling a method, use the formal signature.
1885 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001886
Anders Carlsson280e61f12010-06-21 20:59:55 +00001887 if (Method)
Alp Toker314cc812014-01-25 16:55:45 +00001888 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
1889 CGM.getContext().getCanonicalType(ResultType) &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00001890 "Result type mismatch!");
1891
John McCall1e3157b2015-09-10 22:27:50 +00001892 bool ReceiverCanBeNull = true;
1893
1894 // Super dispatch assumes that self is non-null; even the messenger
1895 // doesn't have a null check internally.
1896 if (IsSuper) {
1897 ReceiverCanBeNull = false;
1898
1899 // If this is a direct dispatch of a class method, check whether the class,
1900 // or anything in its hierarchy, was weak-linked.
1901 } else if (ClassReceiver && Method && Method->isClassMethod()) {
1902 ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver);
1903
1904 // If we're emitting a method, and self is const (meaning just ARC, for now),
1905 // and the receiver is a load of self, then self is a valid object.
1906 } else if (auto CurMethod =
1907 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
1908 auto Self = CurMethod->getSelfDecl();
1909 if (Self->getType().isConstQualified()) {
1910 if (auto LI = dyn_cast<llvm::LoadInst>(Arg0->stripPointerCasts())) {
1911 llvm::Value *SelfAddr = CGF.GetAddrOfLocalVar(Self).getPointer();
1912 if (SelfAddr == LI->getPointerOperand()) {
1913 ReceiverCanBeNull = false;
1914 }
1915 }
1916 }
1917 }
1918
John McCall5880fb82011-05-14 21:12:11 +00001919 NullReturnState nullReturn;
1920
Craig Topper8a13c412014-05-21 05:09:00 +00001921 llvm::Constant *Fn = nullptr;
Tim Northovere77cc392014-03-29 13:28:05 +00001922 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall1e3157b2015-09-10 22:27:50 +00001923 if (ReceiverCanBeNull) nullReturn.init(CGF, Arg0);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00001924 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001925 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001926 } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1927 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
1928 : ObjCTypes.getSendFpretFn(IsSuper);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001929 } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
1930 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
1931 : ObjCTypes.getSendFp2retFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00001932 } else {
Tim Northovere77cc392014-03-29 13:28:05 +00001933 // arm64 uses objc_msgSend for stret methods and yet null receiver check
1934 // must be made for it.
Ahmed Bougachaa3df87b2015-10-02 22:41:59 +00001935 if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
Tim Northovere77cc392014-03-29 13:28:05 +00001936 nullReturn.init(CGF, Arg0);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00001937 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001938 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00001939 }
John McCall1e3157b2015-09-10 22:27:50 +00001940
1941 // Emit a null-check if there's a consumed argument other than the receiver.
1942 bool RequiresNullCheck = false;
1943 if (ReceiverCanBeNull && CGM.getLangOpts().ObjCAutoRefCount && Method) {
David Majnemer59f77922016-06-24 04:05:48 +00001944 for (const auto *ParamDecl : Method->parameters()) {
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001945 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1946 if (!nullReturn.NullBB)
1947 nullReturn.init(CGF, Arg0);
John McCall1e3157b2015-09-10 22:27:50 +00001948 RequiresNullCheck = true;
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001949 break;
1950 }
1951 }
John McCall1e3157b2015-09-10 22:27:50 +00001952 }
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001953
John McCall1e3157b2015-09-10 22:27:50 +00001954 llvm::Instruction *CallSite;
John McCalla729c622012-02-17 03:33:10 +00001955 Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
John McCall1e3157b2015-09-10 22:27:50 +00001956 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00001957 CGCalleeInfo(), &CallSite);
John McCall1e3157b2015-09-10 22:27:50 +00001958
1959 // Mark the call as noreturn if the method is marked noreturn and the
1960 // receiver cannot be null.
1961 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {
1962 llvm::CallSite(CallSite).setDoesNotReturn();
1963 }
1964
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001965 return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
John McCall1e3157b2015-09-10 22:27:50 +00001966 RequiresNullCheck ? Method : nullptr);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001967}
1968
John McCall3fd13f062015-10-21 18:06:47 +00001969static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT,
1970 bool pointee = false) {
1971 // Note that GC qualification applies recursively to C pointer types
1972 // that aren't otherwise decorated. This is weird, but it's probably
1973 // an intentional workaround to the unreliable placement of GC qualifiers.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001974 if (FQT.isObjCGCStrong())
1975 return Qualifiers::Strong;
John McCall3fd13f062015-10-21 18:06:47 +00001976
1977 if (FQT.isObjCGCWeak())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001978 return Qualifiers::Weak;
John McCall3fd13f062015-10-21 18:06:47 +00001979
1980 if (auto ownership = FQT.getObjCLifetime()) {
1981 // Ownership does not apply recursively to C pointer types.
1982 if (pointee) return Qualifiers::GCNone;
1983 switch (ownership) {
1984 case Qualifiers::OCL_Weak: return Qualifiers::Weak;
1985 case Qualifiers::OCL_Strong: return Qualifiers::Strong;
1986 case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone;
1987 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");
1988 case Qualifiers::OCL_None: llvm_unreachable("known nonzero");
1989 }
1990 llvm_unreachable("bad objc ownership");
1991 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001992
John McCall3fd13f062015-10-21 18:06:47 +00001993 // Treat unqualified retainable pointers as strong.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001994 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
1995 return Qualifiers::Strong;
1996
John McCall3fd13f062015-10-21 18:06:47 +00001997 // Walk into C pointer types, but only in GC.
1998 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {
1999 if (const PointerType *PT = FQT->getAs<PointerType>())
2000 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);
2001 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002002
2003 return Qualifiers::GCNone;
2004}
2005
John McCall3fd13f062015-10-21 18:06:47 +00002006namespace {
2007 struct IvarInfo {
2008 CharUnits Offset;
2009 uint64_t SizeInWords;
2010 IvarInfo(CharUnits offset, uint64_t sizeInWords)
2011 : Offset(offset), SizeInWords(sizeInWords) {}
2012
2013 // Allow sorting based on byte pos.
2014 bool operator<(const IvarInfo &other) const {
2015 return Offset < other.Offset;
2016 }
2017 };
2018
2019 /// A helper class for building GC layout strings.
2020 class IvarLayoutBuilder {
2021 CodeGenModule &CGM;
2022
2023 /// The start of the layout. Offsets will be relative to this value,
2024 /// and entries less than this value will be silently discarded.
2025 CharUnits InstanceBegin;
2026
2027 /// The end of the layout. Offsets will never exceed this value.
2028 CharUnits InstanceEnd;
2029
2030 /// Whether we're generating the strong layout or the weak layout.
2031 bool ForStrongLayout;
2032
2033 /// Whether the offsets in IvarsInfo might be out-of-order.
2034 bool IsDisordered = false;
2035
2036 llvm::SmallVector<IvarInfo, 8> IvarsInfo;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002037
John McCall3fd13f062015-10-21 18:06:47 +00002038 public:
2039 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,
2040 CharUnits instanceEnd, bool forStrongLayout)
2041 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),
2042 ForStrongLayout(forStrongLayout) {
2043 }
2044
2045 void visitRecord(const RecordType *RT, CharUnits offset);
2046
2047 template <class Iterator, class GetOffsetFn>
2048 void visitAggregate(Iterator begin, Iterator end,
2049 CharUnits aggrOffset,
2050 const GetOffsetFn &getOffset);
2051
2052 void visitField(const FieldDecl *field, CharUnits offset);
2053
2054 /// Add the layout of a block implementation.
2055 void visitBlock(const CGBlockInfo &blockInfo);
2056
2057 /// Is there any information for an interesting bitmap?
2058 bool hasBitmapData() const { return !IvarsInfo.empty(); }
2059
2060 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,
2061 llvm::SmallVectorImpl<unsigned char> &buffer);
2062
2063 static void dump(ArrayRef<unsigned char> buffer) {
2064 const unsigned char *s = buffer.data();
2065 for (unsigned i = 0, e = buffer.size(); i < e; i++)
2066 if (!(s[i] & 0xf0))
2067 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2068 else
2069 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2070 printf("\n");
2071 }
2072 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002073} // end anonymous namespace
John McCall3fd13f062015-10-21 18:06:47 +00002074
John McCall351762c2011-02-07 10:33:21 +00002075llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
2076 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002077
Chris Lattnerece04092012-02-07 00:39:47 +00002078 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
John McCall460ce582015-10-22 18:38:17 +00002079 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
John McCall351762c2011-02-07 10:33:21 +00002080 return nullPtr;
2081
John McCall3fd13f062015-10-21 18:06:47 +00002082 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,
2083 /*for strong layout*/ true);
2084
2085 builder.visitBlock(blockInfo);
2086
2087 if (!builder.hasBitmapData())
2088 return nullPtr;
2089
2090 llvm::SmallVector<unsigned char, 32> buffer;
2091 llvm::Constant *C = builder.buildBitmap(*this, buffer);
John McCallf5ea0722015-10-29 23:36:14 +00002092 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
John McCall3fd13f062015-10-21 18:06:47 +00002093 printf("\n block variable layout for block: ");
2094 builder.dump(buffer);
2095 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002096
John McCall3fd13f062015-10-21 18:06:47 +00002097 return C;
2098}
2099
2100void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {
Fariborz Jahaniancfddabf2010-09-09 00:21:45 +00002101 // __isa is the first field in block descriptor and must assume by runtime's
2102 // convention that it is GC'able.
John McCall3fd13f062015-10-21 18:06:47 +00002103 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));
John McCall351762c2011-02-07 10:33:21 +00002104
2105 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2106
John McCall351762c2011-02-07 10:33:21 +00002107 // Ignore the optional 'this' capture: C++ objects are not assumed
2108 // to be GC'ed.
2109
John McCall3fd13f062015-10-21 18:06:47 +00002110 CharUnits lastFieldOffset;
2111
John McCall351762c2011-02-07 10:33:21 +00002112 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002113 for (const auto &CI : blockDecl->captures()) {
2114 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00002115 QualType type = variable->getType();
2116
2117 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2118
2119 // Ignore constant captures.
2120 if (capture.isConstant()) continue;
2121
John McCall3fd13f062015-10-21 18:06:47 +00002122 CharUnits fieldOffset = capture.getOffset();
2123
2124 // Block fields are not necessarily ordered; if we detect that we're
2125 // adding them out-of-order, make sure we sort later.
2126 if (fieldOffset < lastFieldOffset)
2127 IsDisordered = true;
2128 lastFieldOffset = fieldOffset;
John McCall351762c2011-02-07 10:33:21 +00002129
2130 // __block variables are passed by their descriptor address.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002131 if (CI.isByRef()) {
John McCall3fd13f062015-10-21 18:06:47 +00002132 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
Fariborz Jahanian933c6722010-09-11 01:27:29 +00002133 continue;
John McCall351762c2011-02-07 10:33:21 +00002134 }
2135
2136 assert(!type->isArrayType() && "array variable should not be caught");
2137 if (const RecordType *record = type->getAs<RecordType>()) {
John McCall3fd13f062015-10-21 18:06:47 +00002138 visitRecord(record, fieldOffset);
Fariborz Jahanian903aba32010-08-05 21:00:25 +00002139 continue;
2140 }
Fariborz Jahanianf95e3582010-08-06 16:28:55 +00002141
John McCall351762c2011-02-07 10:33:21 +00002142 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
John McCall351762c2011-02-07 10:33:21 +00002143
John McCall3fd13f062015-10-21 18:06:47 +00002144 if (GCAttr == Qualifiers::Strong) {
2145 assert(CGM.getContext().getTypeSize(type)
2146 == CGM.getTarget().getPointerWidth(0));
2147 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2148 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002149 }
Fariborz Jahanianc05349e2010-08-04 16:57:49 +00002150}
2151
Fariborz Jahanian2c96d302012-11-04 18:19:40 +00002152/// getBlockCaptureLifetime - This routine returns life time of the captured
2153/// block variable for the purpose of block layout meta-data generation. FQT is
2154/// the type of the variable captured in the block.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002155Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2156 bool ByrefLayout) {
John McCall460ce582015-10-22 18:38:17 +00002157 // If it has an ownership qualifier, we're done.
2158 if (auto lifetime = FQT.getObjCLifetime())
2159 return lifetime;
2160
2161 // If it doesn't, and this is ARC, it has no ownership.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002162 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00002163 return Qualifiers::OCL_None;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002164
John McCall460ce582015-10-22 18:38:17 +00002165 // In MRC, retainable pointers are owned by non-__block variables.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002166 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002167 return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002168
2169 return Qualifiers::OCL_None;
2170}
2171
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002172void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2173 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002174 CharUnits FieldOffset,
2175 CharUnits FieldSize) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002176 // __block variables are passed by their descriptor address.
2177 if (IsByref)
2178 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002179 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002180 else if (LifeTime == Qualifiers::OCL_Strong)
2181 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002182 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002183 else if (LifeTime == Qualifiers::OCL_Weak)
2184 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002185 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002186 else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2187 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002188 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002189 else
2190 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2191 FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002192 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002193}
2194
2195void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2196 const RecordDecl *RD,
2197 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002198 CharUnits BytePos, bool &HasUnion,
2199 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002200 bool IsUnion = (RD && RD->isUnion());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002201 CharUnits MaxUnionSize = CharUnits::Zero();
Craig Topper8a13c412014-05-21 05:09:00 +00002202 const FieldDecl *MaxField = nullptr;
2203 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002204 CharUnits MaxFieldOffset = CharUnits::Zero();
2205 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002206
2207 if (RecFields.empty())
2208 return;
John McCallc8e01702013-04-16 22:48:15 +00002209 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002210
2211 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2212 const FieldDecl *Field = RecFields[i];
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002213 // Note that 'i' here is actually the field index inside RD of Field,
2214 // although this dependency is hidden.
2215 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002216 CharUnits FieldOffset =
2217 CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002218
2219 // Skip over unnamed or bitfields
2220 if (!Field->getIdentifier() || Field->isBitField()) {
2221 LastFieldBitfieldOrUnnamed = Field;
2222 LastBitfieldOrUnnamedOffset = FieldOffset;
2223 continue;
2224 }
Craig Topper8a13c412014-05-21 05:09:00 +00002225
2226 LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002227 QualType FQT = Field->getType();
2228 if (FQT->isRecordType() || FQT->isUnionType()) {
2229 if (FQT->isUnionType())
2230 HasUnion = true;
2231
2232 BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
2233 BytePos + FieldOffset, HasUnion);
2234 continue;
2235 }
2236
2237 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2238 const ConstantArrayType *CArray =
2239 dyn_cast_or_null<ConstantArrayType>(Array);
2240 uint64_t ElCount = CArray->getSize().getZExtValue();
2241 assert(CArray && "only array with known element size is supported");
2242 FQT = CArray->getElementType();
2243 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2244 const ConstantArrayType *CArray =
2245 dyn_cast_or_null<ConstantArrayType>(Array);
2246 ElCount *= CArray->getSize().getZExtValue();
2247 FQT = CArray->getElementType();
2248 }
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002249 if (FQT->isRecordType() && ElCount) {
2250 int OldIndex = RunSkipBlockVars.size() - 1;
2251 const RecordType *RT = FQT->getAs<RecordType>();
2252 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
2253 HasUnion);
2254
2255 // Replicate layout information for each array element. Note that
2256 // one element is already done.
2257 uint64_t ElIx = 1;
2258 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002259 CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002260 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2261 RunSkipBlockVars.push_back(
2262 RUN_SKIP(RunSkipBlockVars[i].opcode,
2263 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2264 RunSkipBlockVars[i].block_var_size));
2265 }
2266 continue;
2267 }
2268 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002269 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002270 if (IsUnion) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002271 CharUnits UnionIvarSize = FieldSize;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002272 if (UnionIvarSize > MaxUnionSize) {
2273 MaxUnionSize = UnionIvarSize;
2274 MaxField = Field;
2275 MaxFieldOffset = FieldOffset;
2276 }
2277 } else {
2278 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002279 getBlockCaptureLifetime(FQT, ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002280 BytePos + FieldOffset,
2281 FieldSize);
2282 }
2283 }
2284
2285 if (LastFieldBitfieldOrUnnamed) {
2286 if (LastFieldBitfieldOrUnnamed->isBitField()) {
2287 // Last field was a bitfield. Must update the info.
2288 uint64_t BitFieldSize
2289 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002290 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
Eli Friedman8cbca202012-11-06 22:15:52 +00002291 ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002292 CharUnits Size = CharUnits::fromQuantity(UnsSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002293 Size += LastBitfieldOrUnnamedOffset;
2294 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002295 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2296 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002297 BytePos + LastBitfieldOrUnnamedOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002298 Size);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002299 } else {
2300 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2301 // Last field was unnamed. Must update skip info.
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002302 CharUnits FieldSize
2303 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002304 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002305 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2306 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002307 BytePos + LastBitfieldOrUnnamedOffset,
2308 FieldSize);
2309 }
2310 }
2311
2312 if (MaxField)
2313 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002314 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002315 BytePos + MaxFieldOffset,
2316 MaxUnionSize);
2317}
2318
2319void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002320 CharUnits BytePos,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002321 bool &HasUnion,
2322 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002323 const RecordDecl *RD = RT->getDecl();
Aaron Ballman62e47c42014-03-10 13:43:55 +00002324 SmallVector<const FieldDecl*, 16> Fields(RD->fields());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002325 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2326 const llvm::StructLayout *RecLayout =
2327 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
2328
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002329 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002330}
2331
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002332/// InlineLayoutInstruction - This routine produce an inline instruction for the
2333/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2334/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2335/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2336/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2337/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2338/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2339/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2340/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2341uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2342 SmallVectorImpl<unsigned char> &Layout) {
2343 uint64_t Result = 0;
2344 if (Layout.size() <= 3) {
2345 unsigned size = Layout.size();
2346 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2347 unsigned char inst;
2348 enum BLOCK_LAYOUT_OPCODE opcode ;
2349 switch (size) {
2350 case 3:
2351 inst = Layout[0];
2352 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2353 if (opcode == BLOCK_LAYOUT_STRONG)
2354 strong_word_count = (inst & 0xF)+1;
2355 else
2356 return 0;
2357 inst = Layout[1];
2358 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2359 if (opcode == BLOCK_LAYOUT_BYREF)
2360 byref_word_count = (inst & 0xF)+1;
2361 else
2362 return 0;
2363 inst = Layout[2];
2364 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2365 if (opcode == BLOCK_LAYOUT_WEAK)
2366 weak_word_count = (inst & 0xF)+1;
2367 else
2368 return 0;
2369 break;
2370
2371 case 2:
2372 inst = Layout[0];
2373 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2374 if (opcode == BLOCK_LAYOUT_STRONG) {
2375 strong_word_count = (inst & 0xF)+1;
2376 inst = Layout[1];
2377 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2378 if (opcode == BLOCK_LAYOUT_BYREF)
2379 byref_word_count = (inst & 0xF)+1;
2380 else if (opcode == BLOCK_LAYOUT_WEAK)
2381 weak_word_count = (inst & 0xF)+1;
2382 else
2383 return 0;
2384 }
2385 else if (opcode == BLOCK_LAYOUT_BYREF) {
2386 byref_word_count = (inst & 0xF)+1;
2387 inst = Layout[1];
2388 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2389 if (opcode == BLOCK_LAYOUT_WEAK)
2390 weak_word_count = (inst & 0xF)+1;
2391 else
2392 return 0;
2393 }
2394 else
2395 return 0;
2396 break;
2397
2398 case 1:
2399 inst = Layout[0];
2400 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2401 if (opcode == BLOCK_LAYOUT_STRONG)
2402 strong_word_count = (inst & 0xF)+1;
2403 else if (opcode == BLOCK_LAYOUT_BYREF)
2404 byref_word_count = (inst & 0xF)+1;
2405 else if (opcode == BLOCK_LAYOUT_WEAK)
2406 weak_word_count = (inst & 0xF)+1;
2407 else
2408 return 0;
2409 break;
2410
2411 default:
2412 return 0;
2413 }
2414
2415 // Cannot inline when any of the word counts is 15. Because this is one less
2416 // than the actual work count (so 15 means 16 actual word counts),
2417 // and we can only display 0 thru 15 word counts.
2418 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2419 return 0;
2420
2421 unsigned count =
2422 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
2423
2424 if (size == count) {
2425 if (strong_word_count)
2426 Result = strong_word_count;
2427 Result <<= 4;
2428 if (byref_word_count)
2429 Result += byref_word_count;
2430 Result <<= 4;
2431 if (weak_word_count)
2432 Result += weak_word_count;
2433 }
2434 }
2435 return Result;
2436}
2437
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002438llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2439 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2440 if (RunSkipBlockVars.empty())
2441 return nullPtr;
John McCallc8e01702013-04-16 22:48:15 +00002442 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2443 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002444 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2445
2446 // Sort on byte position; captures might not be allocated in order,
2447 // and unions can do funny things.
2448 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2449 SmallVector<unsigned char, 16> Layout;
2450
2451 unsigned size = RunSkipBlockVars.size();
2452 for (unsigned i = 0; i < size; i++) {
2453 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2454 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2455 CharUnits end_byte_pos = start_byte_pos;
2456 unsigned j = i+1;
2457 while (j < size) {
2458 if (opcode == RunSkipBlockVars[j].opcode) {
2459 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2460 i++;
2461 }
2462 else
2463 break;
2464 }
2465 CharUnits size_in_bytes =
2466 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2467 if (j < size) {
2468 CharUnits gap =
2469 RunSkipBlockVars[j].block_var_bytepos -
2470 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2471 size_in_bytes += gap;
2472 }
2473 CharUnits residue_in_bytes = CharUnits::Zero();
2474 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2475 residue_in_bytes = size_in_bytes % WordSizeInBytes;
2476 size_in_bytes -= residue_in_bytes;
2477 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2478 }
2479
2480 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2481 while (size_in_words >= 16) {
2482 // Note that value in imm. is one less that the actual
2483 // value. So, 0xf means 16 words follow!
2484 unsigned char inst = (opcode << 4) | 0xf;
2485 Layout.push_back(inst);
2486 size_in_words -= 16;
2487 }
2488 if (size_in_words > 0) {
2489 // Note that value in imm. is one less that the actual
2490 // value. So, we subtract 1 away!
2491 unsigned char inst = (opcode << 4) | (size_in_words-1);
2492 Layout.push_back(inst);
2493 }
2494 if (residue_in_bytes > CharUnits::Zero()) {
2495 unsigned char inst =
2496 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2497 Layout.push_back(inst);
2498 }
2499 }
2500
John McCall7f416cc2015-09-08 08:05:57 +00002501 while (!Layout.empty()) {
2502 unsigned char inst = Layout.back();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002503 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2504 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2505 Layout.pop_back();
2506 else
2507 break;
2508 }
2509
2510 uint64_t Result = InlineLayoutInstruction(Layout);
2511 if (Result != 0) {
2512 // Block variable layout instruction has been inlined.
2513 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2514 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002515 printf("\n Inline BYREF variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002516 else
John McCall7f416cc2015-09-08 08:05:57 +00002517 printf("\n Inline block variable layout: ");
2518 printf("0x0%" PRIx64 "", Result);
2519 if (auto numStrong = (Result & 0xF00) >> 8)
2520 printf(", BL_STRONG:%d", (int) numStrong);
2521 if (auto numByref = (Result & 0x0F0) >> 4)
2522 printf(", BL_BYREF:%d", (int) numByref);
2523 if (auto numWeak = (Result & 0x00F) >> 0)
2524 printf(", BL_WEAK:%d", (int) numWeak);
2525 printf(", BL_OPERATOR:0\n");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002526 }
Vedant Kumar3ed0df02015-12-21 19:43:25 +00002527 return llvm::ConstantInt::get(CGM.IntPtrTy, Result);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002528 }
2529
2530 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2531 Layout.push_back(inst);
2532 std::string BitMap;
2533 for (unsigned i = 0, e = Layout.size(); i != e; i++)
2534 BitMap += Layout[i];
2535
2536 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2537 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002538 printf("\n Byref variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002539 else
John McCall7f416cc2015-09-08 08:05:57 +00002540 printf("\n Block variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002541 for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2542 unsigned char inst = BitMap[i];
2543 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2544 unsigned delta = 1;
2545 switch (opcode) {
2546 case BLOCK_LAYOUT_OPERATOR:
2547 printf("BL_OPERATOR:");
2548 delta = 0;
2549 break;
2550 case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2551 printf("BL_NON_OBJECT_BYTES:");
2552 break;
2553 case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2554 printf("BL_NON_OBJECT_WORD:");
2555 break;
2556 case BLOCK_LAYOUT_STRONG:
2557 printf("BL_STRONG:");
2558 break;
2559 case BLOCK_LAYOUT_BYREF:
2560 printf("BL_BYREF:");
2561 break;
2562 case BLOCK_LAYOUT_WEAK:
2563 printf("BL_WEAK:");
2564 break;
2565 case BLOCK_LAYOUT_UNRETAINED:
2566 printf("BL_UNRETAINED:");
2567 break;
2568 }
2569 // Actual value of word count is one more that what is in the imm.
2570 // field of the instruction
2571 printf("%d", (inst & 0xf) + delta);
2572 if (i < e-1)
2573 printf(", ");
2574 else
2575 printf("\n");
2576 }
2577 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002578
2579 llvm::GlobalVariable *Entry = CreateMetadataVar(
2580 "OBJC_CLASS_NAME_",
2581 llvm::ConstantDataArray::getString(VMContext, BitMap, false),
John McCall7f416cc2015-09-08 08:05:57 +00002582 "__TEXT,__objc_classname,cstring_literals", CharUnits::One(), true);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002583 return getConstantGEP(VMContext, Entry, 0, 0);
2584}
2585
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002586llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2587 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002588 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2589
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002590 RunSkipBlockVars.clear();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002591 bool hasUnion = false;
2592
John McCallc8e01702013-04-16 22:48:15 +00002593 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2594 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002595 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2596
2597 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2598
2599 // Calculate the basic layout of the block structure.
2600 const llvm::StructLayout *layout =
2601 CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
2602
2603 // Ignore the optional 'this' capture: C++ objects are not assumed
2604 // to be GC'ed.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +00002605 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2606 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2607 blockInfo.BlockHeaderForcedGapOffset,
2608 blockInfo.BlockHeaderForcedGapSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002609 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002610 for (const auto &CI : blockDecl->captures()) {
2611 const VarDecl *variable = CI.getVariable();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002612 QualType type = variable->getType();
2613
2614 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2615
2616 // Ignore constant captures.
2617 if (capture.isConstant()) continue;
2618
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002619 CharUnits fieldOffset =
2620 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002621
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002622 assert(!type->isArrayType() && "array variable should not be caught");
Aaron Ballman9371dd22014-03-14 18:34:04 +00002623 if (!CI.isByRef())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002624 if (const RecordType *record = type->getAs<RecordType>()) {
2625 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2626 continue;
2627 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002628 CharUnits fieldSize;
Aaron Ballman9371dd22014-03-14 18:34:04 +00002629 if (CI.isByRef())
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002630 fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2631 else
2632 fieldSize = CGM.getContext().getTypeSizeInChars(type);
Aaron Ballman9371dd22014-03-14 18:34:04 +00002633 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002634 fieldOffset, fieldSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002635 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002636 return getBitmapBlockLayout(false);
2637}
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002638
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002639llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2640 QualType T) {
2641 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2642 assert(!T->isArrayType() && "__block array variable should not be caught");
2643 CharUnits fieldOffset;
2644 RunSkipBlockVars.clear();
2645 bool hasUnion = false;
2646 if (const RecordType *record = T->getAs<RecordType>()) {
2647 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2648 llvm::Constant *Result = getBitmapBlockLayout(true);
Vedant Kumar2f5bb1152015-12-21 20:21:15 +00002649 if (isa<llvm::ConstantInt>(Result))
2650 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002651 return Result;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002652 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002653 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2654 return nullPtr;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002655}
2656
John McCall882987f2013-02-28 19:01:20 +00002657llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002658 const ObjCProtocolDecl *PD) {
Daniel Dunbar7050c552008-09-04 04:33:15 +00002659 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002660 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar7050c552008-09-04 04:33:15 +00002661 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2662
Owen Andersonade90fd2009-07-29 18:54:39 +00002663 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00002664 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002665}
2666
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002667void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stump18bb9282009-05-16 07:57:57 +00002668 // FIXME: We shouldn't need this, the protocol decl should contain enough
2669 // information to tell us whether this was a declaration or a definition.
Daniel Dunbarc475d422008-10-29 22:36:39 +00002670 DefinedProtocols.insert(PD->getIdentifier());
2671
2672 // If we have generated a forward reference to this protocol, emit
2673 // it now. Otherwise do nothing, the protocol objects are lazily
2674 // emitted.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002675 if (Protocols.count(PD->getIdentifier()))
Daniel Dunbarc475d422008-10-29 22:36:39 +00002676 GetOrEmitProtocol(PD);
2677}
2678
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002679llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002680 if (DefinedProtocols.count(PD->getIdentifier()))
2681 return GetOrEmitProtocol(PD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002682
Daniel Dunbarc475d422008-10-29 22:36:39 +00002683 return GetOrEmitProtocolRef(PD);
2684}
2685
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002686llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(
2687 CodeGenFunction &CGF,
2688 const ObjCInterfaceDecl *ID,
2689 ObjCCommonTypesHelper &ObjCTypes) {
2690 llvm::Constant *lookUpClassFn = ObjCTypes.getLookUpClassFn();
2691
2692 llvm::Value *className =
2693 CGF.CGM.GetAddrOfConstantCString(ID->getObjCRuntimeNameAsString())
2694 .getPointer();
2695 ASTContext &ctx = CGF.CGM.getContext();
2696 className =
2697 CGF.Builder.CreateBitCast(className,
2698 CGF.ConvertType(
2699 ctx.getPointerType(ctx.CharTy.withConst())));
2700 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);
2701 call->setDoesNotThrow();
2702 return call;
2703}
2704
Daniel Dunbarb036db82008-08-13 03:21:16 +00002705/*
Rafael Espindolaf9e1e5e2014-02-20 14:09:04 +00002706// Objective-C 1.0 extensions
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002707struct _objc_protocol {
2708struct _objc_protocol_extension *isa;
2709char *protocol_name;
2710struct _objc_protocol_list *protocol_list;
2711struct _objc__method_prototype_list *instance_methods;
2712struct _objc__method_prototype_list *class_methods
2713};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002714
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002715See EmitProtocolExtension().
Daniel Dunbarb036db82008-08-13 03:21:16 +00002716*/
Daniel Dunbarc475d422008-10-29 22:36:39 +00002717llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00002718 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbarc475d422008-10-29 22:36:39 +00002719
2720 // Early exit if a defining object has already been generated.
2721 if (Entry && Entry->hasInitializer())
2722 return Entry;
2723
Douglas Gregora715bff2012-01-01 19:51:50 +00002724 // Use the protocol definition, if there is one.
2725 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2726 PD = Def;
2727
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002728 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002729 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002730 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2731
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002732 // Construct method lists.
2733 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2734 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002735 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002736 for (const auto *MD : PD->instance_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002737 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002738 if (!C)
2739 return GetOrEmitProtocolRef(PD);
2740
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002741 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2742 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002743 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002744 } else {
2745 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002746 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002747 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002748 }
2749
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002750 for (const auto *MD : PD->class_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002751 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002752 if (!C)
2753 return GetOrEmitProtocolRef(PD);
2754
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002755 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2756 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002757 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002758 } else {
2759 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002760 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002761 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002762 }
2763
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002764 MethodTypesExt.insert(MethodTypesExt.end(),
2765 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
2766
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002767 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002768 EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
2769 MethodTypesExt),
2770 GetClassName(PD->getObjCRuntimeNameAsString()),
2771 EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
2772 PD->protocol_begin(), PD->protocol_end()),
2773 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
2774 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2775 InstanceMethods),
2776 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
2777 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2778 ClassMethods)};
Owen Anderson0e0189d2009-07-27 22:29:56 +00002779 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00002780 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002781
Daniel Dunbarb036db82008-08-13 03:21:16 +00002782 if (Entry) {
Rafael Espindola5d117f32014-03-06 01:10:46 +00002783 // Already created, update the initializer.
Rafael Espindolab3262952014-05-09 00:43:37 +00002784 assert(Entry->hasPrivateLinkage());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002785 Entry->setInitializer(Init);
2786 } else {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002787 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2788 false, llvm::GlobalValue::PrivateLinkage,
2789 Init, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002790 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002791 // FIXME: Is this necessary? Why only for protocol?
2792 Entry->setAlignment(4);
John McCallf9582a72012-03-30 21:29:05 +00002793
2794 Protocols[PD->getIdentifier()] = Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002795 }
Rafael Espindola060062a2014-03-06 22:15:10 +00002796 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbarc475d422008-10-29 22:36:39 +00002797
2798 return Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002799}
2800
Daniel Dunbarc475d422008-10-29 22:36:39 +00002801llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00002802 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
2803
2804 if (!Entry) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002805 // We use the initializer as a marker of whether this is a forward
2806 // reference or not. At module finalization we add the empty
2807 // contents for protocols which were referenced but never defined.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002808 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2809 false, llvm::GlobalValue::PrivateLinkage,
2810 nullptr, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002811 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002812 // FIXME: Is this necessary? Why only for protocol?
2813 Entry->setAlignment(4);
2814 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002815
Daniel Dunbarb036db82008-08-13 03:21:16 +00002816 return Entry;
2817}
2818
2819/*
2820 struct _objc_protocol_extension {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002821 uint32_t size;
2822 struct objc_method_description_list *optional_instance_methods;
2823 struct objc_method_description_list *optional_class_methods;
2824 struct objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002825 const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00002826 struct objc_property_list *class_properties;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002827 };
2828*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002829llvm::Constant *
2830CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002831 ArrayRef<llvm::Constant*> OptInstanceMethods,
2832 ArrayRef<llvm::Constant*> OptClassMethods,
2833 ArrayRef<llvm::Constant*> MethodTypesExt) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002834 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00002835 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002836 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002837 llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
2838 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getName(),
2839 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2840 OptInstanceMethods),
2841 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
2842 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2843 OptClassMethods),
2844 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
Manman Renad0e7912016-01-29 19:22:54 +00002845 ObjCTypes, false),
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002846 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
Manman Rence7bff52016-01-29 23:46:55 +00002847 MethodTypesExt, ObjCTypes),
2848 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,
2849 PD, ObjCTypes, true)};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002850
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002851 // Return null if no extension bits are used.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002852 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
Manman Rence7bff52016-01-29 23:46:55 +00002853 Values[3]->isNullValue() && Values[4]->isNullValue() &&
2854 Values[5]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00002855 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002856
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002857 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00002858 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002859
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002860 // No special section, but goes in llvm.used
Alp Toker541d5072014-06-07 23:30:53 +00002861 return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00002862 StringRef(), CGM.getPointerAlign(), true);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002863}
2864
2865/*
2866 struct objc_protocol_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002867 struct objc_protocol_list *next;
2868 long count;
2869 Protocol *list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00002870 };
2871*/
Daniel Dunbardec75f82008-08-21 21:57:41 +00002872llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002873CGObjCMac::EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00002874 ObjCProtocolDecl::protocol_iterator begin,
2875 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002876 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002877
Daniel Dunbardec75f82008-08-21 21:57:41 +00002878 for (; begin != end; ++begin)
2879 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002880
2881 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002882 if (ProtocolRefs.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00002883 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002884
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002885 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00002886 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002887
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002888 llvm::Constant *Values[3];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002889 // This field is only used by the runtime.
Owen Anderson0b75f232009-07-31 20:28:54 +00002890 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002891 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002892 ProtocolRefs.size() - 1);
2893 Values[2] =
2894 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
2895 ProtocolRefs.size()),
Daniel Dunbarb036db82008-08-13 03:21:16 +00002896 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002897
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002898 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002899 llvm::GlobalVariable *GV =
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002900 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00002901 CGM.getPointerAlign(), false);
Owen Andersonade90fd2009-07-29 18:54:39 +00002902 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002903}
2904
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002905void CGObjCCommonMac::
2906PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002907 SmallVectorImpl<llvm::Constant *> &Properties,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002908 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +00002909 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +00002910 const ObjCCommonTypesHelper &ObjCTypes,
2911 bool IsClassProperty) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002912 for (const auto *P : Proto->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002913 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2914 IsClassProperty);
2915
2916 for (const auto *PD : Proto->properties()) {
2917 if (IsClassProperty != PD->isClassProperty())
2918 continue;
David Blaikie82e95a32014-11-19 07:49:47 +00002919 if (!PropertySet.insert(PD->getIdentifier()).second)
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002920 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002921 llvm::Constant *Prop[] = {
2922 GetPropertyName(PD->getIdentifier()),
2923 GetPropertyTypeString(PD, Container)
2924 };
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002925 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2926 }
2927}
2928
Daniel Dunbarb036db82008-08-13 03:21:16 +00002929/*
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002930 struct _objc_property {
Bill Wendlinga515b582012-02-09 22:16:49 +00002931 const char * const name;
2932 const char * const attributes;
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002933 };
2934
2935 struct _objc_property_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002936 uint32_t entsize; // sizeof (struct _objc_property)
2937 uint32_t prop_count;
2938 struct _objc_property[prop_count];
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002939 };
2940*/
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002941llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002942 const Decl *Container,
2943 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +00002944 const ObjCCommonTypesHelper &ObjCTypes,
2945 bool IsClassProperty) {
Manman Ren01b705e2016-04-19 19:05:03 +00002946 if (IsClassProperty) {
2947 // Make this entry NULL for OS X with deployment target < 10.11, for iOS
2948 // with deployment target < 9.0.
2949 const llvm::Triple &Triple = CGM.getTarget().getTriple();
2950 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||
2951 (Triple.isiOS() && Triple.isOSVersionLT(9)))
2952 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2953 }
2954
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002955 SmallVector<llvm::Constant *, 16> Properties;
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002956 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
Nico Weber08c93332015-12-03 17:44:51 +00002957
2958 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2959 llvm::Constant *Prop[] = {GetPropertyName(PD->getIdentifier()),
2960 GetPropertyTypeString(PD, Container)};
2961 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2962 };
2963 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
2964 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
Manman Renad0e7912016-01-29 19:22:54 +00002965 for (auto *PD : ClassExt->properties()) {
2966 if (IsClassProperty != PD->isClassProperty())
2967 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002968 PropertySet.insert(PD->getIdentifier());
2969 AddProperty(PD);
2970 }
Manman Renad0e7912016-01-29 19:22:54 +00002971
2972 for (const auto *PD : OCD->properties()) {
2973 if (IsClassProperty != PD->isClassProperty())
2974 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002975 // Don't emit duplicate metadata for properties that were already in a
2976 // class extension.
2977 if (!PropertySet.insert(PD->getIdentifier()).second)
2978 continue;
2979 AddProperty(PD);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002980 }
Nico Weber08c93332015-12-03 17:44:51 +00002981
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00002982 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002983 for (const auto *P : OID->all_referenced_protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002984 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2985 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00002986 }
2987 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002988 for (const auto *P : CD->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002989 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2990 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00002991 }
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002992
2993 // Return null for empty list.
2994 if (Properties.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00002995 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002996
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002997 unsigned PropertySize =
Micah Villmowdd31ca12012-10-08 16:25:52 +00002998 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002999 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003000 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
3001 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003002 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003003 Properties.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003004 Values[2] = llvm::ConstantArray::get(AT, Properties);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003005 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003006
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003007 llvm::GlobalVariable *GV =
3008 CreateMetadataVar(Name, Init,
3009 (ObjCABI == 2) ? "__DATA, __objc_const" :
Daniel Dunbarb25452a2009-04-15 02:56:18 +00003010 "__OBJC,__property,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00003011 CGM.getPointerAlign(),
Daniel Dunbarb25452a2009-04-15 02:56:18 +00003012 true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003013 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003014}
3015
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003016llvm::Constant *
3017CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
3018 ArrayRef<llvm::Constant*> MethodTypes,
3019 const ObjCCommonTypesHelper &ObjCTypes) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003020 // Return null for empty list.
3021 if (MethodTypes.empty())
3022 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
3023
3024 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3025 MethodTypes.size());
3026 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
3027
Alp Toker541d5072014-06-07 23:30:53 +00003028 llvm::GlobalVariable *GV = CreateMetadataVar(
3029 Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(),
John McCall7f416cc2015-09-08 08:05:57 +00003030 CGM.getPointerAlign(), true);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003031 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
3032}
3033
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003034/*
Daniel Dunbarb036db82008-08-13 03:21:16 +00003035 struct objc_method_description_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003036 int count;
3037 struct objc_method_description list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00003038 };
3039*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003040llvm::Constant *
3041CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003042 llvm::Constant *Desc[] = {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003043 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003044 ObjCTypes.SelectorPtrTy),
3045 GetMethodVarType(MD)
3046 };
Douglas Gregora9d84932011-05-27 01:19:52 +00003047 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00003048 return nullptr;
3049
Owen Anderson0e0189d2009-07-27 22:29:56 +00003050 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003051 Desc);
3052}
Daniel Dunbarb036db82008-08-13 03:21:16 +00003053
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003054llvm::Constant *
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003055CGObjCMac::EmitMethodDescList(Twine Name, StringRef Section,
3056 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00003057 // Return null for empty list.
3058 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003059 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003060
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003061 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003062 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003063 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003064 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003065 Values[1] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003066 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003067
John McCall7f416cc2015-09-08 08:05:57 +00003068 llvm::GlobalVariable *GV =
3069 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003070 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003071 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003072}
3073
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003074/*
3075 struct _objc_category {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003076 char *category_name;
3077 char *class_name;
3078 struct _objc_method_list *instance_methods;
3079 struct _objc_method_list *class_methods;
3080 struct _objc_protocol_list *protocols;
3081 uint32_t size; // <rdar://4585769>
3082 struct _objc_property_list *instance_properties;
Manman Ren96df0b32016-01-29 23:45:01 +00003083 struct _objc_property_list *class_properties;
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003084 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003085*/
Daniel Dunbar92992502008-08-15 22:20:32 +00003086void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00003087 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003088
Mike Stump18bb9282009-05-16 07:57:57 +00003089 // FIXME: This is poor design, the OCD should have a pointer to the category
3090 // decl. Additionally, note that Category can be null for the @implementation
3091 // w/o an @interface case. Sema should just create one for us as it does for
3092 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003093 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003094 const ObjCCategoryDecl *Category =
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003095 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003096
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003097 SmallString<256> ExtName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003098 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
3099 << OCD->getName();
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003100
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003101 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003102 for (const auto *I : OCD->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003103 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003104 InstanceMethods.push_back(GetMethodConstant(I));
3105
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003106 for (const auto *I : OCD->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003107 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003108 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003109
Manman Ren96df0b32016-01-29 23:45:01 +00003110 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003111 Values[0] = GetClassName(OCD->getName());
3112 Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString());
Fariborz Jahaniane55f8662009-04-29 20:40:05 +00003113 LazySymbols.insert(Interface->getIdentifier());
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003114 Values[2] = EmitMethodList("OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
3115 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
3116 InstanceMethods);
3117 Values[3] = EmitMethodList("OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
3118 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
3119 ClassMethods);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003120 if (Category) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003121 Values[4] =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003122 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
3123 Category->protocol_begin(), Category->protocol_end());
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003124 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003125 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003126 }
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003127 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003128
3129 // If there is no category @interface then there can be no properties.
3130 if (Category) {
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003131 Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00003132 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00003133 Values[7] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
3134 OCD, Category, ObjCTypes, true);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003135 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003136 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00003137 Values[7] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003138 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003139
Owen Anderson0e0189d2009-07-27 22:29:56 +00003140 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003141 Values);
3142
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003143 llvm::GlobalVariable *GV =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003144 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003145 "__OBJC,__category,regular,no_dead_strip",
3146 CGM.getPointerAlign(), true);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003147 DefinedCategories.push_back(GV);
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +00003148 DefinedCategoryNames.insert(ExtName.str());
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003149 // method definition entries must be clear for next implementation.
3150 MethodDefinitions.clear();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003151}
3152
John McCallef19dbb2012-10-17 04:53:23 +00003153enum FragileClassFlags {
John McCall460ce582015-10-22 18:38:17 +00003154 /// Apparently: is not a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003155 FragileABI_Class_Factory = 0x00001,
John McCall460ce582015-10-22 18:38:17 +00003156
3157 /// Is a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003158 FragileABI_Class_Meta = 0x00002,
John McCall460ce582015-10-22 18:38:17 +00003159
3160 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003161 FragileABI_Class_HasCXXStructors = 0x02000,
John McCall460ce582015-10-22 18:38:17 +00003162
3163 /// Has hidden visibility.
John McCall09ec1ec2015-10-21 22:06:03 +00003164 FragileABI_Class_Hidden = 0x20000,
John McCall460ce582015-10-22 18:38:17 +00003165
3166 /// Class implementation was compiled under ARC.
3167 FragileABI_Class_CompiledByARC = 0x04000000,
3168
3169 /// Class implementation was compiled under MRC and has MRC weak ivars.
3170 /// Exclusive with CompiledByARC.
3171 FragileABI_Class_HasMRCWeakIvars = 0x08000000,
John McCallef19dbb2012-10-17 04:53:23 +00003172};
3173
3174enum NonFragileClassFlags {
3175 /// Is a meta-class.
3176 NonFragileABI_Class_Meta = 0x00001,
3177
3178 /// Is a root class.
3179 NonFragileABI_Class_Root = 0x00002,
3180
John McCall460ce582015-10-22 18:38:17 +00003181 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003182 NonFragileABI_Class_HasCXXStructors = 0x00004,
3183
3184 /// Has hidden visibility.
3185 NonFragileABI_Class_Hidden = 0x00010,
3186
3187 /// Has the exception attribute.
3188 NonFragileABI_Class_Exception = 0x00020,
3189
3190 /// (Obsolete) ARC-specific: this class has a .release_ivars method
3191 NonFragileABI_Class_HasIvarReleaser = 0x00040,
3192
3193 /// Class implementation was compiled under ARC.
John McCall0d54a172012-10-17 04:53:31 +00003194 NonFragileABI_Class_CompiledByARC = 0x00080,
3195
3196 /// Class has non-trivial destructors, but zero-initialization is okay.
John McCall460ce582015-10-22 18:38:17 +00003197 NonFragileABI_Class_HasCXXDestructorOnly = 0x00100,
3198
3199 /// Class implementation was compiled under MRC and has MRC weak ivars.
3200 /// Exclusive with CompiledByARC.
3201 NonFragileABI_Class_HasMRCWeakIvars = 0x00200,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003202};
3203
John McCall460ce582015-10-22 18:38:17 +00003204static bool hasWeakMember(QualType type) {
3205 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {
3206 return true;
3207 }
3208
3209 if (auto recType = type->getAs<RecordType>()) {
3210 for (auto field : recType->getDecl()->fields()) {
3211 if (hasWeakMember(field->getType()))
3212 return true;
3213 }
3214 }
3215
3216 return false;
3217}
3218
3219/// For compatibility, we only want to set the "HasMRCWeakIvars" flag
3220/// (and actually fill in a layout string) if we really do have any
3221/// __weak ivars.
3222static bool hasMRCWeakIvars(CodeGenModule &CGM,
3223 const ObjCImplementationDecl *ID) {
3224 if (!CGM.getLangOpts().ObjCWeak) return false;
3225 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
3226
3227 for (const ObjCIvarDecl *ivar =
3228 ID->getClassInterface()->all_declared_ivar_begin();
3229 ivar; ivar = ivar->getNextIvar()) {
3230 if (hasWeakMember(ivar->getType()))
3231 return true;
3232 }
3233
3234 return false;
3235}
3236
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003237/*
3238 struct _objc_class {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003239 Class isa;
3240 Class super_class;
3241 const char *name;
3242 long version;
3243 long info;
3244 long instance_size;
3245 struct _objc_ivar_list *ivars;
3246 struct _objc_method_list *methods;
3247 struct _objc_cache *cache;
3248 struct _objc_protocol_list *protocols;
3249 // Objective-C 1.0 extensions (<rdr://4585769>)
3250 const char *ivar_layout;
3251 struct _objc_class_ext *ext;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003252 };
3253
3254 See EmitClassExtension();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003255*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003256void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003257 DefinedSymbols.insert(ID->getIdentifier());
3258
Chris Lattner86d7d912008-11-24 03:54:41 +00003259 std::string ClassName = ID->getNameAsString();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003260 // FIXME: Gross
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003261 ObjCInterfaceDecl *Interface =
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003262 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003263 llvm::Constant *Protocols =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003264 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3265 Interface->all_referenced_protocol_begin(),
3266 Interface->all_referenced_protocol_end());
John McCallef19dbb2012-10-17 04:53:23 +00003267 unsigned Flags = FragileABI_Class_Factory;
John McCall0d54a172012-10-17 04:53:31 +00003268 if (ID->hasNonZeroConstructors() || ID->hasDestructors())
John McCallef19dbb2012-10-17 04:53:23 +00003269 Flags |= FragileABI_Class_HasCXXStructors;
John McCall09ec1ec2015-10-21 22:06:03 +00003270
John McCall460ce582015-10-22 18:38:17 +00003271 bool hasMRCWeak = false;
3272
John McCall09ec1ec2015-10-21 22:06:03 +00003273 if (CGM.getLangOpts().ObjCAutoRefCount)
3274 Flags |= FragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00003275 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
3276 Flags |= FragileABI_Class_HasMRCWeakIvars;
John McCall09ec1ec2015-10-21 22:06:03 +00003277
John McCall3fd13f062015-10-21 18:06:47 +00003278 CharUnits Size =
3279 CGM.getContext().getASTObjCImplementationLayout(ID).getSize();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003280
3281 // FIXME: Set CXX-structors flag.
John McCall457a04e2010-10-22 21:05:15 +00003282 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003283 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003284
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003285 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003286 for (const auto *I : ID->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003287 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003288 InstanceMethods.push_back(GetMethodConstant(I));
3289
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003290 for (const auto *I : ID->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003291 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003292 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003293
Aaron Ballmand85eff42014-03-14 15:02:45 +00003294 for (const auto *PID : ID->property_impls()) {
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003295 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3296 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3297
3298 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3299 if (llvm::Constant *C = GetMethodConstant(MD))
3300 InstanceMethods.push_back(C);
3301 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3302 if (llvm::Constant *C = GetMethodConstant(MD))
3303 InstanceMethods.push_back(C);
3304 }
3305 }
3306
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003307 llvm::Constant *Values[12];
Daniel Dunbarccf61832009-05-03 08:56:52 +00003308 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003309 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003310 // Record a reference to the super class.
3311 LazySymbols.insert(Super->getIdentifier());
3312
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003313 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003314 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003315 ObjCTypes.ClassPtrTy);
3316 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003317 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003318 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003319 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003320 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003321 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3322 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
John McCall3fd13f062015-10-21 18:06:47 +00003323 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size.getQuantity());
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003324 Values[ 6] = EmitIvarList(ID, false);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003325 Values[7] = EmitMethodList("OBJC_INSTANCE_METHODS_" + ID->getName(),
3326 "__OBJC,__inst_meth,regular,no_dead_strip",
3327 InstanceMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003328 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003329 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003330 Values[ 9] = Protocols;
John McCall460ce582015-10-22 18:38:17 +00003331 Values[10] = BuildStrongIvarLayout(ID, CharUnits::Zero(), Size);
Manman Renad0e7912016-01-29 19:22:54 +00003332 Values[11] = EmitClassExtension(ID, Size, hasMRCWeak,
3333 false/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003334 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003335 Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003336 std::string Name("OBJC_CLASS_");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003337 Name += ClassName;
3338 const char *Section = "__OBJC,__class,regular,no_dead_strip";
3339 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003340 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003341 if (GV) {
3342 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3343 "Forward metaclass reference has incorrect type.");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003344 GV->setInitializer(Init);
3345 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003346 GV->setAlignment(CGM.getPointerAlign().getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00003347 CGM.addCompilerUsedGlobal(GV);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003348 } else
John McCall7f416cc2015-09-08 08:05:57 +00003349 GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003350 DefinedClasses.push_back(GV);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00003351 ImplementedClasses.push_back(Interface);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003352 // method definition entries must be clear for next implementation.
3353 MethodDefinitions.clear();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003354}
3355
3356llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3357 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003358 ArrayRef<llvm::Constant*> Methods) {
John McCallef19dbb2012-10-17 04:53:23 +00003359 unsigned Flags = FragileABI_Class_Meta;
Micah Villmowdd31ca12012-10-08 16:25:52 +00003360 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003361
John McCall457a04e2010-10-22 21:05:15 +00003362 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003363 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003364
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003365 llvm::Constant *Values[12];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003366 // The isa for the metaclass is the root of the hierarchy.
3367 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3368 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3369 Root = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003370 Values[ 0] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003371 llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003372 ObjCTypes.ClassPtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003373 // The super class for the metaclass is emitted as the name of the
3374 // super class. The runtime fixes this up to point to the
3375 // *metaclass* for the super class.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003376 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003377 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003378 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003379 ObjCTypes.ClassPtrTy);
3380 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003381 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003382 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003383 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003384 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003385 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3386 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
3387 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003388 Values[ 6] = EmitIvarList(ID, true);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003389 Values[7] =
3390 EmitMethodList("OBJC_CLASS_METHODS_" + ID->getNameAsString(),
3391 "__OBJC,__cls_meth,regular,no_dead_strip", Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003392 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003393 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003394 Values[ 9] = Protocols;
3395 // ivar_layout for metaclass is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003396 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Renad0e7912016-01-29 19:22:54 +00003397 // The class extension is used to store class properties for metaclasses.
3398 Values[11] = EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,
3399 true/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003400 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003401 Values);
3402
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003403 std::string Name("OBJC_METACLASS_");
Benjamin Kramer1bbcbd02012-07-31 11:45:39 +00003404 Name += ID->getName();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003405
3406 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003407 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003408 if (GV) {
3409 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3410 "Forward metaclass reference has incorrect type.");
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003411 GV->setInitializer(Init);
3412 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003413 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003414 llvm::GlobalValue::PrivateLinkage,
Owen Andersonc10c8d32009-07-08 19:05:04 +00003415 Init, Name);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003416 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003417 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbarae333842009-03-09 22:18:41 +00003418 GV->setAlignment(4);
Rafael Espindola060062a2014-03-06 22:15:10 +00003419 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003420
3421 return GV;
3422}
3423
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003424llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003425 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003426
Mike Stump18bb9282009-05-16 07:57:57 +00003427 // FIXME: Should we look these up somewhere other than the module. Its a bit
3428 // silly since we only generate these while processing an implementation, so
3429 // exactly one pointer would work if know when we entered/exitted an
3430 // implementation block.
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003431
3432 // Check for an existing forward reference.
Fariborz Jahanian475831b2009-01-07 20:11:22 +00003433 // Previously, metaclass with internal linkage may have been defined.
3434 // pass 'true' as 2nd argument so it is returned.
Rafael Espindola21039aa2014-02-27 16:26:32 +00003435 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3436 if (!GV)
3437 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003438 llvm::GlobalValue::PrivateLinkage, nullptr,
3439 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003440
3441 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3442 "Forward metaclass reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003443 return GV;
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003444}
3445
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003446llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003447 std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
Rafael Espindola21039aa2014-02-27 16:26:32 +00003448 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3449
3450 if (!GV)
3451 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003452 llvm::GlobalValue::PrivateLinkage, nullptr,
3453 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003454
3455 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3456 "Forward class metadata reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003457 return GV;
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003458}
3459
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003460/*
John McCall3fd13f062015-10-21 18:06:47 +00003461 Emit a "class extension", which in this specific context means extra
3462 data that doesn't fit in the normal fragile-ABI class structure, and
3463 has nothing to do with the language concept of a class extension.
3464
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003465 struct objc_class_ext {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003466 uint32_t size;
3467 const char *weak_ivar_layout;
3468 struct _objc_property_list *properties;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003469 };
3470*/
3471llvm::Constant *
John McCall3fd13f062015-10-21 18:06:47 +00003472CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,
Manman Renad0e7912016-01-29 19:22:54 +00003473 CharUnits InstanceSize, bool hasMRCWeakIvars,
3474 bool isClassProperty) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003475 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003476 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003477
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003478 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003479 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Manman Ren92e0a712016-02-21 05:31:05 +00003480 if (isClassProperty) {
3481 llvm::Type *PtrTy = CGM.Int8PtrTy;
3482 Values[1] = llvm::Constant::getNullValue(PtrTy);
3483 } else
Manman Renad0e7912016-01-29 19:22:54 +00003484 Values[1] = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,
3485 hasMRCWeakIvars);
3486 if (isClassProperty)
3487 Values[2] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getName(),
3488 ID, ID->getClassInterface(), ObjCTypes, true);
3489 else
3490 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
3491 ID, ID->getClassInterface(), ObjCTypes, false);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003492
3493 // Return null if no extension bits are used.
Manman Renad0e7912016-01-29 19:22:54 +00003494 if ((!Values[1] || Values[1]->isNullValue()) && Values[2]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00003495 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003496
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003497 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00003498 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003499 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003500 "__OBJC,__class_ext,regular,no_dead_strip",
3501 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003502}
3503
3504/*
3505 struct objc_ivar {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003506 char *ivar_name;
3507 char *ivar_type;
3508 int ivar_offset;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003509 };
3510
3511 struct objc_ivar_list {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003512 int ivar_count;
3513 struct objc_ivar list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003514 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003515*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003516llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003517 bool ForClass) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003518 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003519
3520 // When emitting the root class GCC emits ivar entries for the
3521 // actual class structure. It is not clear if we need to follow this
3522 // behavior; for now lets try and get away with not doing it. If so,
3523 // the cleanest solution would be to make up an ObjCInterfaceDecl
3524 // for the class.
3525 if (ForClass)
Owen Anderson0b75f232009-07-31 20:28:54 +00003526 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003527
Jordy Rosea91768e2011-07-22 02:08:32 +00003528 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003529
Jordy Rosea91768e2011-07-22 02:08:32 +00003530 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00003531 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00003532 // Ignore unnamed bit-fields.
3533 if (!IVD->getDeclName())
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003534 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003535 llvm::Constant *Ivar[] = {
3536 GetMethodVarName(IVD->getIdentifier()),
3537 GetMethodVarType(IVD),
3538 llvm::ConstantInt::get(ObjCTypes.IntTy,
Eli Friedman8cbca202012-11-06 22:15:52 +00003539 ComputeIvarBaseOffset(CGM, OID, IVD))
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003540 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003541 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003542 }
3543
3544 // Return null for empty list.
3545 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003546 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003547
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003548 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003549 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003550 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003551 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003552 Values[1] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003553 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003554
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003555 llvm::GlobalVariable *GV;
3556 if (ForClass)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003557 GV =
3558 CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003559 "__OBJC,__class_vars,regular,no_dead_strip",
3560 CGM.getPointerAlign(), true);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003561 else
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003562 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003563 "__OBJC,__instance_vars,regular,no_dead_strip",
3564 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003565 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003566}
3567
3568/*
3569 struct objc_method {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003570 SEL method_name;
3571 char *method_types;
3572 void *method;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003573 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003574
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003575 struct objc_method_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003576 struct objc_method_list *obsolete;
3577 int count;
3578 struct objc_method methods_list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003579 };
3580*/
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003581
3582/// GetMethodConstant - Return a struct objc_method constant for the
3583/// given method if it has been defined. The result is null if the
3584/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003585llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00003586 llvm::Function *Fn = GetMethodDefinition(MD);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003587 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00003588 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003589
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003590 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00003591 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003592 ObjCTypes.SelectorPtrTy),
3593 GetMethodVarType(MD),
3594 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
3595 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003596 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003597}
3598
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003599llvm::Constant *CGObjCMac::EmitMethodList(Twine Name, StringRef Section,
3600 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003601 // Return null for empty list.
3602 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003603 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003604
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003605 llvm::Constant *Values[3];
Owen Anderson0b75f232009-07-31 20:28:54 +00003606 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003607 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003608 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003609 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003610 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003611 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003612
John McCall7f416cc2015-09-08 08:05:57 +00003613 llvm::GlobalVariable *GV =
3614 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003615 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003616}
3617
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00003618llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003619 const ObjCContainerDecl *CD) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003620 SmallString<256> Name;
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003621 GetNameForMethod(OMD, CD, Name);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003622
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003623 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003624 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003625 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003626 llvm::Function *Method =
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00003627 llvm::Function::Create(MethodTy,
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003628 llvm::GlobalValue::InternalLinkage,
Daniel Dunbard2386812009-10-19 01:21:19 +00003629 Name.str(),
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003630 &CGM.getModule());
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003631 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003632
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003633 return Method;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003634}
3635
Alp Toker541d5072014-06-07 23:30:53 +00003636llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
3637 llvm::Constant *Init,
3638 StringRef Section,
John McCall7f416cc2015-09-08 08:05:57 +00003639 CharUnits Align,
Alp Toker541d5072014-06-07 23:30:53 +00003640 bool AddToUsed) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003641 llvm::Type *Ty = Init->getType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003642 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00003643 new llvm::GlobalVariable(CGM.getModule(), Ty, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003644 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alp Toker541d5072014-06-07 23:30:53 +00003645 if (!Section.empty())
Daniel Dunbar30c65362009-03-09 20:09:19 +00003646 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003647 GV->setAlignment(Align.getQuantity());
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00003648 if (AddToUsed)
Rafael Espindola060062a2014-03-06 22:15:10 +00003649 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar30c65362009-03-09 20:09:19 +00003650 return GV;
3651}
3652
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003653llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00003654 // Abuse this interface function as a place to finalize.
3655 FinishModule();
Craig Topper8a13c412014-05-21 05:09:00 +00003656 return nullptr;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003657}
3658
Chris Lattnerd4808922009-03-22 21:03:39 +00003659llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003660 return ObjCTypes.getGetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003661}
3662
Chris Lattnerd4808922009-03-22 21:03:39 +00003663llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003664 return ObjCTypes.getSetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003665}
3666
Ted Kremeneke65b0862012-03-06 20:05:56 +00003667llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
3668 bool copy) {
3669 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
3670}
3671
David Chisnall168b80f2010-12-26 22:13:16 +00003672llvm::Constant *CGObjCMac::GetGetStructFunction() {
3673 return ObjCTypes.getCopyStructFn();
3674}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003675
David Chisnall168b80f2010-12-26 22:13:16 +00003676llvm::Constant *CGObjCMac::GetSetStructFunction() {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003677 return ObjCTypes.getCopyStructFn();
3678}
3679
David Chisnall0d75e062012-12-17 18:54:24 +00003680llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
3681 return ObjCTypes.getCppAtomicObjectFunction();
3682}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003683
David Chisnall0d75e062012-12-17 18:54:24 +00003684llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003685 return ObjCTypes.getCppAtomicObjectFunction();
3686}
3687
Chris Lattnerd4808922009-03-22 21:03:39 +00003688llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003689 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson3f35a262008-08-31 04:05:03 +00003690}
3691
John McCallbd309292010-07-06 01:34:17 +00003692void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
3693 return EmitTryOrSynchronizedStmt(CGF, S);
3694}
3695
3696void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
3697 const ObjCAtSynchronizedStmt &S) {
3698 return EmitTryOrSynchronizedStmt(CGF, S);
3699}
3700
John McCall65bea082010-07-21 06:59:36 +00003701namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00003702 struct PerformFragileFinally final : EHScopeStack::Cleanup {
John McCall65bea082010-07-21 06:59:36 +00003703 const Stmt &S;
John McCall7f416cc2015-09-08 08:05:57 +00003704 Address SyncArgSlot;
3705 Address CallTryExitVar;
3706 Address ExceptionData;
John McCall65bea082010-07-21 06:59:36 +00003707 ObjCTypesHelper &ObjCTypes;
3708 PerformFragileFinally(const Stmt *S,
John McCall7f416cc2015-09-08 08:05:57 +00003709 Address SyncArgSlot,
3710 Address CallTryExitVar,
3711 Address ExceptionData,
John McCall65bea082010-07-21 06:59:36 +00003712 ObjCTypesHelper *ObjCTypes)
John McCall2dd7d442010-08-04 05:59:32 +00003713 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
John McCall65bea082010-07-21 06:59:36 +00003714 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
3715
Craig Topper4f12f102014-03-12 06:41:41 +00003716 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall65bea082010-07-21 06:59:36 +00003717 // Check whether we need to call objc_exception_try_exit.
3718 // In optimized code, this branch will always be folded.
3719 llvm::BasicBlock *FinallyCallExit =
3720 CGF.createBasicBlock("finally.call_exit");
3721 llvm::BasicBlock *FinallyNoCallExit =
3722 CGF.createBasicBlock("finally.no_call_exit");
3723 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
3724 FinallyCallExit, FinallyNoCallExit);
3725
3726 CGF.EmitBlock(FinallyCallExit);
John McCall882987f2013-02-28 19:01:20 +00003727 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
John McCall7f416cc2015-09-08 08:05:57 +00003728 ExceptionData.getPointer());
John McCall65bea082010-07-21 06:59:36 +00003729
3730 CGF.EmitBlock(FinallyNoCallExit);
3731
3732 if (isa<ObjCAtTryStmt>(S)) {
3733 if (const ObjCAtFinallyStmt* FinallyStmt =
John McCallcebe0ca2010-08-11 00:16:14 +00003734 cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
John McCall638d4f52013-04-03 00:56:07 +00003735 // Don't try to do the @finally if this is an EH cleanup.
3736 if (flags.isForEHCleanup()) return;
3737
John McCallcebe0ca2010-08-11 00:16:14 +00003738 // Save the current cleanup destination in case there's
3739 // control flow inside the finally statement.
3740 llvm::Value *CurCleanupDest =
3741 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
3742
John McCall65bea082010-07-21 06:59:36 +00003743 CGF.EmitStmt(FinallyStmt->getFinallyBody());
3744
John McCallcebe0ca2010-08-11 00:16:14 +00003745 if (CGF.HaveInsertPoint()) {
3746 CGF.Builder.CreateStore(CurCleanupDest,
3747 CGF.getNormalCleanupDestSlot());
3748 } else {
3749 // Currently, the end of the cleanup must always exist.
3750 CGF.EnsureInsertPoint();
3751 }
3752 }
John McCall65bea082010-07-21 06:59:36 +00003753 } else {
3754 // Emit objc_sync_exit(expr); as finally's sole statement for
3755 // @synchronized.
John McCall2dd7d442010-08-04 05:59:32 +00003756 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
John McCall882987f2013-02-28 19:01:20 +00003757 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
John McCall65bea082010-07-21 06:59:36 +00003758 }
3759 }
3760 };
John McCall42227ed2010-07-31 23:20:56 +00003761
3762 class FragileHazards {
3763 CodeGenFunction &CGF;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003764 SmallVector<llvm::Value*, 20> Locals;
John McCall42227ed2010-07-31 23:20:56 +00003765 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
3766
3767 llvm::InlineAsm *ReadHazard;
3768 llvm::InlineAsm *WriteHazard;
3769
3770 llvm::FunctionType *GetAsmFnType();
3771
3772 void collectLocals();
3773 void emitReadHazard(CGBuilderTy &Builder);
3774
3775 public:
3776 FragileHazards(CodeGenFunction &CGF);
John McCall2dd7d442010-08-04 05:59:32 +00003777
John McCall42227ed2010-07-31 23:20:56 +00003778 void emitWriteHazard();
John McCall2dd7d442010-08-04 05:59:32 +00003779 void emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00003780 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003781} // end anonymous namespace
John McCall42227ed2010-07-31 23:20:56 +00003782
3783/// Create the fragile-ABI read and write hazards based on the current
3784/// state of the function, which is presumed to be immediately prior
3785/// to a @try block. These hazards are used to maintain correct
3786/// semantics in the face of optimization and the fragile ABI's
3787/// cavalier use of setjmp/longjmp.
3788FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
3789 collectLocals();
3790
3791 if (Locals.empty()) return;
3792
3793 // Collect all the blocks in the function.
3794 for (llvm::Function::iterator
3795 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
3796 BlocksBeforeTry.insert(&*I);
3797
3798 llvm::FunctionType *AsmFnTy = GetAsmFnType();
3799
3800 // Create a read hazard for the allocas. This inhibits dead-store
3801 // optimizations and forces the values to memory. This hazard is
3802 // inserted before any 'throwing' calls in the protected scope to
3803 // reflect the possibility that the variables might be read from the
3804 // catch block if the call throws.
3805 {
3806 std::string Constraint;
3807 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3808 if (I) Constraint += ',';
3809 Constraint += "*m";
3810 }
3811
3812 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3813 }
3814
3815 // Create a write hazard for the allocas. This inhibits folding
3816 // loads across the hazard. This hazard is inserted at the
3817 // beginning of the catch path to reflect the possibility that the
3818 // variables might have been written within the protected scope.
3819 {
3820 std::string Constraint;
3821 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3822 if (I) Constraint += ',';
3823 Constraint += "=*m";
3824 }
3825
3826 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3827 }
3828}
3829
3830/// Emit a write hazard at the current location.
3831void FragileHazards::emitWriteHazard() {
3832 if (Locals.empty()) return;
3833
John McCall882987f2013-02-28 19:01:20 +00003834 CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
John McCall42227ed2010-07-31 23:20:56 +00003835}
3836
John McCall42227ed2010-07-31 23:20:56 +00003837void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
3838 assert(!Locals.empty());
John McCall882987f2013-02-28 19:01:20 +00003839 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
3840 call->setDoesNotThrow();
3841 call->setCallingConv(CGF.getRuntimeCC());
John McCall42227ed2010-07-31 23:20:56 +00003842}
3843
3844/// Emit read hazards in all the protected blocks, i.e. all the blocks
3845/// which have been inserted since the beginning of the try.
John McCall2dd7d442010-08-04 05:59:32 +00003846void FragileHazards::emitHazardsInNewBlocks() {
John McCall42227ed2010-07-31 23:20:56 +00003847 if (Locals.empty()) return;
3848
John McCall7f416cc2015-09-08 08:05:57 +00003849 CGBuilderTy Builder(CGF, CGF.getLLVMContext());
John McCall42227ed2010-07-31 23:20:56 +00003850
3851 // Iterate through all blocks, skipping those prior to the try.
3852 for (llvm::Function::iterator
3853 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
3854 llvm::BasicBlock &BB = *FI;
3855 if (BlocksBeforeTry.count(&BB)) continue;
3856
3857 // Walk through all the calls in the block.
3858 for (llvm::BasicBlock::iterator
3859 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
3860 llvm::Instruction &I = *BI;
3861
3862 // Ignore instructions that aren't non-intrinsic calls.
3863 // These are the only calls that can possibly call longjmp.
3864 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
3865 if (isa<llvm::IntrinsicInst>(I))
3866 continue;
3867
3868 // Ignore call sites marked nounwind. This may be questionable,
3869 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
3870 llvm::CallSite CS(&I);
3871 if (CS.doesNotThrow()) continue;
3872
John McCall2dd7d442010-08-04 05:59:32 +00003873 // Insert a read hazard before the call. This will ensure that
3874 // any writes to the locals are performed before making the
3875 // call. If the call throws, then this is sufficient to
3876 // guarantee correctness as long as it doesn't also write to any
3877 // locals.
John McCall42227ed2010-07-31 23:20:56 +00003878 Builder.SetInsertPoint(&BB, BI);
3879 emitReadHazard(Builder);
3880 }
3881 }
3882}
3883
3884static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
3885 if (V) S.insert(V);
3886}
3887
John McCall7f416cc2015-09-08 08:05:57 +00003888static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) {
3889 if (V.isValid()) S.insert(V.getPointer());
3890}
3891
John McCall42227ed2010-07-31 23:20:56 +00003892void FragileHazards::collectLocals() {
3893 // Compute a set of allocas to ignore.
3894 llvm::DenseSet<llvm::Value*> AllocasToIgnore;
3895 addIfPresent(AllocasToIgnore, CGF.ReturnValue);
3896 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
John McCall42227ed2010-07-31 23:20:56 +00003897
3898 // Collect all the allocas currently in the function. This is
3899 // probably way too aggressive.
3900 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
3901 for (llvm::BasicBlock::iterator
3902 I = Entry.begin(), E = Entry.end(); I != E; ++I)
3903 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
3904 Locals.push_back(&*I);
3905}
3906
3907llvm::FunctionType *FragileHazards::GetAsmFnType() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003908 SmallVector<llvm::Type *, 16> tys(Locals.size());
John McCall9dc0db22011-05-15 01:53:33 +00003909 for (unsigned i = 0, e = Locals.size(); i != e; ++i)
3910 tys[i] = Locals[i]->getType();
3911 return llvm::FunctionType::get(CGF.VoidTy, tys, false);
John McCall65bea082010-07-21 06:59:36 +00003912}
3913
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003914/*
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003915
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003916 Objective-C setjmp-longjmp (sjlj) Exception Handling
3917 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003918
John McCallbd309292010-07-06 01:34:17 +00003919 A catch buffer is a setjmp buffer plus:
3920 - a pointer to the exception that was caught
3921 - a pointer to the previous exception data buffer
3922 - two pointers of reserved storage
3923 Therefore catch buffers form a stack, with a pointer to the top
3924 of the stack kept in thread-local storage.
3925
3926 objc_exception_try_enter pushes a catch buffer onto the EH stack.
3927 objc_exception_try_exit pops the given catch buffer, which is
3928 required to be the top of the EH stack.
3929 objc_exception_throw pops the top of the EH stack, writes the
3930 thrown exception into the appropriate field, and longjmps
3931 to the setjmp buffer. It crashes the process (with a printf
3932 and an abort()) if there are no catch buffers on the stack.
3933 objc_exception_extract just reads the exception pointer out of the
3934 catch buffer.
3935
3936 There's no reason an implementation couldn't use a light-weight
3937 setjmp here --- something like __builtin_setjmp, but API-compatible
3938 with the heavyweight setjmp. This will be more important if we ever
3939 want to implement correct ObjC/C++ exception interactions for the
3940 fragile ABI.
3941
3942 Note that for this use of setjmp/longjmp to be correct, we may need
3943 to mark some local variables volatile: if a non-volatile local
3944 variable is modified between the setjmp and the longjmp, it has
3945 indeterminate value. For the purposes of LLVM IR, it may be
3946 sufficient to make loads and stores within the @try (to variables
3947 declared outside the @try) volatile. This is necessary for
3948 optimized correctness, but is not currently being done; this is
3949 being tracked as rdar://problem/8160285
3950
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003951 The basic framework for a @try-catch-finally is as follows:
3952 {
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003953 objc_exception_data d;
3954 id _rethrow = null;
Anders Carlssonda0e4562009-02-07 21:26:04 +00003955 bool _call_try_exit = true;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003956
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003957 objc_exception_try_enter(&d);
3958 if (!setjmp(d.jmp_buf)) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003959 ... try body ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003960 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003961 // exception path
3962 id _caught = objc_exception_extract(&d);
3963
3964 // enter new try scope for handlers
3965 if (!setjmp(d.jmp_buf)) {
3966 ... match exception and execute catch blocks ...
3967
3968 // fell off end, rethrow.
3969 _rethrow = _caught;
3970 ... jump-through-finally to finally_rethrow ...
3971 } else {
3972 // exception in catch block
3973 _rethrow = objc_exception_extract(&d);
3974 _call_try_exit = false;
3975 ... jump-through-finally to finally_rethrow ...
3976 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003977 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00003978 ... jump-through-finally to finally_end ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003979
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003980 finally:
Anders Carlssonda0e4562009-02-07 21:26:04 +00003981 if (_call_try_exit)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003982 objc_exception_try_exit(&d);
Anders Carlssonda0e4562009-02-07 21:26:04 +00003983
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003984 ... finally block ....
Daniel Dunbar2efd5382008-09-30 01:06:03 +00003985 ... dispatch to finally destination ...
3986
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003987 finally_rethrow:
Daniel Dunbar2efd5382008-09-30 01:06:03 +00003988 objc_exception_throw(_rethrow);
3989
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003990 finally_end:
3991 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003992
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003993 This framework differs slightly from the one gcc uses, in that gcc
3994 uses _rethrow to determine if objc_exception_try_exit should be called
3995 and if the object should be rethrown. This breaks in the face of
3996 throwing nil and introduces unnecessary branches.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003997
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003998 We specialize this framework for a few particular circumstances:
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003999
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004000 - If there are no catch blocks, then we avoid emitting the second
4001 exception handling context.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004002
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004003 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
4004 e)) we avoid emitting the code to rethrow an uncaught exception.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004005
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004006 - FIXME: If there is no @finally block we can do a few more
4007 simplifications.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004008
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004009 Rethrows and Jumps-Through-Finally
4010 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004011
John McCallbd309292010-07-06 01:34:17 +00004012 '@throw;' is supported by pushing the currently-caught exception
4013 onto ObjCEHStack while the @catch blocks are emitted.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004014
John McCallbd309292010-07-06 01:34:17 +00004015 Branches through the @finally block are handled with an ordinary
4016 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
4017 exceptions are not compatible with C++ exceptions, and this is
4018 hardly the only place where this will go wrong.
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004019
John McCallbd309292010-07-06 01:34:17 +00004020 @synchronized(expr) { stmt; } is emitted as if it were:
4021 id synch_value = expr;
4022 objc_sync_enter(synch_value);
4023 @try { stmt; } @finally { objc_sync_exit(synch_value); }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004024*/
4025
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00004026void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4027 const Stmt &S) {
4028 bool isTry = isa<ObjCAtTryStmt>(S);
John McCallbd309292010-07-06 01:34:17 +00004029
4030 // A destination for the fall-through edges of the catch handlers to
4031 // jump to.
4032 CodeGenFunction::JumpDest FinallyEnd =
4033 CGF.getJumpDestInCurrentScope("finally.end");
4034
4035 // A destination for the rethrow edge of the catch handlers to jump
4036 // to.
4037 CodeGenFunction::JumpDest FinallyRethrow =
4038 CGF.getJumpDestInCurrentScope("finally.rethrow");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004039
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004040 // For @synchronized, call objc_sync_enter(sync.expr). The
4041 // evaluation of the expression must occur before we enter the
John McCall2dd7d442010-08-04 05:59:32 +00004042 // @synchronized. We can't avoid a temp here because we need the
4043 // value to be preserved. If the backend ever does liveness
4044 // correctly after setjmp, this will be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00004045 Address SyncArgSlot = Address::invalid();
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004046 if (!isTry) {
John McCall2dd7d442010-08-04 05:59:32 +00004047 llvm::Value *SyncArg =
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004048 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4049 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004050 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
John McCall2dd7d442010-08-04 05:59:32 +00004051
John McCall7f416cc2015-09-08 08:05:57 +00004052 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),
4053 CGF.getPointerAlign(), "sync.arg");
John McCall2dd7d442010-08-04 05:59:32 +00004054 CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004055 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004056
John McCall2dd7d442010-08-04 05:59:32 +00004057 // Allocate memory for the setjmp buffer. This needs to be kept
4058 // live throughout the try and catch blocks.
John McCall7f416cc2015-09-08 08:05:57 +00004059 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
4060 CGF.getPointerAlign(),
4061 "exceptiondata.ptr");
John McCall2dd7d442010-08-04 05:59:32 +00004062
John McCall42227ed2010-07-31 23:20:56 +00004063 // Create the fragile hazards. Note that this will not capture any
4064 // of the allocas required for exception processing, but will
4065 // capture the current basic block (which extends all the way to the
4066 // setjmp call) as "before the @try".
4067 FragileHazards Hazards(CGF);
4068
John McCallbd309292010-07-06 01:34:17 +00004069 // Create a flag indicating whether the cleanup needs to call
4070 // objc_exception_try_exit. This is true except when
4071 // - no catches match and we're branching through the cleanup
4072 // just to rethrow the exception, or
4073 // - a catch matched and we're falling out of the catch handler.
John McCall2dd7d442010-08-04 05:59:32 +00004074 // The setjmp-safety rule here is that we should always store to this
4075 // variable in a place that dominates the branch through the cleanup
4076 // without passing through any setjmps.
John McCall7f416cc2015-09-08 08:05:57 +00004077 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
4078 CharUnits::One(),
4079 "_call_try_exit");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004080
John McCall9916e3f2010-10-04 23:42:51 +00004081 // A slot containing the exception to rethrow. Only needed when we
4082 // have both a @catch and a @finally.
John McCall7f416cc2015-09-08 08:05:57 +00004083 Address PropagatingExnVar = Address::invalid();
John McCall9916e3f2010-10-04 23:42:51 +00004084
John McCallbd309292010-07-06 01:34:17 +00004085 // Push a normal cleanup to leave the try scope.
John McCall638d4f52013-04-03 00:56:07 +00004086 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
John McCall2dd7d442010-08-04 05:59:32 +00004087 SyncArgSlot,
John McCallcda666c2010-07-21 07:22:38 +00004088 CallTryExitVar,
4089 ExceptionData,
4090 &ObjCTypes);
John McCallbd309292010-07-06 01:34:17 +00004091
4092 // Enter a try block:
4093 // - Call objc_exception_try_enter to push ExceptionData on top of
4094 // the EH stack.
Nico Weber6307cf02015-02-26 20:43:00 +00004095 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004096 ExceptionData.getPointer());
John McCallbd309292010-07-06 01:34:17 +00004097
4098 // - Call setjmp on the exception data buffer.
4099 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
4100 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
David Blaikie6b2a8302015-04-03 17:47:16 +00004101 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
John McCall7f416cc2015-09-08 08:05:57 +00004102 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes,
4103 "setjmp_buffer");
Nico Weber6307cf02015-02-26 20:43:00 +00004104 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
4105 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004106 SetJmpResult->setCanReturnTwice();
John McCallbd309292010-07-06 01:34:17 +00004107
4108 // If setjmp returned 0, enter the protected block; otherwise,
4109 // branch to the handler.
Daniel Dunbar75283ff2008-11-11 02:29:29 +00004110 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4111 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
John McCallbd309292010-07-06 01:34:17 +00004112 llvm::Value *DidCatch =
John McCallcebe0ca2010-08-11 00:16:14 +00004113 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4114 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004115
John McCallbd309292010-07-06 01:34:17 +00004116 // Emit the protected block.
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004117 CGF.EmitBlock(TryBlock);
John McCall2dd7d442010-08-04 05:59:32 +00004118 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004119 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
John McCallbd309292010-07-06 01:34:17 +00004120 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
John McCall2dd7d442010-08-04 05:59:32 +00004121
4122 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004123
John McCallbd309292010-07-06 01:34:17 +00004124 // Emit the exception handler block.
Daniel Dunbar7f086782008-09-27 23:30:04 +00004125 CGF.EmitBlock(TryHandler);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004126
John McCall42227ed2010-07-31 23:20:56 +00004127 // Don't optimize loads of the in-scope locals across this point.
4128 Hazards.emitWriteHazard();
4129
John McCallbd309292010-07-06 01:34:17 +00004130 // For a @synchronized (or a @try with no catches), just branch
4131 // through the cleanup to the rethrow block.
4132 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
4133 // Tell the cleanup not to re-pop the exit.
John McCall2dd7d442010-08-04 05:59:32 +00004134 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004135 CGF.EmitBranchThroughCleanup(FinallyRethrow);
John McCallbd309292010-07-06 01:34:17 +00004136
4137 // Otherwise, we have to match against the caught exceptions.
4138 } else {
John McCall2dd7d442010-08-04 05:59:32 +00004139 // Retrieve the exception object. We may emit multiple blocks but
4140 // nothing can cross this so the value is already in SSA form.
4141 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004142 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004143 ExceptionData.getPointer(), "caught");
John McCall2dd7d442010-08-04 05:59:32 +00004144
John McCallbd309292010-07-06 01:34:17 +00004145 // Push the exception to rethrow onto the EH value stack for the
4146 // benefit of any @throws in the handlers.
4147 CGF.ObjCEHValueStack.push_back(Caught);
4148
Douglas Gregor96c79492010-04-23 22:50:49 +00004149 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004150
Craig Topper8a13c412014-05-21 05:09:00 +00004151 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
John McCallbd309292010-07-06 01:34:17 +00004152
Craig Topper8a13c412014-05-21 05:09:00 +00004153 llvm::BasicBlock *CatchBlock = nullptr;
4154 llvm::BasicBlock *CatchHandler = nullptr;
John McCall2dd7d442010-08-04 05:59:32 +00004155 if (HasFinally) {
John McCall9916e3f2010-10-04 23:42:51 +00004156 // Save the currently-propagating exception before
4157 // objc_exception_try_enter clears the exception slot.
4158 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
John McCall7f416cc2015-09-08 08:05:57 +00004159 CGF.getPointerAlign(),
John McCall9916e3f2010-10-04 23:42:51 +00004160 "propagating_exception");
4161 CGF.Builder.CreateStore(Caught, PropagatingExnVar);
4162
John McCall2dd7d442010-08-04 05:59:32 +00004163 // Enter a new exception try block (in case a @catch block
4164 // throws an exception).
John McCall882987f2013-02-28 19:01:20 +00004165 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004166 ExceptionData.getPointer());
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004167
John McCall2dd7d442010-08-04 05:59:32 +00004168 llvm::CallInst *SetJmpResult =
John McCall882987f2013-02-28 19:01:20 +00004169 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
4170 SetJmpBuffer, "setjmp.result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004171 SetJmpResult->setCanReturnTwice();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004172
John McCall2dd7d442010-08-04 05:59:32 +00004173 llvm::Value *Threw =
4174 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4175
4176 CatchBlock = CGF.createBasicBlock("catch");
4177 CatchHandler = CGF.createBasicBlock("catch_for_catch");
4178 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
4179
4180 CGF.EmitBlock(CatchBlock);
4181 }
4182
4183 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004184
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004185 // Handle catch list. As a special case we check if everything is
4186 // matched and avoid generating code for falling off the end if
4187 // so.
4188 bool AllMatched = false;
Douglas Gregor96c79492010-04-23 22:50:49 +00004189 for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
4190 const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004191
Douglas Gregor46a572b2010-04-26 16:46:50 +00004192 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00004193 const ObjCObjectPointerType *OPT = nullptr;
Daniel Dunbar523208f2008-09-27 07:36:24 +00004194
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004195 // catch(...) always matches.
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004196 if (!CatchParam) {
4197 AllMatched = true;
4198 } else {
John McCall9dd450b2009-09-21 23:43:11 +00004199 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004200
John McCallbd309292010-07-06 01:34:17 +00004201 // catch(id e) always matches under this ABI, since only
4202 // ObjC exceptions end up here in the first place.
Daniel Dunbar86919f42008-09-27 22:21:14 +00004203 // FIXME: For the time being we also match id<X>; this should
4204 // be rejected by Sema instead.
Eli Friedman55179ca2009-07-11 00:57:02 +00004205 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004206 AllMatched = true;
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004207 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004208
John McCallbd309292010-07-06 01:34:17 +00004209 // If this is a catch-all, we don't need to test anything.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004210 if (AllMatched) {
John McCallbd309292010-07-06 01:34:17 +00004211 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4212
Anders Carlsson9396a892008-09-11 09:15:33 +00004213 if (CatchParam) {
John McCall1c9c3fd2010-10-15 04:57:14 +00004214 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004215 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
John McCallbd309292010-07-06 01:34:17 +00004216
4217 // These types work out because ConvertType(id) == i8*.
John McCall17f02752015-10-30 00:56:02 +00004218 EmitInitOfCatchParam(CGF, Caught, CatchParam);
Anders Carlsson9396a892008-09-11 09:15:33 +00004219 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004220
Anders Carlsson9396a892008-09-11 09:15:33 +00004221 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004222
4223 // The scope of the catch variable ends right here.
4224 CatchVarCleanups.ForceCleanup();
4225
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004226 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004227 break;
4228 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004229
Steve Naroff7cae42b2009-07-10 23:34:53 +00004230 assert(OPT && "Unexpected non-object pointer type in @catch");
John McCall96fa4842010-05-17 21:00:27 +00004231 const ObjCObjectType *ObjTy = OPT->getObjectType();
John McCallbd309292010-07-06 01:34:17 +00004232
4233 // FIXME: @catch (Class c) ?
John McCall96fa4842010-05-17 21:00:27 +00004234 ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
4235 assert(IDecl && "Catch parameter must have Objective-C type!");
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004236
4237 // Check if the @catch block matches the exception object.
John McCall882987f2013-02-28 19:01:20 +00004238 llvm::Value *Class = EmitClassRef(CGF, IDecl);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004239
John McCall882987f2013-02-28 19:01:20 +00004240 llvm::Value *matchArgs[] = { Class, Caught };
John McCallbd309292010-07-06 01:34:17 +00004241 llvm::CallInst *Match =
John McCall882987f2013-02-28 19:01:20 +00004242 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
4243 matchArgs, "match");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004244
John McCallbd309292010-07-06 01:34:17 +00004245 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
4246 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004247
4248 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar7f086782008-09-27 23:30:04 +00004249 MatchedBlock, NextCatchBlock);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004250
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004251 // Emit the @catch block.
4252 CGF.EmitBlock(MatchedBlock);
John McCallbd309292010-07-06 01:34:17 +00004253
4254 // Collect any cleanups for the catch variable. The scope lasts until
4255 // the end of the catch body.
John McCall2dd7d442010-08-04 05:59:32 +00004256 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
John McCallbd309292010-07-06 01:34:17 +00004257
John McCall1c9c3fd2010-10-15 04:57:14 +00004258 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004259 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004260
John McCallbd309292010-07-06 01:34:17 +00004261 // Initialize the catch variable.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004262 llvm::Value *Tmp =
4263 CGF.Builder.CreateBitCast(Caught,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004264 CGF.ConvertType(CatchParam->getType()));
John McCall17f02752015-10-30 00:56:02 +00004265 EmitInitOfCatchParam(CGF, Tmp, CatchParam);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004266
Anders Carlsson9396a892008-09-11 09:15:33 +00004267 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004268
4269 // We're done with the catch variable.
4270 CatchVarCleanups.ForceCleanup();
4271
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004272 CGF.EmitBranchThroughCleanup(FinallyEnd);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004273
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004274 CGF.EmitBlock(NextCatchBlock);
4275 }
4276
John McCallbd309292010-07-06 01:34:17 +00004277 CGF.ObjCEHValueStack.pop_back();
4278
John McCall2dd7d442010-08-04 05:59:32 +00004279 // If nothing wanted anything to do with the caught exception,
4280 // kill the extract call.
4281 if (Caught->use_empty())
4282 Caught->eraseFromParent();
4283
4284 if (!AllMatched)
4285 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4286
4287 if (HasFinally) {
4288 // Emit the exception handler for the @catch blocks.
4289 CGF.EmitBlock(CatchHandler);
4290
4291 // In theory we might now need a write hazard, but actually it's
4292 // unnecessary because there's no local-accessing code between
4293 // the try's write hazard and here.
4294 //Hazards.emitWriteHazard();
4295
John McCall9916e3f2010-10-04 23:42:51 +00004296 // Extract the new exception and save it to the
4297 // propagating-exception slot.
John McCall7f416cc2015-09-08 08:05:57 +00004298 assert(PropagatingExnVar.isValid());
John McCall9916e3f2010-10-04 23:42:51 +00004299 llvm::CallInst *NewCaught =
John McCall882987f2013-02-28 19:01:20 +00004300 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004301 ExceptionData.getPointer(), "caught");
John McCall9916e3f2010-10-04 23:42:51 +00004302 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4303
John McCall2dd7d442010-08-04 05:59:32 +00004304 // Don't pop the catch handler; the throw already did.
4305 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004306 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004307 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004308 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004309
John McCall42227ed2010-07-31 23:20:56 +00004310 // Insert read hazards as required in the new blocks.
John McCall2dd7d442010-08-04 05:59:32 +00004311 Hazards.emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00004312
John McCallbd309292010-07-06 01:34:17 +00004313 // Pop the cleanup.
John McCall2dd7d442010-08-04 05:59:32 +00004314 CGF.Builder.restoreIP(TryFallthroughIP);
4315 if (CGF.HaveInsertPoint())
4316 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
John McCallbd309292010-07-06 01:34:17 +00004317 CGF.PopCleanupBlock();
John McCall2dd7d442010-08-04 05:59:32 +00004318 CGF.EmitBlock(FinallyEnd.getBlock(), true);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004319
John McCallbd309292010-07-06 01:34:17 +00004320 // Emit the rethrow block.
John McCall42227ed2010-07-31 23:20:56 +00004321 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
John McCallad5d61e2010-07-23 21:56:41 +00004322 CGF.EmitBlock(FinallyRethrow.getBlock(), true);
John McCallbd309292010-07-06 01:34:17 +00004323 if (CGF.HaveInsertPoint()) {
John McCall9916e3f2010-10-04 23:42:51 +00004324 // If we have a propagating-exception variable, check it.
4325 llvm::Value *PropagatingExn;
John McCall7f416cc2015-09-08 08:05:57 +00004326 if (PropagatingExnVar.isValid()) {
John McCall9916e3f2010-10-04 23:42:51 +00004327 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
John McCall2dd7d442010-08-04 05:59:32 +00004328
John McCall9916e3f2010-10-04 23:42:51 +00004329 // Otherwise, just look in the buffer for the exception to throw.
4330 } else {
4331 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004332 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004333 ExceptionData.getPointer());
John McCall9916e3f2010-10-04 23:42:51 +00004334 PropagatingExn = Caught;
4335 }
4336
John McCall882987f2013-02-28 19:01:20 +00004337 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4338 PropagatingExn);
John McCallbd309292010-07-06 01:34:17 +00004339 CGF.Builder.CreateUnreachable();
Fariborz Jahaniane2caaaa2008-11-21 19:21:53 +00004340 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004341
John McCall42227ed2010-07-31 23:20:56 +00004342 CGF.Builder.restoreIP(SavedIP);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004343}
4344
4345void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004346 const ObjCAtThrowStmt &S,
4347 bool ClearInsertionPoint) {
Anders Carlssone005aa12008-09-09 16:16:55 +00004348 llvm::Value *ExceptionAsObject;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004349
Anders Carlssone005aa12008-09-09 16:16:55 +00004350 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00004351 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004352 ExceptionAsObject =
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004353 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
Anders Carlssone005aa12008-09-09 16:16:55 +00004354 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004355 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004356 "Unexpected rethrow outside @catch block.");
Anders Carlssonbf8a1be2009-02-07 21:37:21 +00004357 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlssone005aa12008-09-09 16:16:55 +00004358 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004359
John McCall882987f2013-02-28 19:01:20 +00004360 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
John McCallbd309292010-07-06 01:34:17 +00004361 ->setDoesNotReturn();
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004362 CGF.Builder.CreateUnreachable();
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004363
4364 // Clear the insertion point to indicate we are in unreachable code.
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004365 if (ClearInsertionPoint)
4366 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004367}
4368
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004369/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004370/// object: objc_read_weak (id *src)
4371///
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004372llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004373 Address AddrWeakObj) {
4374 llvm::Type* DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004375 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
4376 ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004377 llvm::Value *read_weak =
4378 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004379 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00004380 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004381 return read_weak;
4382}
4383
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004384/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4385/// objc_assign_weak (id src, id *dst)
4386///
4387void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004388 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004389 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004390 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004391 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004392 assert(Size <= 8 && "does not support size > 8");
4393 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004394 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004395 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4396 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004397 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4398 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004399 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004400 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4401 args, "weakassign");
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004402}
4403
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004404/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4405/// objc_assign_global (id src, id *dst)
4406///
4407void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004408 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00004409 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004410 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004411 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004412 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004413 assert(Size <= 8 && "does not support size > 8");
4414 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004415 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004416 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4417 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004418 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4419 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004420 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00004421 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00004422 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4423 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00004424 else
John McCall882987f2013-02-28 19:01:20 +00004425 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4426 args, "threadlocalassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004427}
4428
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004429/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004430/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004431///
4432void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004433 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004434 llvm::Value *ivarOffset) {
4435 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00004436 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004437 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004438 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004439 assert(Size <= 8 && "does not support size > 8");
4440 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004441 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004442 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4443 }
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004444 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4445 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004446 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00004447 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004448}
4449
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004450/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4451/// objc_assign_strongCast (id src, id *dst)
4452///
4453void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004454 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004455 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004456 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004457 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004458 assert(Size <= 8 && "does not support size > 8");
4459 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004460 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004461 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4462 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004463 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4464 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004465 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004466 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004467 args, "strongassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004468}
4469
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004470void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004471 Address DestPtr,
4472 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004473 llvm::Value *size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004474 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
4475 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004476 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size };
John McCall882987f2013-02-28 19:01:20 +00004477 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004478}
4479
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004480/// EmitObjCValueForIvar - Code Gen for ivar reference.
4481///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004482LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
4483 QualType ObjectTy,
4484 llvm::Value *BaseValue,
4485 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004486 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004487 const ObjCInterfaceDecl *ID =
4488 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004489 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4490 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004491}
4492
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004493llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004494 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004495 const ObjCIvarDecl *Ivar) {
Eli Friedman8cbca202012-11-06 22:15:52 +00004496 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
4497 return llvm::ConstantInt::get(
4498 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
4499 Offset);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004500}
4501
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004502/* *** Private Interface *** */
4503
4504/// EmitImageInfo - Emit the image info marker used to encode some module
4505/// level information.
4506///
4507/// See: <rdr://4810609&4810587&4810587>
4508/// struct IMAGE_INFO {
4509/// unsigned version;
4510/// unsigned flags;
4511/// };
4512enum ImageInfoFlags {
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004513 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004514 eImageInfo_GarbageCollected = (1 << 1),
4515 eImageInfo_GCOnly = (1 << 2),
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004516 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
Daniel Dunbar75e909f2009-04-20 07:11:47 +00004517
Daniel Dunbar5e639272010-04-25 20:39:01 +00004518 // A flag indicating that the module has no instances of a @synthesize of a
4519 // superclass variable. <rdar://problem/6803242>
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004520 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
Manman Ren96df0b32016-01-29 23:45:01 +00004521 eImageInfo_ImageIsSimulated = (1 << 5),
4522 eImageInfo_ClassProperties = (1 << 6)
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004523};
4524
Daniel Dunbar5e639272010-04-25 20:39:01 +00004525void CGObjCCommonMac::EmitImageInfo() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004526 unsigned version = 0; // Version is unused?
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004527 const char *Section = (ObjCABI == 1) ?
4528 "__OBJC, __image_info,regular" :
4529 "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004530
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004531 // Generate module-level named metadata to convey this information to the
4532 // linker and code-gen.
4533 llvm::Module &Mod = CGM.getModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004534
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004535 // Add the ObjC ABI version to the module flags.
4536 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
4537 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
4538 version);
4539 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
4540 llvm::MDString::get(VMContext,Section));
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004541
David Blaikiebbafb8a2012-03-11 07:00:24 +00004542 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004543 // Non-GC overrides those files which specify GC.
4544 Mod.addModuleFlag(llvm::Module::Override,
4545 "Objective-C Garbage Collection", (uint32_t)0);
4546 } else {
4547 // Add the ObjC garbage collection value.
4548 Mod.addModuleFlag(llvm::Module::Error,
4549 "Objective-C Garbage Collection",
4550 eImageInfo_GarbageCollected);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00004551
David Blaikiebbafb8a2012-03-11 07:00:24 +00004552 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004553 // Add the ObjC GC Only value.
4554 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
4555 eImageInfo_GCOnly);
4556
4557 // Require that GC be specified and set to eImageInfo_GarbageCollected.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004558 llvm::Metadata *Ops[2] = {
4559 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
4560 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4561 llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004562 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
4563 llvm::MDNode::get(VMContext, Ops));
4564 }
4565 }
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004566
4567 // Indicate whether we're compiling this to run on a simulator.
4568 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Tim Northover756447a2015-10-30 16:30:36 +00004569 if ((Triple.isiOS() || Triple.isWatchOS()) &&
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004570 (Triple.getArch() == llvm::Triple::x86 ||
4571 Triple.getArch() == llvm::Triple::x86_64))
4572 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
4573 eImageInfo_ImageIsSimulated);
Manman Ren96df0b32016-01-29 23:45:01 +00004574
4575 // Indicate whether we are generating class properties.
4576 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",
4577 eImageInfo_ClassProperties);
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004578}
4579
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004580// struct objc_module {
4581// unsigned long version;
4582// unsigned long size;
4583// const char *name;
4584// Symtab symtab;
4585// };
4586
4587// FIXME: Get from somewhere
4588static const int ModuleVersion = 7;
4589
4590void CGObjCMac::EmitModuleInfo() {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004591 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004592
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004593 llvm::Constant *Values[] = {
4594 llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
4595 llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
4596 // This used to be the filename, now it is unused. <rdr://4327263>
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004597 GetClassName(StringRef("")),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004598 EmitModuleSymbols()
4599 };
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004600 CreateMetadataVar("OBJC_MODULES",
Owen Anderson0e0189d2009-07-27 22:29:56 +00004601 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
John McCall7f416cc2015-09-08 08:05:57 +00004602 "__OBJC,__module_info,regular,no_dead_strip",
4603 CGM.getPointerAlign(), true);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004604}
4605
4606llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004607 unsigned NumClasses = DefinedClasses.size();
4608 unsigned NumCategories = DefinedCategories.size();
4609
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004610 // Return null if no symbols were defined.
4611 if (!NumClasses && !NumCategories)
Owen Anderson0b75f232009-07-31 20:28:54 +00004612 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004613
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004614 llvm::Constant *Values[5];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004615 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Owen Anderson0b75f232009-07-31 20:28:54 +00004616 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004617 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
4618 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004619
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004620 // The runtime expects exactly the list of defined classes followed
4621 // by the list of defined categories, in a single array.
Chris Lattner3def9ae2012-02-06 22:16:34 +00004622 SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004623 for (unsigned i=0; i<NumClasses; i++) {
4624 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
4625 assert(ID);
4626 if (ObjCImplementationDecl *IMP = ID->getImplementation())
4627 // We are implementing a weak imported interface. Give it external linkage
4628 if (ID->isWeakImported() && !IMP->isWeakImported())
4629 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
4630
Owen Andersonade90fd2009-07-29 18:54:39 +00004631 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004632 ObjCTypes.Int8PtrTy);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004633 }
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004634 for (unsigned i=0; i<NumCategories; i++)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004635 Symbols[NumClasses + i] =
Owen Andersonade90fd2009-07-29 18:54:39 +00004636 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004637 ObjCTypes.Int8PtrTy);
4638
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004639 Values[4] =
Owen Anderson9793f0e2009-07-29 22:16:19 +00004640 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00004641 Symbols.size()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004642 Symbols);
4643
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004644 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004645
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004646 llvm::GlobalVariable *GV = CreateMetadataVar(
John McCall7f416cc2015-09-08 08:05:57 +00004647 "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip",
4648 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00004649 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004650}
4651
John McCall882987f2013-02-28 19:01:20 +00004652llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
4653 IdentifierInfo *II) {
John McCall31168b02011-06-15 23:02:42 +00004654 LazySymbols.insert(II);
4655
4656 llvm::GlobalVariable *&Entry = ClassReferences[II];
4657
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004658 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004659 llvm::Constant *Casted =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004660 llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
John McCall31168b02011-06-15 23:02:42 +00004661 ObjCTypes.ClassPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004662 Entry = CreateMetadataVar(
4663 "OBJC_CLASS_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004664 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
4665 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004666 }
John McCall31168b02011-06-15 23:02:42 +00004667
John McCall7f416cc2015-09-08 08:05:57 +00004668 return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign());
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004669}
4670
John McCall882987f2013-02-28 19:01:20 +00004671llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00004672 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00004673 // If the class has the objc_runtime_visible attribute, we need to
4674 // use the Objective-C runtime to get the class.
4675 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
4676 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
4677
John McCall882987f2013-02-28 19:01:20 +00004678 return EmitClassRefFromId(CGF, ID->getIdentifier());
John McCall31168b02011-06-15 23:02:42 +00004679}
4680
John McCall882987f2013-02-28 19:01:20 +00004681llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00004682 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
John McCall882987f2013-02-28 19:01:20 +00004683 return EmitClassRefFromId(CGF, II);
John McCall31168b02011-06-15 23:02:42 +00004684}
4685
John McCall7f416cc2015-09-08 08:05:57 +00004686llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {
4687 return CGF.Builder.CreateLoad(EmitSelectorAddr(CGF, Sel));
4688}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004689
John McCall7f416cc2015-09-08 08:05:57 +00004690Address CGObjCMac::EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel) {
4691 CharUnits Align = CGF.getPointerAlign();
4692
4693 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004694 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004695 llvm::Constant *Casted =
Owen Andersonade90fd2009-07-29 18:54:39 +00004696 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004697 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004698 Entry = CreateMetadataVar(
4699 "OBJC_SELECTOR_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004700 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);
Michael Gottesman5c205962013-02-05 23:08:45 +00004701 Entry->setExternallyInitialized(true);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004702 }
4703
John McCall7f416cc2015-09-08 08:05:57 +00004704 return Address(Entry, Align);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004705}
4706
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004707llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
4708 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
4709 if (!Entry)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004710 Entry = CreateMetadataVar(
4711 "OBJC_CLASS_NAME_",
4712 llvm::ConstantDataArray::getString(VMContext, RuntimeName),
4713 ((ObjCABI == 2) ? "__TEXT,__objc_classname,cstring_literals"
4714 : "__TEXT,__cstring,cstring_literals"),
John McCall7f416cc2015-09-08 08:05:57 +00004715 CharUnits::One(), true);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004716 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004717}
4718
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004719llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
4720 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
4721 I = MethodDefinitions.find(MD);
4722 if (I != MethodDefinitions.end())
4723 return I->second;
4724
Craig Topper8a13c412014-05-21 05:09:00 +00004725 return nullptr;
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004726}
4727
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004728/// GetIvarLayoutName - Returns a unique constant for the given
4729/// ivar layout bitmap.
4730llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004731 const ObjCCommonTypesHelper &ObjCTypes) {
Owen Anderson0b75f232009-07-31 20:28:54 +00004732 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004733}
4734
John McCall3fd13f062015-10-21 18:06:47 +00004735void IvarLayoutBuilder::visitRecord(const RecordType *RT,
4736 CharUnits offset) {
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004737 const RecordDecl *RD = RT->getDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004738
John McCall3fd13f062015-10-21 18:06:47 +00004739 // If this is a union, remember that we had one, because it might mess
4740 // up the ordering of layout entries.
4741 if (RD->isUnion())
4742 IsDisordered = true;
4743
4744 const ASTRecordLayout *recLayout = nullptr;
4745 visitAggregate(RD->field_begin(), RD->field_end(), offset,
4746 [&](const FieldDecl *field) -> CharUnits {
4747 if (!recLayout)
4748 recLayout = &CGM.getContext().getASTRecordLayout(RD);
4749 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());
4750 return CGM.getContext().toCharUnitsFromBits(offsetInBits);
4751 });
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004752}
4753
John McCall3fd13f062015-10-21 18:06:47 +00004754template <class Iterator, class GetOffsetFn>
4755void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,
4756 CharUnits aggregateOffset,
4757 const GetOffsetFn &getOffset) {
4758 for (; begin != end; ++begin) {
4759 auto field = *begin;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004760
John McCall3fd13f062015-10-21 18:06:47 +00004761 // Skip over bitfields.
4762 if (field->isBitField()) {
4763 continue;
4764 }
4765
4766 // Compute the offset of the field within the aggregate.
4767 CharUnits fieldOffset = aggregateOffset + getOffset(field);
4768
4769 visitField(field, fieldOffset);
4770 }
4771}
4772
4773/// Collect layout information for the given fields into IvarsInfo.
4774void IvarLayoutBuilder::visitField(const FieldDecl *field,
4775 CharUnits fieldOffset) {
4776 QualType fieldType = field->getType();
4777
4778 // Drill down into arrays.
4779 uint64_t numElts = 1;
4780 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {
4781 numElts *= arrayType->getSize().getZExtValue();
4782 fieldType = arrayType->getElementType();
4783 }
4784
4785 assert(!fieldType->isArrayType() && "ivar of non-constant array type?");
4786
4787 // If we ended up with a zero-sized array, we've done what we can do within
4788 // the limits of this layout encoding.
4789 if (numElts == 0) return;
4790
4791 // Recurse if the base element type is a record type.
4792 if (auto recType = fieldType->getAs<RecordType>()) {
4793 size_t oldEnd = IvarsInfo.size();
4794
4795 visitRecord(recType, fieldOffset);
4796
4797 // If we have an array, replicate the first entry's layout information.
4798 auto numEltEntries = IvarsInfo.size() - oldEnd;
4799 if (numElts != 1 && numEltEntries != 0) {
4800 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);
4801 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {
4802 // Copy the last numEltEntries onto the end of the array, adjusting
4803 // each for the element size.
4804 for (size_t i = 0; i != numEltEntries; ++i) {
4805 auto firstEntry = IvarsInfo[oldEnd + i];
4806 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,
4807 firstEntry.SizeInWords));
4808 }
4809 }
4810 }
4811
Fariborz Jahanian524bb202009-03-10 16:22:08 +00004812 return;
Fariborz Jahanian3b0f8862009-03-11 00:07:04 +00004813 }
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004814
John McCall3fd13f062015-10-21 18:06:47 +00004815 // Classify the element type.
4816 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004817
John McCall3fd13f062015-10-21 18:06:47 +00004818 // If it matches what we're looking for, add an entry.
4819 if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
4820 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
4821 assert(CGM.getContext().getTypeSizeInChars(fieldType)
4822 == CGM.getPointerSize());
4823 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));
4824 }
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00004825}
4826
John McCall3fd13f062015-10-21 18:06:47 +00004827/// buildBitmap - This routine does the horsework of taking the offsets of
4828/// strong/weak references and creating a bitmap. The bitmap is also
4829/// returned in the given buffer, suitable for being passed to \c dump().
4830llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,
4831 llvm::SmallVectorImpl<unsigned char> &buffer) {
4832 // The bitmap is a series of skip/scan instructions, aligned to word
4833 // boundaries. The skip is performed first.
4834 const unsigned char MaxNibble = 0xF;
4835 const unsigned char SkipMask = 0xF0, SkipShift = 4;
4836 const unsigned char ScanMask = 0x0F, ScanShift = 0;
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004837
John McCall3fd13f062015-10-21 18:06:47 +00004838 assert(!IvarsInfo.empty() && "generating bitmap for no data");
4839
4840 // Sort the ivar info on byte position in case we encounterred a
4841 // union nested in the ivar list.
4842 if (IsDisordered) {
4843 // This isn't a stable sort, but our algorithm should handle it fine.
4844 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
4845 } else {
Craig Toppera3467052016-01-03 19:43:20 +00004846 assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end()));
John McCall3fd13f062015-10-21 18:06:47 +00004847 }
4848 assert(IvarsInfo.back().Offset < InstanceEnd);
4849
4850 assert(buffer.empty());
4851
4852 // Skip the next N words.
4853 auto skip = [&](unsigned numWords) {
4854 assert(numWords > 0);
4855
4856 // Try to merge into the previous byte. Since scans happen second, we
4857 // can't do this if it includes a scan.
4858 if (!buffer.empty() && !(buffer.back() & ScanMask)) {
4859 unsigned lastSkip = buffer.back() >> SkipShift;
4860 if (lastSkip < MaxNibble) {
4861 unsigned claimed = std::min(MaxNibble - lastSkip, numWords);
4862 numWords -= claimed;
4863 lastSkip += claimed;
4864 buffer.back() = (lastSkip << SkipShift);
4865 }
4866 }
4867
4868 while (numWords >= MaxNibble) {
4869 buffer.push_back(MaxNibble << SkipShift);
4870 numWords -= MaxNibble;
4871 }
4872 if (numWords) {
4873 buffer.push_back(numWords << SkipShift);
4874 }
4875 };
4876
4877 // Scan the next N words.
4878 auto scan = [&](unsigned numWords) {
4879 assert(numWords > 0);
4880
4881 // Try to merge into the previous byte. Since scans happen second, we can
4882 // do this even if it includes a skip.
4883 if (!buffer.empty()) {
4884 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;
4885 if (lastScan < MaxNibble) {
4886 unsigned claimed = std::min(MaxNibble - lastScan, numWords);
4887 numWords -= claimed;
4888 lastScan += claimed;
4889 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);
4890 }
4891 }
4892
4893 while (numWords >= MaxNibble) {
4894 buffer.push_back(MaxNibble << ScanShift);
4895 numWords -= MaxNibble;
4896 }
4897 if (numWords) {
4898 buffer.push_back(numWords << ScanShift);
4899 }
4900 };
4901
4902 // One past the end of the last scan.
4903 unsigned endOfLastScanInWords = 0;
4904 const CharUnits WordSize = CGM.getPointerSize();
4905
4906 // Consider all the scan requests.
4907 for (auto &request : IvarsInfo) {
4908 CharUnits beginOfScan = request.Offset - InstanceBegin;
4909
4910 // Ignore scan requests that don't start at an even multiple of the
4911 // word size. We can't encode them.
4912 if ((beginOfScan % WordSize) != 0) continue;
4913
4914 // Ignore scan requests that start before the instance start.
4915 // This assumes that scans never span that boundary. The boundary
4916 // isn't the true start of the ivars, because in the fragile-ARC case
4917 // it's rounded up to word alignment, but the test above should leave
4918 // us ignoring that possibility.
4919 if (beginOfScan.isNegative()) {
4920 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);
4921 continue;
4922 }
4923
4924 unsigned beginOfScanInWords = beginOfScan / WordSize;
4925 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;
4926
4927 // If the scan starts some number of words after the last one ended,
4928 // skip forward.
4929 if (beginOfScanInWords > endOfLastScanInWords) {
4930 skip(beginOfScanInWords - endOfLastScanInWords);
4931
4932 // Otherwise, start scanning where the last left off.
4933 } else {
4934 beginOfScanInWords = endOfLastScanInWords;
4935
4936 // If that leaves us with nothing to scan, ignore this request.
4937 if (beginOfScanInWords >= endOfScanInWords) continue;
4938 }
4939
4940 // Scan to the end of the request.
4941 assert(beginOfScanInWords < endOfScanInWords);
4942 scan(endOfScanInWords - beginOfScanInWords);
4943 endOfLastScanInWords = endOfScanInWords;
4944 }
4945
John McCallf5ea0722015-10-29 23:36:14 +00004946 if (buffer.empty())
4947 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
4948
John McCall3fd13f062015-10-21 18:06:47 +00004949 // For GC layouts, emit a skip to the end of the allocation so that we
4950 // have precise information about the entire thing. This isn't useful
4951 // or necessary for the ARC-style layout strings.
4952 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
4953 unsigned lastOffsetInWords =
4954 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;
4955 if (lastOffsetInWords > endOfLastScanInWords) {
4956 skip(lastOffsetInWords - endOfLastScanInWords);
4957 }
4958 }
4959
4960 // Null terminate the string.
4961 buffer.push_back(0);
4962
4963 bool isNonFragileABI = CGObjC.isNonFragileABI();
4964
4965 llvm::GlobalVariable *Entry = CGObjC.CreateMetadataVar(
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004966 "OBJC_CLASS_NAME_",
John McCall3fd13f062015-10-21 18:06:47 +00004967 llvm::ConstantDataArray::get(CGM.getLLVMContext(), buffer),
4968 (isNonFragileABI ? "__TEXT,__objc_classname,cstring_literals"
4969 : "__TEXT,__cstring,cstring_literals"),
John McCall7f416cc2015-09-08 08:05:57 +00004970 CharUnits::One(), true);
John McCall3fd13f062015-10-21 18:06:47 +00004971 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00004972}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004973
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00004974/// BuildIvarLayout - Builds ivar layout bitmap for the class
4975/// implementation for the __strong or __weak case.
4976/// The layout map displays which words in ivar list must be skipped
4977/// and which must be scanned by GC (see below). String is built of bytes.
4978/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
4979/// of words to skip and right nibble is count of words to scan. So, each
4980/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
4981/// represented by a 0x00 byte which also ends the string.
4982/// 1. when ForStrongLayout is true, following ivars are scanned:
4983/// - id, Class
4984/// - object *
4985/// - __strong anything
4986///
4987/// 2. When ForStrongLayout is false, following ivars are scanned:
4988/// - __weak anything
4989///
John McCall3fd13f062015-10-21 18:06:47 +00004990llvm::Constant *
4991CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,
4992 CharUnits beginOffset, CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +00004993 bool ForStrongLayout, bool HasMRCWeakIvars) {
4994 // If this is MRC, and we're either building a strong layout or there
4995 // are no weak ivars, bail out early.
Chris Lattnerece04092012-02-07 00:39:47 +00004996 llvm::Type *PtrTy = CGM.Int8PtrTy;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004997 if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
John McCall460ce582015-10-22 18:38:17 +00004998 !CGM.getLangOpts().ObjCAutoRefCount &&
4999 (ForStrongLayout || !HasMRCWeakIvars))
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005000 return llvm::Constant::getNullValue(PtrTy);
5001
Jordy Rosea91768e2011-07-22 02:08:32 +00005002 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
John McCall3fd13f062015-10-21 18:06:47 +00005003 SmallVector<const ObjCIvarDecl*, 32> ivars;
5004
5005 // GC layout strings include the complete object layout, possibly
5006 // inaccurately in the non-fragile ABI; the runtime knows how to fix this
5007 // up.
5008 //
5009 // ARC layout strings only include the class's ivars. In non-fragile
John McCallf5ea0722015-10-29 23:36:14 +00005010 // runtimes, that means starting at InstanceStart, rounded up to word
5011 // alignment. In fragile runtimes, there's no InstanceStart, so it means
John McCalld80218f2015-11-19 02:27:55 +00005012 // starting at the offset of the first ivar, rounded up to word alignment.
John McCall460ce582015-10-22 18:38:17 +00005013 //
5014 // MRC weak layout strings follow the ARC style.
John McCall3fd13f062015-10-21 18:06:47 +00005015 CharUnits baseOffset;
John McCall460ce582015-10-22 18:38:17 +00005016 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005017 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005018 IVD; IVD = IVD->getNextIvar())
John McCall3fd13f062015-10-21 18:06:47 +00005019 ivars.push_back(IVD);
5020
5021 if (isNonFragileABI()) {
5022 baseOffset = beginOffset; // InstanceStart
John McCalld80218f2015-11-19 02:27:55 +00005023 } else if (!ivars.empty()) {
5024 baseOffset =
5025 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));
John McCall3fd13f062015-10-21 18:06:47 +00005026 } else {
5027 baseOffset = CharUnits::Zero();
5028 }
John McCallf5ea0722015-10-29 23:36:14 +00005029
Rui Ueyama83aa9792016-01-14 21:00:27 +00005030 baseOffset = baseOffset.alignTo(CGM.getPointerAlign());
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005031 }
5032 else {
John McCall3fd13f062015-10-21 18:06:47 +00005033 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005034
John McCall3fd13f062015-10-21 18:06:47 +00005035 baseOffset = CharUnits::Zero();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005036 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005037
John McCall3fd13f062015-10-21 18:06:47 +00005038 if (ivars.empty())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005039 return llvm::Constant::getNullValue(PtrTy);
5040
John McCall3fd13f062015-10-21 18:06:47 +00005041 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005042
John McCall3fd13f062015-10-21 18:06:47 +00005043 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),
5044 [&](const ObjCIvarDecl *ivar) -> CharUnits {
5045 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));
5046 });
5047
5048 if (!builder.hasBitmapData())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005049 return llvm::Constant::getNullValue(PtrTy);
John McCall3fd13f062015-10-21 18:06:47 +00005050
5051 llvm::SmallVector<unsigned char, 4> buffer;
5052 llvm::Constant *C = builder.buildBitmap(*this, buffer);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005053
John McCallf5ea0722015-10-29 23:36:14 +00005054 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005055 printf("\n%s ivar layout for class '%s': ",
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005056 ForStrongLayout ? "strong" : "weak",
Ben Langmuire013bdc2014-07-11 00:43:47 +00005057 OMD->getClassInterface()->getName().str().c_str());
John McCall3fd13f062015-10-21 18:06:47 +00005058 builder.dump(buffer);
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005059 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005060 return C;
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00005061}
5062
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005063llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005064 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
5065
Chris Lattner3def9ae2012-02-06 22:16:34 +00005066 // FIXME: Avoid std::string in "Sel.getAsString()"
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005067 if (!Entry)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005068 Entry = CreateMetadataVar(
5069 "OBJC_METH_VAR_NAME_",
5070 llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
5071 ((ObjCABI == 2) ? "__TEXT,__objc_methname,cstring_literals"
5072 : "__TEXT,__cstring,cstring_literals"),
John McCall7f416cc2015-09-08 08:05:57 +00005073 CharUnits::One(), true);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005074
Owen Anderson170229f2009-07-14 23:10:40 +00005075 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005076}
5077
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005078// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005079llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005080 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
5081}
5082
Daniel Dunbarf5c18462009-04-20 06:54:31 +00005083llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005084 std::string TypeStr;
5085 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
5086
5087 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarb036db82008-08-13 03:21:16 +00005088
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005089 if (!Entry)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005090 Entry = CreateMetadataVar(
5091 "OBJC_METH_VAR_TYPE_",
5092 llvm::ConstantDataArray::getString(VMContext, TypeStr),
5093 ((ObjCABI == 2) ? "__TEXT,__objc_methtype,cstring_literals"
5094 : "__TEXT,__cstring,cstring_literals"),
John McCall7f416cc2015-09-08 08:05:57 +00005095 CharUnits::One(), true);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005096
Owen Anderson170229f2009-07-14 23:10:40 +00005097 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005098}
5099
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005100llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
5101 bool Extended) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005102 std::string TypeStr;
Bill Wendlinge22bef72012-02-09 22:45:21 +00005103 if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
Craig Topper8a13c412014-05-21 05:09:00 +00005104 return nullptr;
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005105
5106 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
5107
Daniel Dunbar3241fae2009-04-14 23:14:47 +00005108 if (!Entry)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005109 Entry = CreateMetadataVar(
5110 "OBJC_METH_VAR_TYPE_",
5111 llvm::ConstantDataArray::getString(VMContext, TypeStr),
5112 ((ObjCABI == 2) ? "__TEXT,__objc_methtype,cstring_literals"
5113 : "__TEXT,__cstring,cstring_literals"),
John McCall7f416cc2015-09-08 08:05:57 +00005114 CharUnits::One(), true);
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005115
Owen Anderson170229f2009-07-14 23:10:40 +00005116 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005117}
5118
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005119// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005120llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005121 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005122
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005123 if (!Entry)
Alp Toker541d5072014-06-07 23:30:53 +00005124 Entry = CreateMetadataVar(
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005125 "OBJC_PROP_NAME_ATTR_",
Alp Toker541d5072014-06-07 23:30:53 +00005126 llvm::ConstantDataArray::getString(VMContext, Ident->getName()),
John McCall7f416cc2015-09-08 08:05:57 +00005127 "__TEXT,__cstring,cstring_literals", CharUnits::One(), true);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005128
Owen Anderson170229f2009-07-14 23:10:40 +00005129 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005130}
5131
5132// FIXME: Merge into a single cstring creation function.
Daniel Dunbar4932b362008-08-28 04:38:10 +00005133// FIXME: This Decl should be more precise.
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005134llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005135CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
5136 const Decl *Container) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005137 std::string TypeStr;
5138 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005139 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
5140}
5141
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005142void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005143 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005144 SmallVectorImpl<char> &Name) {
Daniel Dunbard2386812009-10-19 01:21:19 +00005145 llvm::raw_svector_ostream OS(Name);
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00005146 assert (CD && "Missing container decl in GetNameForMethod");
Daniel Dunbard2386812009-10-19 01:21:19 +00005147 OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
5148 << '[' << CD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005149 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbard2386812009-10-19 01:21:19 +00005150 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +00005151 OS << '(' << *CID << ')';
Daniel Dunbard2386812009-10-19 01:21:19 +00005152 OS << ' ' << D->getSelector().getAsString() << ']';
Daniel Dunbara94ecd22008-08-16 03:19:19 +00005153}
5154
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005155void CGObjCMac::FinishModule() {
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005156 EmitModuleInfo();
5157
Daniel Dunbarc475d422008-10-29 22:36:39 +00005158 // Emit the dummy bodies for any protocols which were referenced but
5159 // never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005160 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
Chris Lattnerf56501c2009-07-17 23:57:13 +00005161 I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
5162 if (I->second->hasInitializer())
Daniel Dunbarc475d422008-10-29 22:36:39 +00005163 continue;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005164
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005165 llvm::Constant *Values[5];
Owen Anderson0b75f232009-07-31 20:28:54 +00005166 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005167 Values[1] = GetClassName(I->first->getName());
Owen Anderson0b75f232009-07-31 20:28:54 +00005168 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005169 Values[3] = Values[4] =
Owen Anderson0b75f232009-07-31 20:28:54 +00005170 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00005171 I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarc475d422008-10-29 22:36:39 +00005172 Values));
Rafael Espindola060062a2014-03-06 22:15:10 +00005173 CGM.addCompilerUsedGlobal(I->second);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005174 }
5175
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005176 // Add assembler directives to add lazy undefined symbol references
5177 // for classes which are referenced but not defined. This is
5178 // important for correct linker interaction.
Daniel Dunbard027a922009-09-07 00:20:42 +00005179 //
5180 // FIXME: It would be nice if we had an LLVM construct for this.
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005181 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&
5182 CGM.getTriple().isOSBinFormatMachO()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005183 SmallString<256> Asm;
Daniel Dunbard027a922009-09-07 00:20:42 +00005184 Asm += CGM.getModule().getModuleInlineAsm();
5185 if (!Asm.empty() && Asm.back() != '\n')
5186 Asm += '\n';
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005187
Daniel Dunbard027a922009-09-07 00:20:42 +00005188 llvm::raw_svector_ostream OS(Asm);
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005189 for (const auto *Sym : DefinedSymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005190 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"
5191 << "\t.globl .objc_class_name_" << Sym->getName() << "\n";
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005192 for (const auto *Sym : LazySymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005193 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";
5194 for (const auto &Category : DefinedCategoryNames)
5195 OS << "\t.objc_category_name_" << Category << "=0\n"
5196 << "\t.globl .objc_category_name_" << Category << "\n";
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +00005197
Daniel Dunbard027a922009-09-07 00:20:42 +00005198 CGM.getModule().setModuleInlineAsm(OS.str());
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005199 }
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005200}
5201
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005202CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00005203 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),
5204 ObjCEmptyVtableVar(nullptr) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005205 ObjCABI = 2;
5206}
5207
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005208/* *** */
5209
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005210ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
Craig Topper8a13c412014-05-21 05:09:00 +00005211 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
Douglas Gregora95f9aa2012-01-17 23:38:32 +00005212{
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005213 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5214 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005215
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005216 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005217 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005218 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00005219 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Chris Lattnerece04092012-02-07 00:39:47 +00005220 Int8PtrTy = CGM.Int8PtrTy;
5221 Int8PtrPtrTy = CGM.Int8PtrPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005222
Tim Northover238b5082014-03-29 13:42:40 +00005223 // arm64 targets use "int" ivar offset variables. All others,
5224 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
Tim Northover40956e62014-07-23 12:32:58 +00005225 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
Tim Northover238b5082014-03-29 13:42:40 +00005226 IvarOffsetVarTy = IntTy;
5227 else
5228 IvarOffsetVarTy = LongTy;
5229
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005230 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00005231 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005232 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005233
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005234 // I'm not sure I like this. The implicit coordination is a bit
5235 // gross. We should solve this in a reasonable fashion because this
5236 // is a pretty common task (match some runtime data structure with
5237 // an LLVM data structure).
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005238
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005239 // FIXME: This is leaked.
5240 // FIXME: Merge with rewriter code?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005241
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005242 // struct _objc_super {
5243 // id self;
5244 // Class cls;
5245 // }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005246 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005247 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005248 SourceLocation(), SourceLocation(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005249 &Ctx.Idents.get("_objc_super"));
Craig Topper8a13c412014-05-21 05:09:00 +00005250 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5251 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
5252 false, ICIS_NoInit));
5253 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5254 nullptr, Ctx.getObjCClassType(), nullptr,
5255 nullptr, false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005256 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005257
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005258 SuperCTy = Ctx.getTagDeclType(RD);
5259 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005260
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005261 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005262 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
5263
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005264 // struct _prop_t {
5265 // char *name;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005266 // char *attributes;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005267 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005268 PropertyTy = llvm::StructType::create("struct._prop_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005269 Int8PtrTy, Int8PtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005270
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005271 // struct _prop_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005272 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005273 // uint32_t count_of_properties;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005274 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005275 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005276 PropertyListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005277 llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005278 llvm::ArrayType::get(PropertyTy, 0), nullptr);
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005279 // struct _prop_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005280 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005281
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005282 // struct _objc_method {
5283 // SEL _cmd;
5284 // char *method_type;
5285 // char *_imp;
5286 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005287 MethodTy = llvm::StructType::create("struct._objc_method",
5288 SelectorPtrTy, Int8PtrTy, Int8PtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005289 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005290
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005291 // struct _objc_cache *
Chris Lattner5ec04a52011-08-12 17:43:31 +00005292 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005293 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005294}
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005295
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005296ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005297 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005298 // struct _objc_method_description {
5299 // SEL name;
5300 // char *types;
5301 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005302 MethodDescriptionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005303 llvm::StructType::create("struct._objc_method_description",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005304 SelectorPtrTy, Int8PtrTy, nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005305
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005306 // struct _objc_method_description_list {
5307 // int count;
5308 // struct _objc_method_description[1];
5309 // }
Reid Kleckneree7cf842014-12-01 22:02:27 +00005310 MethodDescriptionListTy = llvm::StructType::create(
5311 "struct._objc_method_description_list", IntTy,
5312 llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005313
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005314 // struct _objc_method_description_list *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005315 MethodDescriptionListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005316 llvm::PointerType::getUnqual(MethodDescriptionListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005317
Daniel Dunbarb036db82008-08-13 03:21:16 +00005318 // Protocol description structures
5319
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005320 // struct _objc_protocol_extension {
5321 // uint32_t size; // sizeof(struct _objc_protocol_extension)
5322 // struct _objc_method_description_list *optional_instance_methods;
5323 // struct _objc_method_description_list *optional_class_methods;
5324 // struct _objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005325 // const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00005326 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005327 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005328 ProtocolExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005329 llvm::StructType::create("struct._objc_protocol_extension",
5330 IntTy, MethodDescriptionListPtrTy,
5331 MethodDescriptionListPtrTy, PropertyListPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005332 Int8PtrPtrTy, PropertyListPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005333
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005334 // struct _objc_protocol_extension *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005335 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005336
Daniel Dunbarc475d422008-10-29 22:36:39 +00005337 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarb036db82008-08-13 03:21:16 +00005338
Chris Lattnera5f58b02011-07-09 17:41:47 +00005339 ProtocolTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005340 llvm::StructType::create(VMContext, "struct._objc_protocol");
Daniel Dunbarb036db82008-08-13 03:21:16 +00005341
Chris Lattnera5f58b02011-07-09 17:41:47 +00005342 ProtocolListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005343 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005344 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005345 LongTy,
Chris Lattnera5f58b02011-07-09 17:41:47 +00005346 llvm::ArrayType::get(ProtocolTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005347 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005348
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005349 // struct _objc_protocol {
5350 // struct _objc_protocol_extension *isa;
5351 // char *protocol_name;
5352 // struct _objc_protocol **_objc_protocol_list;
5353 // struct _objc_method_description_list *instance_methods;
5354 // struct _objc_method_description_list *class_methods;
5355 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005356 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
5357 llvm::PointerType::getUnqual(ProtocolListTy),
5358 MethodDescriptionListPtrTy,
5359 MethodDescriptionListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005360 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005361
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005362 // struct _objc_protocol_list *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005363 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005364
Owen Anderson9793f0e2009-07-29 22:16:19 +00005365 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005366
5367 // Class description structures
5368
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005369 // struct _objc_ivar {
5370 // char *ivar_name;
5371 // char *ivar_type;
5372 // int ivar_offset;
5373 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005374 IvarTy = llvm::StructType::create("struct._objc_ivar",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005375 Int8PtrTy, Int8PtrTy, IntTy, nullptr);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005376
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005377 // struct _objc_ivar_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005378 IvarListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005379 llvm::StructType::create(VMContext, "struct._objc_ivar_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005380 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005381
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005382 // struct _objc_method_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005383 MethodListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005384 llvm::StructType::create(VMContext, "struct._objc_method_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005385 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005386
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005387 // struct _objc_class_extension *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005388 ClassExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005389 llvm::StructType::create("struct._objc_class_extension",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005390 IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005391 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005392
Chris Lattner5ec04a52011-08-12 17:43:31 +00005393 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005394
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005395 // struct _objc_class {
5396 // Class isa;
5397 // Class super_class;
5398 // char *name;
5399 // long version;
5400 // long info;
5401 // long instance_size;
5402 // struct _objc_ivar_list *ivars;
5403 // struct _objc_method_list *methods;
5404 // struct _objc_cache *cache;
5405 // struct _objc_protocol_list *protocols;
5406 // char *ivar_layout;
5407 // struct _objc_class_ext *ext;
5408 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005409 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
5410 llvm::PointerType::getUnqual(ClassTy),
5411 Int8PtrTy,
5412 LongTy,
5413 LongTy,
5414 LongTy,
5415 IvarListPtrTy,
5416 MethodListPtrTy,
5417 CachePtrTy,
5418 ProtocolListPtrTy,
5419 Int8PtrTy,
5420 ClassExtensionPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005421 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005422
Owen Anderson9793f0e2009-07-29 22:16:19 +00005423 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005424
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005425 // struct _objc_category {
5426 // char *category_name;
5427 // char *class_name;
5428 // struct _objc_method_list *instance_method;
5429 // struct _objc_method_list *class_method;
Manman Renb3736772016-01-25 22:37:47 +00005430 // struct _objc_protocol_list *protocols;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005431 // uint32_t size; // sizeof(struct _objc_category)
5432 // struct _objc_property_list *instance_properties;// category's @property
Manman Ren96df0b32016-01-29 23:45:01 +00005433 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005434 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005435 CategoryTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005436 llvm::StructType::create("struct._objc_category",
5437 Int8PtrTy, Int8PtrTy, MethodListPtrTy,
5438 MethodListPtrTy, ProtocolListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005439 IntTy, PropertyListPtrTy, PropertyListPtrTy,
5440 nullptr);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005441
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005442 // Global metadata structures
5443
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005444 // struct _objc_symtab {
5445 // long sel_ref_cnt;
5446 // SEL *refs;
5447 // short cls_def_cnt;
5448 // short cat_def_cnt;
5449 // char *defs[cls_def_cnt + cat_def_cnt];
5450 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005451 SymtabTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005452 llvm::StructType::create("struct._objc_symtab",
5453 LongTy, SelectorPtrTy, ShortTy, ShortTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005454 llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005455 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005456
Fariborz Jahanianeee54df2009-01-22 00:37:21 +00005457 // struct _objc_module {
5458 // long version;
5459 // long size; // sizeof(struct _objc_module)
5460 // char *name;
5461 // struct _objc_symtab* symtab;
5462 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005463 ModuleTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005464 llvm::StructType::create("struct._objc_module",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005465 LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00005466
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005467
Mike Stump18bb9282009-05-16 07:57:57 +00005468 // FIXME: This is the size of the setjmp buffer and should be target
5469 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson9ff22482008-09-09 10:10:21 +00005470 uint64_t SetJmpBufferSize = 18;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005471
Anders Carlsson9ff22482008-09-09 10:10:21 +00005472 // Exceptions
Chris Lattnerece04092012-02-07 00:39:47 +00005473 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005474
5475 ExceptionDataTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005476 llvm::StructType::create("struct._objc_exception_data",
Chris Lattnerece04092012-02-07 00:39:47 +00005477 llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005478 StackPtrTy, nullptr);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005479}
5480
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005481ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005482 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005483 // struct _method_list_t {
5484 // uint32_t entsize; // sizeof(struct _objc_method)
5485 // uint32_t method_count;
5486 // struct _objc_method method_list[method_count];
5487 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005488 MethodListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005489 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005490 llvm::ArrayType::get(MethodTy, 0), nullptr);
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005491 // struct method_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005492 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005493
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005494 // struct _protocol_t {
5495 // id isa; // NULL
5496 // const char * const protocol_name;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005497 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005498 // const struct method_list_t * const instance_methods;
5499 // const struct method_list_t * const class_methods;
5500 // const struct method_list_t *optionalInstanceMethods;
5501 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005502 // const struct _prop_list_t * properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005503 // const uint32_t size; // sizeof(struct _protocol_t)
5504 // const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005505 // const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00005506 // const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00005507 // const struct _prop_list_t * class_properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005508 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005509
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005510 // Holder for struct _protocol_list_t *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005511 ProtocolListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005512 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005513
Chris Lattnera5f58b02011-07-09 17:41:47 +00005514 ProtocolnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005515 llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
5516 llvm::PointerType::getUnqual(ProtocolListnfABITy),
5517 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
5518 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005519 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005520 Int8PtrTy, PropertyListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005521 nullptr);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005522
5523 // struct _protocol_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005524 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005525
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005526 // struct _protocol_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005527 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005528 // struct _protocol_t *[protocol_count];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005529 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005530 ProtocolListnfABITy->setBody(LongTy,
5531 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005532 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005533
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005534 // struct _objc_protocol_list*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005535 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005536
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005537 // struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00005538 // unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005539 // char *name;
5540 // char *type;
5541 // uint32_t alignment;
5542 // uint32_t size;
5543 // }
Tim Northover238b5082014-03-29 13:42:40 +00005544 IvarnfABITy = llvm::StructType::create(
5545 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005546 Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005547
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005548 // struct _ivar_list_t {
5549 // uint32 entsize; // sizeof(struct _ivar_t)
5550 // uint32 count;
5551 // struct _iver_t list[count];
5552 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005553 IvarListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005554 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005555 llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005556
Owen Anderson9793f0e2009-07-29 22:16:19 +00005557 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005558
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005559 // struct _class_ro_t {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005560 // uint32_t const flags;
5561 // uint32_t const instanceStart;
5562 // uint32_t const instanceSize;
5563 // uint32_t const reserved; // only when building for 64bit targets
5564 // const uint8_t * const ivarLayout;
5565 // const char *const name;
5566 // const struct _method_list_t * const baseMethods;
5567 // const struct _objc_protocol_list *const baseProtocols;
5568 // const struct _ivar_list_t *const ivars;
5569 // const uint8_t * const weakIvarLayout;
5570 // const struct _prop_list_t * const properties;
5571 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005572
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005573 // FIXME. Add 'reserved' field in 64bit abi mode!
Chris Lattner5ec04a52011-08-12 17:43:31 +00005574 ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
5575 IntTy, IntTy, IntTy, Int8PtrTy,
5576 Int8PtrTy, MethodListnfABIPtrTy,
5577 ProtocolListnfABIPtrTy,
5578 IvarListnfABIPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005579 Int8PtrTy, PropertyListPtrTy,
5580 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005581
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005582 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +00005583 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +00005584 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
5585 ->getPointerTo();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005586
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005587 // struct _class_t {
5588 // struct _class_t *isa;
5589 // struct _class_t * const superclass;
5590 // void *cache;
5591 // IMP *vtable;
5592 // struct class_ro_t *ro;
5593 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005594
Chris Lattner5ec04a52011-08-12 17:43:31 +00005595 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005596 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
5597 llvm::PointerType::getUnqual(ClassnfABITy),
5598 CachePtrTy,
5599 llvm::PointerType::getUnqual(ImpnfABITy),
5600 llvm::PointerType::getUnqual(ClassRonfABITy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005601 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005602
Fariborz Jahanian71394042009-01-23 23:53:38 +00005603 // LLVM for struct _class_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005604 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005605
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005606 // struct _category_t {
5607 // const char * const name;
5608 // struct _class_t *const cls;
5609 // const struct _method_list_t * const instance_methods;
5610 // const struct _method_list_t * const class_methods;
5611 // const struct _protocol_list_t * const protocols;
5612 // const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00005613 // const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00005614 // const uint32_t size;
Fariborz Jahanian5a63e4c2009-01-23 17:41:22 +00005615 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005616 CategorynfABITy = llvm::StructType::create("struct._category_t",
5617 Int8PtrTy, ClassnfABIPtrTy,
5618 MethodListnfABIPtrTy,
5619 MethodListnfABIPtrTy,
5620 ProtocolListnfABIPtrTy,
5621 PropertyListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005622 PropertyListPtrTy,
Manman Ren42ff3902016-02-24 17:49:50 +00005623 IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005624 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005625
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005626 // New types for nonfragile abi messaging.
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005627 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5628 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005629
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005630 // MessageRefTy - LLVM for:
5631 // struct _message_ref_t {
5632 // IMP messenger;
5633 // SEL name;
5634 // };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005635
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005636 // First the clang type for struct _message_ref_t
Abramo Bagnara6150c882010-05-11 21:36:43 +00005637 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005638 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005639 SourceLocation(), SourceLocation(),
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005640 &Ctx.Idents.get("_message_ref_t"));
Craig Topper8a13c412014-05-21 05:09:00 +00005641 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5642 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
Richard Smith2b013182012-06-10 03:12:00 +00005643 ICIS_NoInit));
Craig Topper8a13c412014-05-21 05:09:00 +00005644 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5645 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
5646 false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005647 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005648
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005649 MessageRefCTy = Ctx.getTagDeclType(RD);
5650 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
5651 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005652
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005653 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005654 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005655
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005656 // SuperMessageRefTy - LLVM for:
5657 // struct _super_message_ref_t {
5658 // SUPER_IMP messenger;
5659 // SEL name;
5660 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005661 SuperMessageRefTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005662 llvm::StructType::create("struct._super_message_ref_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005663 ImpnfABITy, SelectorPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005664
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005665 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005666 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00005667
Daniel Dunbarb1559a42009-03-01 04:46:24 +00005668
5669 // struct objc_typeinfo {
5670 // const void** vtable; // objc_ehtype_vtable + 2
5671 // const char* name; // c++ typeinfo string
5672 // Class cls;
5673 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005674 EHTypeTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005675 llvm::StructType::create("struct._objc_typeinfo",
5676 llvm::PointerType::getUnqual(Int8PtrTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005677 Int8PtrTy, ClassnfABIPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005678 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005679}
5680
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005681llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
Fariborz Jahanian71394042009-01-23 23:53:38 +00005682 FinishNonFragileABIModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005683
Craig Topper8a13c412014-05-21 05:09:00 +00005684 return nullptr;
Fariborz Jahanian71394042009-01-23 23:53:38 +00005685}
5686
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00005687void CGObjCNonFragileABIMac::AddModuleClassList(
5688 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,
5689 StringRef SectionName) {
Daniel Dunbar19573e72009-05-15 21:48:48 +00005690 unsigned NumClasses = Container.size();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005691
Daniel Dunbar19573e72009-05-15 21:48:48 +00005692 if (!NumClasses)
5693 return;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005694
Chris Lattner3def9ae2012-02-06 22:16:34 +00005695 SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005696 for (unsigned i=0; i<NumClasses; i++)
Owen Andersonade90fd2009-07-29 18:54:39 +00005697 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
Daniel Dunbar19573e72009-05-15 21:48:48 +00005698 ObjCTypes.Int8PtrTy);
Chris Lattner3def9ae2012-02-06 22:16:34 +00005699 llvm::Constant *Init =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005700 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00005701 Symbols.size()),
Daniel Dunbar19573e72009-05-15 21:48:48 +00005702 Symbols);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005703
Daniel Dunbar19573e72009-05-15 21:48:48 +00005704 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00005705 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005706 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar19573e72009-05-15 21:48:48 +00005707 Init,
Owen Andersonc10c8d32009-07-08 19:05:04 +00005708 SymbolName);
Micah Villmowdd31ca12012-10-08 16:25:52 +00005709 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Daniel Dunbar19573e72009-05-15 21:48:48 +00005710 GV->setSection(SectionName);
Rafael Espindola060062a2014-03-06 22:15:10 +00005711 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005712}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005713
Fariborz Jahanian71394042009-01-23 23:53:38 +00005714void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
5715 // nonfragile abi has no module definition.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005716
Daniel Dunbar19573e72009-05-15 21:48:48 +00005717 // Build list of all implemented class addresses in array
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005718 // L_OBJC_LABEL_CLASS_$.
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005719
5720 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
5721 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
5722 assert(ID);
5723 if (ObjCImplementationDecl *IMP = ID->getImplementation())
5724 // We are implementing a weak imported interface. Give it external linkage
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005725 if (ID->isWeakImported() && !IMP->isWeakImported()) {
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005726 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005727 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
5728 }
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005729 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005730
5731 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005732 "__DATA, __objc_classlist, regular, no_dead_strip");
Rafael Espindola554256c2014-02-26 22:25:45 +00005733
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005734 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005735 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005736
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005737 // Build list of all implemented category addresses in array
5738 // L_OBJC_LABEL_CATEGORY_$.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005739 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005740 "__DATA, __objc_catlist, regular, no_dead_strip");
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005741 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005742 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005743
Daniel Dunbar5e639272010-04-25 20:39:01 +00005744 EmitImageInfo();
Fariborz Jahanian71394042009-01-23 23:53:38 +00005745}
5746
John McCall9e8bb002011-05-14 03:10:52 +00005747/// isVTableDispatchedSelector - Returns true if SEL is not in the list of
5748/// VTableDispatchMethods; false otherwise. What this means is that
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005749/// except for the 19 selectors in the list, we generate 32bit-style
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005750/// message dispatch call for all the rest.
John McCall9e8bb002011-05-14 03:10:52 +00005751bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
5752 // At various points we've experimented with using vtable-based
5753 // dispatch for all methods.
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005754 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005755 case CodeGenOptions::Legacy:
Fariborz Jahaniandfb39832010-04-19 17:53:30 +00005756 return false;
John McCall9e8bb002011-05-14 03:10:52 +00005757 case CodeGenOptions::NonLegacy:
5758 return true;
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005759 case CodeGenOptions::Mixed:
5760 break;
5761 }
5762
5763 // If so, see whether this selector is in the white-list of things which must
5764 // use the new dispatch convention. We lazily build a dense set for this.
John McCall9e8bb002011-05-14 03:10:52 +00005765 if (VTableDispatchMethods.empty()) {
5766 VTableDispatchMethods.insert(GetNullarySelector("alloc"));
5767 VTableDispatchMethods.insert(GetNullarySelector("class"));
5768 VTableDispatchMethods.insert(GetNullarySelector("self"));
5769 VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
5770 VTableDispatchMethods.insert(GetNullarySelector("length"));
5771 VTableDispatchMethods.insert(GetNullarySelector("count"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005772
John McCall9e8bb002011-05-14 03:10:52 +00005773 // These are vtable-based if GC is disabled.
5774 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005775 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
John McCall9e8bb002011-05-14 03:10:52 +00005776 VTableDispatchMethods.insert(GetNullarySelector("retain"));
5777 VTableDispatchMethods.insert(GetNullarySelector("release"));
5778 VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
5779 }
5780
5781 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
5782 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
5783 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
5784 VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
5785 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
5786 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
5787 VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
5788
5789 // These are vtable-based if GC is enabled.
5790 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005791 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
John McCall9e8bb002011-05-14 03:10:52 +00005792 VTableDispatchMethods.insert(GetNullarySelector("hash"));
5793 VTableDispatchMethods.insert(GetUnarySelector("addObject"));
5794
5795 // "countByEnumeratingWithState:objects:count"
5796 IdentifierInfo *KeyIdents[] = {
5797 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
5798 &CGM.getContext().Idents.get("objects"),
5799 &CGM.getContext().Idents.get("count")
5800 };
5801 VTableDispatchMethods.insert(
5802 CGM.getContext().Selectors.getSelector(3, KeyIdents));
5803 }
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005804 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005805
John McCall9e8bb002011-05-14 03:10:52 +00005806 return VTableDispatchMethods.count(Sel);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005807}
5808
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005809/// BuildClassRoTInitializer - generate meta-data for:
5810/// struct _class_ro_t {
5811/// uint32_t const flags;
5812/// uint32_t const instanceStart;
5813/// uint32_t const instanceSize;
5814/// uint32_t const reserved; // only when building for 64bit targets
5815/// const uint8_t * const ivarLayout;
5816/// const char *const name;
5817/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005818/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005819/// const struct _ivar_list_t *const ivars;
5820/// const uint8_t * const weakIvarLayout;
5821/// const struct _prop_list_t * const properties;
5822/// }
5823///
5824llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005825 unsigned flags,
5826 unsigned InstanceStart,
5827 unsigned InstanceSize,
5828 const ObjCImplementationDecl *ID) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005829 std::string ClassName = ID->getObjCRuntimeNameAsString();
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005830 llvm::Constant *Values[10]; // 11 for 64bit targets!
John McCall31168b02011-06-15 23:02:42 +00005831
John McCall3fd13f062015-10-21 18:06:47 +00005832 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);
5833 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);
5834
John McCall460ce582015-10-22 18:38:17 +00005835 bool hasMRCWeak = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005836 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallef19dbb2012-10-17 04:53:23 +00005837 flags |= NonFragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00005838 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
5839 flags |= NonFragileABI_Class_HasMRCWeakIvars;
John McCall31168b02011-06-15 23:02:42 +00005840
Owen Andersonb7a2fe62009-07-24 23:12:58 +00005841 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
5842 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
5843 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005844 // FIXME. For 64bit targets add 0 here.
John McCallef19dbb2012-10-17 04:53:23 +00005845 Values[ 3] = (flags & NonFragileABI_Class_Meta)
Craig Topper8a13c412014-05-21 05:09:00 +00005846 ? GetIvarLayoutName(nullptr, ObjCTypes)
John McCall460ce582015-10-22 18:38:17 +00005847 : BuildStrongIvarLayout(ID, beginInstance, endInstance);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005848 Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005849 // const struct _method_list_t * const baseMethods;
5850 std::vector<llvm::Constant*> Methods;
5851 std::string MethodListName("\01l_OBJC_$_");
John McCallef19dbb2012-10-17 04:53:23 +00005852 if (flags & NonFragileABI_Class_Meta) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005853 MethodListName += "CLASS_METHODS_";
5854 MethodListName += ID->getObjCRuntimeNameAsString();
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005855 for (const auto *I : ID->class_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005856 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005857 Methods.push_back(GetMethodConstant(I));
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005858 } else {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005859 MethodListName += "INSTANCE_METHODS_";
5860 MethodListName += ID->getObjCRuntimeNameAsString();
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005861 for (const auto *I : ID->instance_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005862 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005863 Methods.push_back(GetMethodConstant(I));
5864
Aaron Ballmand85eff42014-03-14 15:02:45 +00005865 for (const auto *PID : ID->property_impls()) {
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005866 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
5867 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005868
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005869 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
5870 if (llvm::Constant *C = GetMethodConstant(MD))
5871 Methods.push_back(C);
5872 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
5873 if (llvm::Constant *C = GetMethodConstant(MD))
5874 Methods.push_back(C);
5875 }
5876 }
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005877 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005878 Values[ 5] = EmitMethodList(MethodListName,
5879 "__DATA, __objc_const", Methods);
5880
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005881 const ObjCInterfaceDecl *OID = ID->getClassInterface();
5882 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005883 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005884 + OID->getObjCRuntimeNameAsString(),
Ted Kremenek0ef508d2010-09-01 01:21:15 +00005885 OID->all_referenced_protocol_begin(),
5886 OID->all_referenced_protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005887
John McCallef19dbb2012-10-17 04:53:23 +00005888 if (flags & NonFragileABI_Class_Meta) {
Owen Anderson0b75f232009-07-31 20:28:54 +00005889 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +00005890 Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
Manman Renad0e7912016-01-29 19:22:54 +00005891 Values[ 9] = EmitPropertyList(
5892 "\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5893 ID, ID->getClassInterface(), ObjCTypes, true);
John McCallef19dbb2012-10-17 04:53:23 +00005894 } else {
5895 Values[ 7] = EmitIvarList(ID);
John McCall460ce582015-10-22 18:38:17 +00005896 Values[ 8] = BuildWeakIvarLayout(ID, beginInstance, endInstance,
5897 hasMRCWeak);
Manman Renad0e7912016-01-29 19:22:54 +00005898 Values[ 9] = EmitPropertyList(
5899 "\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5900 ID, ID->getClassInterface(), ObjCTypes, false);
John McCallef19dbb2012-10-17 04:53:23 +00005901 }
Owen Anderson0e0189d2009-07-27 22:29:56 +00005902 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005903 Values);
5904 llvm::GlobalVariable *CLASS_RO_GV =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005905 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005906 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005907 Init,
John McCallef19dbb2012-10-17 04:53:23 +00005908 (flags & NonFragileABI_Class_Meta) ?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005909 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
5910 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00005911 CLASS_RO_GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00005912 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00005913 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005914 return CLASS_RO_GV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00005915
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005916}
5917
5918/// BuildClassMetaData - This routine defines that to-level meta-data
5919/// for the given ClassName for:
5920/// struct _class_t {
5921/// struct _class_t *isa;
5922/// struct _class_t * const superclass;
5923/// void *cache;
5924/// IMP *vtable;
5925/// struct class_ro_t *ro;
5926/// }
5927///
Rafael Espindola554256c2014-02-26 22:25:45 +00005928llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005929 const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00005930 llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005931 llvm::Constant *Values[] = {
5932 IsAGV,
5933 SuperClassGV,
5934 ObjCEmptyCacheVar, // &ObjCEmptyCacheVar
5935 ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
5936 ClassRoGV // &CLASS_RO_GV
5937 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005938 if (!Values[1])
5939 Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian42d49552013-10-24 17:40:28 +00005940 if (!Values[3])
5941 Values[3] = llvm::Constant::getNullValue(
5942 llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005943 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005944 Values);
Rafael Espindola554256c2014-02-26 22:25:45 +00005945 llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00005946 GV->setInitializer(Init);
Fariborz Jahanian04087232009-01-31 01:07:39 +00005947 GV->setSection("__DATA, __objc_data");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00005948 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00005949 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00005950 if (!CGM.getTriple().isOSBinFormatCOFF())
5951 if (HiddenVisibility)
5952 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00005953 return GV;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005954}
5955
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005956bool
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00005957CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Craig Topper8a13c412014-05-21 05:09:00 +00005958 return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005959}
5960
Daniel Dunbar961202372009-05-03 12:57:56 +00005961void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00005962 uint32_t &InstanceStart,
5963 uint32_t &InstanceSize) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005964 const ASTRecordLayout &RL =
Daniel Dunbar9252ee12009-05-04 21:26:30 +00005965 CGM.getContext().getASTObjCImplementationLayout(OID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005966
Daniel Dunbar9b042e02009-05-04 23:23:09 +00005967 // InstanceSize is really instance end.
Ken Dyckd5090c12011-02-11 02:20:09 +00005968 InstanceSize = RL.getDataSize().getQuantity();
Daniel Dunbar9b042e02009-05-04 23:23:09 +00005969
5970 // If there are no fields, the start is the same as the end.
5971 if (!RL.getFieldCount())
5972 InstanceStart = InstanceSize;
5973 else
Ken Dyckc5ca8762011-04-14 00:43:09 +00005974 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
Daniel Dunbar554fd792009-04-19 23:41:48 +00005975}
5976
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00005977static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,
5978 StringRef Name) {
5979 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
5980 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
5981 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5982
5983 const VarDecl *VD = nullptr;
5984 for (const auto &Result : DC->lookup(&II))
5985 if ((VD = dyn_cast<VarDecl>(Result)))
5986 break;
5987
5988 if (!VD)
5989 return llvm::GlobalValue::DLLImportStorageClass;
5990 if (VD->hasAttr<DLLExportAttr>())
5991 return llvm::GlobalValue::DLLExportStorageClass;
5992 if (VD->hasAttr<DLLImportAttr>())
5993 return llvm::GlobalValue::DLLImportStorageClass;
5994 return llvm::GlobalValue::DefaultStorageClass;
5995}
5996
Fariborz Jahanian71394042009-01-23 23:53:38 +00005997void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
Fariborz Jahanian71394042009-01-23 23:53:38 +00005998 if (!ObjCEmptyCacheVar) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00005999 ObjCEmptyCacheVar =
6000 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,
6001 llvm::GlobalValue::ExternalLinkage, nullptr,
6002 "_objc_empty_cache");
6003 if (CGM.getTriple().isOSBinFormatCOFF())
6004 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));
Craig Topper8a13c412014-05-21 05:09:00 +00006005
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006006 // Only OS X with deployment version <10.9 use the empty vtable symbol
Fariborz Jahanian42d49552013-10-24 17:40:28 +00006007 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006008 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006009 ObjCEmptyVtableVar =
6010 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,
6011 llvm::GlobalValue::ExternalLinkage, nullptr,
6012 "_objc_empty_vtable");
Fariborz Jahanian71394042009-01-23 23:53:38 +00006013 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006014
Daniel Dunbare3f5cfc2009-04-20 20:18:54 +00006015 // FIXME: Is this correct (that meta class size is never computed)?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006016 uint32_t InstanceStart =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006017 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006018 uint32_t InstanceSize = InstanceStart;
John McCallef19dbb2012-10-17 04:53:23 +00006019 uint32_t flags = NonFragileABI_Class_Meta;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006020
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006021 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006022
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006023 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006024 const auto *CI = ID->getClassInterface();
6025 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");
6026
John McCall0d54a172012-10-17 04:53:31 +00006027 // Build the flags for the metaclass.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006028 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())
6029 ? !CI->hasAttr<DLLExportAttr>()
6030 : CI->getVisibility() == HiddenVisibility;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006031 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006032 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006033
6034 // FIXME: why is this flag set on the metaclass?
6035 // ObjC metaclasses have no fields and don't really get constructed.
6036 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006037 flags |= NonFragileABI_Class_HasCXXStructors;
John McCall0d54a172012-10-17 04:53:31 +00006038 if (!ID->hasNonZeroConstructors())
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006039 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
John McCall0d54a172012-10-17 04:53:31 +00006040 }
6041
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006042 if (!CI->getSuperClass()) {
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006043 // class is root
John McCallef19dbb2012-10-17 04:53:23 +00006044 flags |= NonFragileABI_Class_Root;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006045
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006046 SuperClassGV = GetClassGlobal((getClassSymbolPrefix() + ClassName).str(),
6047 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006048 if (CGM.getTriple().isOSBinFormatCOFF())
6049 if (CI->hasAttr<DLLImportAttr>())
6050 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006051
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006052 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + ClassName).str(),
6053 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006054 if (CGM.getTriple().isOSBinFormatCOFF())
6055 if (CI->hasAttr<DLLImportAttr>())
6056 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006057 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006058 // Has a root. Current class is not a root.
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006059 const ObjCInterfaceDecl *Root = ID->getClassInterface();
6060 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
6061 Root = Super;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006062
6063 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006064 StringRef RootClassName = Root->getObjCRuntimeNameAsString();
6065 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006066
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006067 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + RootClassName).str(),
6068 Root->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006069 if (CGM.getTriple().isOSBinFormatCOFF())
6070 if (Root->hasAttr<DLLImportAttr>())
6071 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006072
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006073 // work on super class metadata symbol.
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006074 SuperClassGV =
6075 GetClassGlobal((getMetaclassSymbolPrefix() + SuperClassName).str(),
6076 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006077 if (CGM.getTriple().isOSBinFormatCOFF())
6078 if (Super->hasAttr<DLLImportAttr>())
6079 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006080 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006081
6082 llvm::GlobalVariable *CLASS_RO_GV =
6083 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6084
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006085 llvm::GlobalVariable *MetaTClass =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006086 BuildClassMetaData((getMetaclassSymbolPrefix() + ClassName).str(), IsAGV,
6087 SuperClassGV, CLASS_RO_GV, classIsHidden,
6088 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006089 if (CGM.getTriple().isOSBinFormatCOFF())
6090 if (CI->hasAttr<DLLExportAttr>())
6091 MetaTClass->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian67260552009-11-17 21:37:35 +00006092 DefinedMetaClasses.push_back(MetaTClass);
Daniel Dunbar15894b72009-04-07 05:48:37 +00006093
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006094 // Metadata for the class
John McCallef19dbb2012-10-17 04:53:23 +00006095 flags = 0;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006096 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006097 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006098
6099 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006100 flags |= NonFragileABI_Class_HasCXXStructors;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006101
John McCall0d54a172012-10-17 04:53:31 +00006102 // Set a flag to enable a runtime optimization when a class has
6103 // fields that require destruction but which don't require
6104 // anything except zero-initialization during construction. This
6105 // is most notably true of __strong and __weak types, but you can
6106 // also imagine there being C++ types with non-trivial default
6107 // constructors that merely set all fields to null.
6108 if (!ID->hasNonZeroConstructors())
6109 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6110 }
6111
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006112 if (hasObjCExceptionAttribute(CGM.getContext(), CI))
John McCallef19dbb2012-10-17 04:53:23 +00006113 flags |= NonFragileABI_Class_Exception;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006114
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006115 if (!CI->getSuperClass()) {
John McCallef19dbb2012-10-17 04:53:23 +00006116 flags |= NonFragileABI_Class_Root;
Craig Topper8a13c412014-05-21 05:09:00 +00006117 SuperClassGV = nullptr;
Chris Lattnerb433b272009-04-19 06:02:28 +00006118 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006119 // Has a root. Current class is not a root.
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006120 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006121 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006122
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006123 SuperClassGV =
6124 GetClassGlobal((getClassSymbolPrefix() + SuperClassName).str(),
6125 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006126 if (CGM.getTriple().isOSBinFormatCOFF())
6127 if (Super->hasAttr<DLLImportAttr>())
6128 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006129 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006130
Daniel Dunbar961202372009-05-03 12:57:56 +00006131 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006132 CLASS_RO_GV =
6133 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006134
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006135 llvm::GlobalVariable *ClassMD =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006136 BuildClassMetaData((getClassSymbolPrefix() + ClassName).str(), MetaTClass,
6137 SuperClassGV, CLASS_RO_GV, classIsHidden,
6138 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006139 if (CGM.getTriple().isOSBinFormatCOFF())
6140 if (CI->hasAttr<DLLExportAttr>())
6141 ClassMD->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006142 DefinedClasses.push_back(ClassMD);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006143 ImplementedClasses.push_back(CI);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006144
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006145 // Determine if this class is also "non-lazy".
6146 if (ImplementationIsNonLazy(ID))
6147 DefinedNonLazyClasses.push_back(ClassMD);
6148
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006149 // Force the definition of the EHType if necessary.
John McCallef19dbb2012-10-17 04:53:23 +00006150 if (flags & NonFragileABI_Class_Exception)
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006151 GetInterfaceEHType(CI, true);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006152 // Make sure method definition entries are all clear for next implementation.
6153 MethodDefinitions.clear();
Fariborz Jahanian71394042009-01-23 23:53:38 +00006154}
6155
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006156/// GenerateProtocolRef - This routine is called to generate code for
6157/// a protocol reference expression; as in:
6158/// @code
6159/// @protocol(Proto1);
6160/// @endcode
6161/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
6162/// which will hold address of the protocol meta-data.
6163///
John McCall882987f2013-02-28 19:01:20 +00006164llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006165 const ObjCProtocolDecl *PD) {
6166
Fariborz Jahanian464423d2009-04-10 18:47:34 +00006167 // This routine is called for @protocol only. So, we must build definition
6168 // of protocol's meta-data (not a reference to it!)
6169 //
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006170 llvm::Constant *Init =
6171 llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00006172 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006173
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006174 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006175 ProtocolName += PD->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006176
John McCall7f416cc2015-09-08 08:05:57 +00006177 CharUnits Align = CGF.getPointerAlign();
6178
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006179 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
6180 if (PTGV)
John McCall7f416cc2015-09-08 08:05:57 +00006181 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006182 PTGV = new llvm::GlobalVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006183 CGM.getModule(),
6184 Init->getType(), false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006185 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006186 Init,
6187 ProtocolName);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006188 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006189 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall7f416cc2015-09-08 08:05:57 +00006190 PTGV->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00006191 CGM.addCompilerUsedGlobal(PTGV);
John McCall7f416cc2015-09-08 08:05:57 +00006192 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006193}
6194
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006195/// GenerateCategory - Build metadata for a category implementation.
6196/// struct _category_t {
6197/// const char * const name;
6198/// struct _class_t *const cls;
6199/// const struct _method_list_t * const instance_methods;
6200/// const struct _method_list_t * const class_methods;
6201/// const struct _protocol_list_t * const protocols;
6202/// const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00006203/// const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00006204/// const uint32_t size;
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006205/// }
6206///
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006207void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006208 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006209 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006210
6211 llvm::SmallString<64> ExtCatName(Prefix);
6212 ExtCatName += Interface->getObjCRuntimeNameAsString();
6213 ExtCatName += "_$_";
6214 ExtCatName += OCD->getNameAsString();
6215
6216 llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
6217 ExtClassName += Interface->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006218
Manman Ren42ff3902016-02-24 17:49:50 +00006219 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006220 Values[0] = GetClassName(OCD->getIdentifier()->getName());
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006221 // meta-class entry symbol
Rafael Espindola554256c2014-02-26 22:25:45 +00006222 llvm::GlobalVariable *ClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006223 GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
Rafael Espindola554256c2014-02-26 22:25:45 +00006224
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006225 Values[1] = ClassGV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006226 std::vector<llvm::Constant*> Methods;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006227 llvm::SmallString<64> MethodListName(Prefix);
6228
6229 MethodListName += "INSTANCE_METHODS_";
6230 MethodListName += Interface->getObjCRuntimeNameAsString();
6231 MethodListName += "_$_";
6232 MethodListName += OCD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006233
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006234 for (const auto *I : OCD->instance_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006235 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006236 Methods.push_back(GetMethodConstant(I));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006237
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006238 Values[2] = EmitMethodList(MethodListName.str(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006239 "__DATA, __objc_const",
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006240 Methods);
6241
6242 MethodListName = Prefix;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006243 MethodListName += "CLASS_METHODS_";
6244 MethodListName += Interface->getObjCRuntimeNameAsString();
6245 MethodListName += "_$_";
6246 MethodListName += OCD->getNameAsString();
6247
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006248 Methods.clear();
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006249 for (const auto *I : OCD->class_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006250 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006251 Methods.push_back(GetMethodConstant(I));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006252
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006253 Values[3] = EmitMethodList(MethodListName.str(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006254 "__DATA, __objc_const",
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006255 Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006256 const ObjCCategoryDecl *Category =
Fariborz Jahanian066347e2009-01-28 22:18:42 +00006257 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006258 if (Category) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006259 SmallString<256> ExtName;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006260 llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006261 << OCD->getName();
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006262 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006263 + Interface->getObjCRuntimeNameAsString() + "_$_"
6264 + Category->getName(),
6265 Category->protocol_begin(),
6266 Category->protocol_end());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006267 Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00006268 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00006269 Values[6] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
6270 OCD, Category, ObjCTypes, true);
Mike Stump658fe022009-07-30 22:28:39 +00006271 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00006272 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
6273 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00006274 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006275 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006276
Manman Ren42ff3902016-02-24 17:49:50 +00006277 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);
6278 Values[7] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6279
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006280 llvm::Constant *Init =
6281 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006282 Values);
6283 llvm::GlobalVariable *GCATV
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006284 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006285 false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006286 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006287 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006288 ExtCatName.str());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006289 GCATV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006290 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006291 GCATV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006292 CGM.addCompilerUsedGlobal(GCATV);
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006293 DefinedCategories.push_back(GCATV);
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006294
6295 // Determine if this category is also "non-lazy".
6296 if (ImplementationIsNonLazy(OCD))
6297 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006298 // method definition entries must be clear for next implementation.
6299 MethodDefinitions.clear();
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006300}
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006301
6302/// GetMethodConstant - Return a struct objc_method constant for the
6303/// given method if it has been defined. The result is null if the
6304/// method has not been defined. The return value has type MethodPtrTy.
6305llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006306 const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00006307 llvm::Function *Fn = GetMethodDefinition(MD);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006308 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00006309 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006310
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006311 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00006312 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006313 ObjCTypes.SelectorPtrTy),
6314 GetMethodVarType(MD),
6315 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
6316 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00006317 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006318}
6319
6320/// EmitMethodList - Build meta-data for method declarations
6321/// struct _method_list_t {
6322/// uint32_t entsize; // sizeof(struct _objc_method)
6323/// uint32_t method_count;
6324/// struct _objc_method method_list[method_count];
6325/// }
6326///
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00006327llvm::Constant *
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00006328CGObjCNonFragileABIMac::EmitMethodList(Twine Name, StringRef Section,
6329 ArrayRef<llvm::Constant *> Methods) {
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006330 // Return null for empty list.
6331 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006332 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006333
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006334 llvm::Constant *Values[3];
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006335 // sizeof(struct _objc_method)
Micah Villmowdd31ca12012-10-08 16:25:52 +00006336 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006337 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006338 // method_count
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006339 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006340 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006341 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006342 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006343 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006344
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006345 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00006346 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006347 llvm::GlobalValue::PrivateLinkage, Init, Name);
Micah Villmowdd31ca12012-10-08 16:25:52 +00006348 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006349 GV->setSection(Section);
Rafael Espindola060062a2014-03-06 22:15:10 +00006350 CGM.addCompilerUsedGlobal(GV);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006351 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006352}
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006353
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006354/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
6355/// the given ivar.
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006356llvm::GlobalVariable *
6357CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
6358 const ObjCIvarDecl *Ivar) {
6359 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006360 llvm::SmallString<64> Name("OBJC_IVAR_$_");
6361 Name += Container->getObjCRuntimeNameAsString();
6362 Name += ".";
6363 Name += Ivar->getName();
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006364 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
6365 if (!IvarOffsetGV) {
6366 IvarOffsetGV =
6367 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,
6368 false, llvm::GlobalValue::ExternalLinkage,
6369 nullptr, Name.str());
6370 if (CGM.getTriple().isOSBinFormatCOFF()) {
6371 bool IsPrivateOrPackage =
6372 Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6373 Ivar->getAccessControl() == ObjCIvarDecl::Package;
6374
6375 if (ID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)
6376 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6377 else if (ID->hasAttr<DLLImportAttr>())
6378 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6379 }
6380 }
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006381 return IvarOffsetGV;
6382}
6383
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006384llvm::Constant *
6385CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
6386 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00006387 unsigned long int Offset) {
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006388 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Tim Northover238b5082014-03-29 13:42:40 +00006389 IvarOffsetGV->setInitializer(
6390 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006391 IvarOffsetGV->setAlignment(
Tim Northover238b5082014-03-29 13:42:40 +00006392 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006393
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006394 if (!CGM.getTriple().isOSBinFormatCOFF()) {
6395 // FIXME: This matches gcc, but shouldn't the visibility be set on the use
6396 // as well (i.e., in ObjCIvarOffsetVariable).
6397 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6398 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6399 ID->getVisibility() == HiddenVisibility)
6400 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6401 else
6402 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6403 }
6404
Bill Wendlingf7d45982011-05-04 21:37:25 +00006405 IvarOffsetGV->setSection("__DATA, __objc_ivar");
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006406 return IvarOffsetGV;
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006407}
6408
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006409/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006410/// implementation. The return value has type
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006411/// IvarListnfABIPtrTy.
6412/// struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00006413/// unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006414/// char *name;
6415/// char *type;
6416/// uint32_t alignment;
6417/// uint32_t size;
6418/// }
6419/// struct _ivar_list_t {
6420/// uint32 entsize; // sizeof(struct _ivar_t)
6421/// uint32 count;
6422/// struct _iver_t list[count];
6423/// }
6424///
Daniel Dunbarf5c18462009-04-20 06:54:31 +00006425
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006426llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006427 const ObjCImplementationDecl *ID) {
6428
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006429 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006430
Jordy Rosea91768e2011-07-22 02:08:32 +00006431 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006432 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006433
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006434 // FIXME. Consolidate this with similar code in GenerateClass.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006435
Jordy Rosea91768e2011-07-22 02:08:32 +00006436 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00006437 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00006438 // Ignore unnamed bit-fields.
6439 if (!IVD->getDeclName())
6440 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006441 llvm::Constant *Ivar[5];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006442 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar961202372009-05-03 12:57:56 +00006443 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006444 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
6445 Ivar[2] = GetMethodVarType(IVD);
Chris Lattner2192fe52011-07-18 04:24:23 +00006446 llvm::Type *FieldTy =
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006447 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00006448 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006449 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006450 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006451 Align = llvm::Log2_32(Align);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006452 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbarae032262009-04-20 00:33:43 +00006453 // NOTE. Size of a bitfield does not match gcc's, because of the
6454 // way bitfields are treated special in each. But I am told that
6455 // 'size' for bitfield ivars is ignored by the runtime so it does
6456 // not matter. If it matters, there is enough info to get the
6457 // bitfield right!
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006458 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006459 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006460 }
6461 // Return null for empty list.
6462 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006463 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006464
6465 llvm::Constant *Values[3];
Micah Villmowdd31ca12012-10-08 16:25:52 +00006466 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006467 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6468 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006469 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006470 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006471 Values[2] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006472 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006473 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
6474 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00006475 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006476 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006477 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006478 Prefix + OID->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006479 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006480 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006481 GV->setSection("__DATA, __objc_const");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006482
Rafael Espindola060062a2014-03-06 22:15:10 +00006483 CGM.addCompilerUsedGlobal(GV);
Owen Andersonade90fd2009-07-29 18:54:39 +00006484 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006485}
6486
6487llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006488 const ObjCProtocolDecl *PD) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006489 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006490
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006491 if (!Entry)
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006492 // We use the initializer as a marker of whether this is a forward
6493 // reference or not. At module finalization we add the empty
6494 // contents for protocols which were referenced but never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006495 Entry =
Rafael Espindola5d117f32014-03-06 01:10:46 +00006496 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
Rafael Espindola24615092014-09-12 20:14:20 +00006497 false, llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00006498 nullptr,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006499 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006500
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006501 return Entry;
6502}
6503
6504/// GetOrEmitProtocol - Generate the protocol meta-data:
6505/// @code
6506/// struct _protocol_t {
6507/// id isa; // NULL
6508/// const char * const protocol_name;
6509/// const struct _protocol_list_t * protocol_list; // super protocols
6510/// const struct method_list_t * const instance_methods;
6511/// const struct method_list_t * const class_methods;
6512/// const struct method_list_t *optionalInstanceMethods;
6513/// const struct method_list_t *optionalClassMethods;
6514/// const struct _prop_list_t * properties;
6515/// const uint32_t size; // sizeof(struct _protocol_t)
6516/// const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006517/// const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006518/// const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00006519/// const struct _prop_list_t * class_properties;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006520/// }
6521/// @endcode
6522///
6523
6524llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006525 const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00006526 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006527
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006528 // Early exit if a defining object has already been generated.
6529 if (Entry && Entry->hasInitializer())
6530 return Entry;
6531
Douglas Gregora715bff2012-01-01 19:51:50 +00006532 // Use the protocol definition, if there is one.
6533 if (const ObjCProtocolDecl *Def = PD->getDefinition())
6534 PD = Def;
6535
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006536 // Construct method lists.
6537 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
6538 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006539 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006540 for (const auto *MD : PD->instance_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006541 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006542 if (!C)
6543 return GetOrEmitProtocolRef(PD);
6544
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006545 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6546 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006547 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006548 } else {
6549 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006550 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006551 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006552 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006553
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006554 for (const auto *MD : PD->class_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006555 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006556 if (!C)
6557 return GetOrEmitProtocolRef(PD);
6558
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006559 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6560 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006561 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006562 } else {
6563 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006564 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006565 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006566 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006567
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006568 MethodTypesExt.insert(MethodTypesExt.end(),
6569 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
6570
Manman Rence7bff52016-01-29 23:46:55 +00006571 llvm::Constant *Values[13];
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006572 // isa is NULL
Owen Anderson0b75f232009-07-31 20:28:54 +00006573 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006574 Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
6575 Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006576 PD->protocol_begin(),
6577 PD->protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006578
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006579 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006580 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006581 "__DATA, __objc_const",
6582 InstanceMethods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006583 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006584 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006585 "__DATA, __objc_const",
6586 ClassMethods);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006587 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006588 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006589 "__DATA, __objc_const",
6590 OptInstanceMethods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006591 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006592 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006593 "__DATA, __objc_const",
6594 OptClassMethods);
Manman Renad0e7912016-01-29 19:22:54 +00006595 Values[7] = EmitPropertyList(
6596 "\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6597 nullptr, PD, ObjCTypes, false);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006598 uint32_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006599 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006600 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0b75f232009-07-31 20:28:54 +00006601 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006602 Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006603 + PD->getObjCRuntimeNameAsString(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006604 MethodTypesExt, ObjCTypes);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006605 // const char *demangledName;
6606 Values[11] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Rence7bff52016-01-29 23:46:55 +00006607
6608 Values[12] = EmitPropertyList(
6609 "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6610 nullptr, PD, ObjCTypes, true);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006611
Owen Anderson0e0189d2009-07-27 22:29:56 +00006612 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006613 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006614
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006615 if (Entry) {
Rafael Espindola24615092014-09-12 20:14:20 +00006616 // Already created, fix the linkage and update the initializer.
6617 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006618 Entry->setInitializer(Init);
6619 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006620 Entry =
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006621 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006622 false, llvm::GlobalValue::WeakAnyLinkage, Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006623 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006624 Entry->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006625 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
John McCallf9582a72012-03-30 21:29:05 +00006626
6627 Protocols[PD->getIdentifier()] = Entry;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006628 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006629 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006630 CGM.addCompilerUsedGlobal(Entry);
Chris Lattnerf56501c2009-07-17 23:57:13 +00006631
Fariborz Jahanian61cd4b52009-01-29 20:10:59 +00006632 // Use this protocol meta-data to build protocol list table in section
6633 // __DATA, __objc_protolist
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006634 llvm::GlobalVariable *PTGV =
6635 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006636 false, llvm::GlobalValue::WeakAnyLinkage, Entry,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006637 "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006638 PTGV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006639 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbarb25452a2009-04-15 02:56:18 +00006640 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006641 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006642 CGM.addCompilerUsedGlobal(PTGV);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006643 return Entry;
6644}
6645
6646/// EmitProtocolList - Generate protocol list meta-data:
6647/// @code
6648/// struct _protocol_list_t {
6649/// long protocol_count; // Note, this is 32/64 bit
6650/// struct _protocol_t[protocol_count];
6651/// }
6652/// @endcode
6653///
6654llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006655CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006656 ObjCProtocolDecl::protocol_iterator begin,
6657 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006658 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006659
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006660 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006661 if (begin == end)
Owen Anderson0b75f232009-07-31 20:28:54 +00006662 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006663
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006664 // FIXME: We shouldn't need to do this lookup here, should we?
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006665 SmallString<256> TmpName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006666 Name.toVector(TmpName);
6667 llvm::GlobalVariable *GV =
6668 CGM.getModule().getGlobalVariable(TmpName.str(), true);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006669 if (GV)
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006670 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006671
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006672 for (; begin != end; ++begin)
6673 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
6674
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006675 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00006676 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006677 ObjCTypes.ProtocolnfABIPtrTy));
6678
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006679 llvm::Constant *Values[2];
Owen Anderson170229f2009-07-14 23:10:40 +00006680 Values[0] =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006681 llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006682 Values[1] =
Bill Wendlinga515b582012-02-09 22:16:49 +00006683 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
6684 ProtocolRefs.size()),
6685 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006686
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006687 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Owen Andersonc10c8d32009-07-08 19:05:04 +00006688 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006689 llvm::GlobalValue::PrivateLinkage,
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006690 Init, Name);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006691 GV->setSection("__DATA, __objc_const");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006692 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006693 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Rafael Espindola060062a2014-03-06 22:15:10 +00006694 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006695 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006696 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006697}
6698
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006699/// GetMethodDescriptionConstant - This routine build following meta-data:
6700/// struct _objc_method {
6701/// SEL _cmd;
6702/// char *method_type;
6703/// char *_imp;
6704/// }
6705
6706llvm::Constant *
6707CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006708 llvm::Constant *Desc[3];
Owen Anderson170229f2009-07-14 23:10:40 +00006709 Desc[0] =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006710 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
6711 ObjCTypes.SelectorPtrTy);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006712 Desc[1] = GetMethodVarType(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006713 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00006714 return nullptr;
6715
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006716 // Protocol methods have no implementation. So, this entry is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00006717 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006718 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006719}
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006720
6721/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
6722/// This code gen. amounts to generating code for:
6723/// @code
6724/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
6725/// @encode
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006726///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00006727LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
John McCall96fa4842010-05-17 21:00:27 +00006728 CodeGen::CodeGenFunction &CGF,
6729 QualType ObjectTy,
6730 llvm::Value *BaseValue,
6731 const ObjCIvarDecl *Ivar,
6732 unsigned CVRQualifiers) {
6733 ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006734 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00006735 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006736 Offset);
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006737}
6738
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006739llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006740 CodeGen::CodeGenFunction &CGF,
6741 const ObjCInterfaceDecl *Interface,
6742 const ObjCIvarDecl *Ivar) {
Tim Northover238b5082014-03-29 13:42:40 +00006743 llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
John McCall7f416cc2015-09-08 08:05:57 +00006744 IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
6745 CGF.getSizeAlign(), "ivar");
Tim Northover238b5082014-03-29 13:42:40 +00006746 if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
6747 cast<llvm::LoadInst>(IvarOffsetValue)
6748 ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
Craig Topper5fc8fc22014-08-27 06:28:36 +00006749 llvm::MDNode::get(VMContext, None));
Tim Northover238b5082014-03-29 13:42:40 +00006750
6751 // This could be 32bit int or 64bit integer depending on the architecture.
6752 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
6753 // as this is what caller always expectes.
6754 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
6755 IvarOffsetValue = CGF.Builder.CreateIntCast(
6756 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
6757 return IvarOffsetValue;
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006758}
6759
John McCall234eac82011-05-13 23:16:18 +00006760static void appendSelectorForMessageRefTable(std::string &buffer,
6761 Selector selector) {
6762 if (selector.isUnarySelector()) {
6763 buffer += selector.getNameForSlot(0);
6764 return;
6765 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006766
John McCall234eac82011-05-13 23:16:18 +00006767 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
6768 buffer += selector.getNameForSlot(i);
6769 buffer += '_';
6770 }
6771}
6772
Eric Christopherd160c502016-01-29 01:35:53 +00006773/// Emit a "vtable" message send. We emit a weak hidden-visibility
John McCall9e8bb002011-05-14 03:10:52 +00006774/// struct, initially containing the selector pointer and a pointer to
6775/// a "fixup" variant of the appropriate objc_msgSend. To call, we
6776/// load and call the function pointer, passing the address of the
6777/// struct as the second parameter. The runtime determines whether
6778/// the selector is currently emitted using vtable dispatch; if so, it
6779/// substitutes a stub function which simply tail-calls through the
6780/// appropriate vtable slot, and if not, it substitues a stub function
6781/// which tail-calls objc_msgSend. Both stubs adjust the selector
6782/// argument to correctly point to the selector.
6783RValue
6784CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
6785 ReturnValueSlot returnSlot,
6786 QualType resultType,
6787 Selector selector,
6788 llvm::Value *arg0,
6789 QualType arg0Type,
6790 bool isSuper,
6791 const CallArgList &formalArgs,
6792 const ObjCMethodDecl *method) {
John McCall234eac82011-05-13 23:16:18 +00006793 // Compute the actual arguments.
6794 CallArgList args;
6795
John McCall9e8bb002011-05-14 03:10:52 +00006796 // First argument: the receiver / super-call structure.
John McCall234eac82011-05-13 23:16:18 +00006797 if (!isSuper)
John McCall9e8bb002011-05-14 03:10:52 +00006798 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
6799 args.add(RValue::get(arg0), arg0Type);
John McCall234eac82011-05-13 23:16:18 +00006800
John McCall9e8bb002011-05-14 03:10:52 +00006801 // Second argument: a pointer to the message ref structure. Leave
6802 // the actual argument value blank for now.
Craig Topper8a13c412014-05-21 05:09:00 +00006803 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
John McCall234eac82011-05-13 23:16:18 +00006804
6805 args.insert(args.end(), formalArgs.begin(), formalArgs.end());
6806
John McCalla729c622012-02-17 03:33:10 +00006807 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
John McCall234eac82011-05-13 23:16:18 +00006808
John McCall5880fb82011-05-14 21:12:11 +00006809 NullReturnState nullReturn;
6810
John McCall9e8bb002011-05-14 03:10:52 +00006811 // Find the function to call and the mangled name for the message
6812 // ref structure. Using a different mangled name wouldn't actually
6813 // be a problem; it would just be a waste.
6814 //
6815 // The runtime currently never uses vtable dispatch for anything
6816 // except normal, non-super message-sends.
6817 // FIXME: don't use this for that.
Craig Topper8a13c412014-05-21 05:09:00 +00006818 llvm::Constant *fn = nullptr;
John McCall234eac82011-05-13 23:16:18 +00006819 std::string messageRefName("\01l_");
Tim Northovere77cc392014-03-29 13:28:05 +00006820 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall234eac82011-05-13 23:16:18 +00006821 if (isSuper) {
6822 fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
6823 messageRefName += "objc_msgSendSuper2_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006824 } else {
John McCall5880fb82011-05-14 21:12:11 +00006825 nullReturn.init(CGF, arg0);
John McCall234eac82011-05-13 23:16:18 +00006826 fn = ObjCTypes.getMessageSendStretFixupFn();
6827 messageRefName += "objc_msgSend_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006828 }
John McCall234eac82011-05-13 23:16:18 +00006829 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
6830 fn = ObjCTypes.getMessageSendFpretFixupFn();
6831 messageRefName += "objc_msgSend_fpret_fixup";
Mike Stump658fe022009-07-30 22:28:39 +00006832 } else {
John McCall234eac82011-05-13 23:16:18 +00006833 if (isSuper) {
6834 fn = ObjCTypes.getMessageSendSuper2FixupFn();
6835 messageRefName += "objc_msgSendSuper2_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006836 } else {
John McCall234eac82011-05-13 23:16:18 +00006837 fn = ObjCTypes.getMessageSendFixupFn();
6838 messageRefName += "objc_msgSend_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006839 }
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00006840 }
John McCall234eac82011-05-13 23:16:18 +00006841 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
6842 messageRefName += '_';
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006843
John McCall234eac82011-05-13 23:16:18 +00006844 // Append the selector name, except use underscores anywhere we
6845 // would have used colons.
6846 appendSelectorForMessageRefTable(messageRefName, selector);
6847
6848 llvm::GlobalVariable *messageRef
6849 = CGM.getModule().getGlobalVariable(messageRefName);
6850 if (!messageRef) {
John McCall9e8bb002011-05-14 03:10:52 +00006851 // Build the message ref structure.
John McCall234eac82011-05-13 23:16:18 +00006852 llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006853 llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
John McCall234eac82011-05-13 23:16:18 +00006854 messageRef = new llvm::GlobalVariable(CGM.getModule(),
6855 init->getType(),
6856 /*constant*/ false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006857 llvm::GlobalValue::WeakAnyLinkage,
John McCall234eac82011-05-13 23:16:18 +00006858 init,
6859 messageRefName);
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006860 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall234eac82011-05-13 23:16:18 +00006861 messageRef->setAlignment(16);
6862 messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
6863 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006864
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006865 bool requiresnullCheck = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006866 if (CGM.getLangOpts().ObjCAutoRefCount && method)
David Majnemer59f77922016-06-24 04:05:48 +00006867 for (const auto *ParamDecl : method->parameters()) {
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006868 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
6869 if (!nullReturn.NullBB)
6870 nullReturn.init(CGF, arg0);
6871 requiresnullCheck = true;
6872 break;
6873 }
6874 }
6875
John McCall7f416cc2015-09-08 08:05:57 +00006876 Address mref =
6877 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),
6878 CGF.getPointerAlign());
John McCall234eac82011-05-13 23:16:18 +00006879
John McCall9e8bb002011-05-14 03:10:52 +00006880 // Update the message ref argument.
John McCall7f416cc2015-09-08 08:05:57 +00006881 args[1].RV = RValue::get(mref.getPointer());
John McCall234eac82011-05-13 23:16:18 +00006882
6883 // Load the function to call from the message ref table.
John McCall7f416cc2015-09-08 08:05:57 +00006884 Address calleeAddr =
6885 CGF.Builder.CreateStructGEP(mref, 0, CharUnits::Zero());
6886 llvm::Value *callee = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");
John McCall234eac82011-05-13 23:16:18 +00006887
John McCalla729c622012-02-17 03:33:10 +00006888 callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
John McCall234eac82011-05-13 23:16:18 +00006889
John McCalla729c622012-02-17 03:33:10 +00006890 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
Craig Topper8a13c412014-05-21 05:09:00 +00006891 return nullReturn.complete(CGF, result, resultType, formalArgs,
6892 requiresnullCheck ? method : nullptr);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006893}
6894
6895/// Generate code for a message send expression in the nonfragile abi.
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006896CodeGen::RValue
6897CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00006898 ReturnValueSlot Return,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006899 QualType ResultType,
6900 Selector Sel,
6901 llvm::Value *Receiver,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006902 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00006903 const ObjCInterfaceDecl *Class,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006904 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00006905 return isVTableDispatchedSelector(Sel)
6906 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006907 Receiver, CGF.getContext().getObjCIdType(),
John McCall9e8bb002011-05-14 03:10:52 +00006908 false, CallArgs, Method)
6909 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00006910 EmitSelector(CGF, Sel),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006911 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00006912 false, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006913}
6914
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006915llvm::GlobalVariable *
Benjamin Kramer0772c422016-02-13 13:42:54 +00006916CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name, bool Weak) {
Rafael Espindola554256c2014-02-26 22:25:45 +00006917 llvm::GlobalValue::LinkageTypes L =
6918 Weak ? llvm::GlobalValue::ExternalWeakLinkage
6919 : llvm::GlobalValue::ExternalLinkage;
6920
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006921 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
6922
Rafael Espindola554256c2014-02-26 22:25:45 +00006923 if (!GV)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006924 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
Craig Topper8a13c412014-05-21 05:09:00 +00006925 false, L, nullptr, Name);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006926
Rafael Espindola554256c2014-02-26 22:25:45 +00006927 assert(GV->getLinkage() == L);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006928 return GV;
6929}
6930
John McCall882987f2013-02-28 19:01:20 +00006931llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
Rafael Espindola554256c2014-02-26 22:25:45 +00006932 IdentifierInfo *II,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006933 bool Weak,
6934 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00006935 CharUnits Align = CGF.getPointerAlign();
John McCall31168b02011-06-15 23:02:42 +00006936 llvm::GlobalVariable *&Entry = ClassReferences[II];
6937
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00006938 if (!Entry) {
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00006939 StringRef Name = ID ? ID->getObjCRuntimeNameAsString() : II->getName();
6940 std::string ClassName = (getClassSymbolPrefix() + Name).str();
Rafael Espindola554256c2014-02-26 22:25:45 +00006941 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006942 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
6943 false, llvm::GlobalValue::PrivateLinkage,
6944 ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
John McCall7f416cc2015-09-08 08:05:57 +00006945 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006946 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00006947 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006948 }
John McCall7f416cc2015-09-08 08:05:57 +00006949 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006950}
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00006951
John McCall882987f2013-02-28 19:01:20 +00006952llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00006953 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006954 // If the class has the objc_runtime_visible attribute, we need to
6955 // use the Objective-C runtime to get the class.
6956 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
6957 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
6958
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006959 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
John McCall31168b02011-06-15 23:02:42 +00006960}
6961
6962llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
John McCall882987f2013-02-28 19:01:20 +00006963 CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00006964 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
Hans Wennborgdcfba332015-10-06 23:40:43 +00006965 return EmitClassRefFromId(CGF, II, false, nullptr);
John McCall31168b02011-06-15 23:02:42 +00006966}
6967
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006968llvm::Value *
John McCall882987f2013-02-28 19:01:20 +00006969CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006970 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00006971 CharUnits Align = CGF.getPointerAlign();
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006972 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006973
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006974 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006975 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
6976 ClassName += ID->getObjCRuntimeNameAsString();
6977 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00006978 ID->isWeakImported());
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006979 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
6980 false, llvm::GlobalValue::PrivateLinkage,
6981 ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00006982 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006983 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00006984 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00006985 }
John McCall7f416cc2015-09-08 08:05:57 +00006986 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00006987}
6988
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00006989/// EmitMetaClassRef - Return a Value * of the address of _class_t
6990/// meta-data
6991///
John McCall882987f2013-02-28 19:01:20 +00006992llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00006993 const ObjCInterfaceDecl *ID,
6994 bool Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00006995 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00006996 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
Rafael Espindola21039aa2014-02-27 16:26:32 +00006997 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006998 llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
6999 MetaClassName += ID->getObjCRuntimeNameAsString();
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007000 llvm::GlobalVariable *MetaClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007001 GetClassGlobal(MetaClassName.str(), Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007002
Rafael Espindola21039aa2014-02-27 16:26:32 +00007003 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00007004 false, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007005 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007006 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007007
Rafael Espindola21039aa2014-02-27 16:26:32 +00007008 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007009 CGM.addCompilerUsedGlobal(Entry);
Rafael Espindola21039aa2014-02-27 16:26:32 +00007010 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007011
John McCall7f416cc2015-09-08 08:05:57 +00007012 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007013}
7014
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007015/// GetClass - Return a reference to the class for the given interface
7016/// decl.
John McCall882987f2013-02-28 19:01:20 +00007017llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007018 const ObjCInterfaceDecl *ID) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007019 if (ID->isWeakImported()) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007020 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
7021 ClassName += ID->getObjCRuntimeNameAsString();
7022 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
Nick Lewycky9a441642014-02-27 00:36:00 +00007023 (void)ClassGV;
Rafael Espindolab3262952014-05-09 00:43:37 +00007024 assert(ClassGV->hasExternalWeakLinkage());
Fariborz Jahanian95ace552009-11-17 22:42:00 +00007025 }
7026
John McCall882987f2013-02-28 19:01:20 +00007027 return EmitClassRef(CGF, ID);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007028}
7029
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007030/// Generates a message send where the super is the receiver. This is
7031/// a message send to self with special delivery semantics indicating
7032/// which class's method should be called.
7033CodeGen::RValue
7034CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007035 ReturnValueSlot Return,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007036 QualType ResultType,
7037 Selector Sel,
7038 const ObjCInterfaceDecl *Class,
7039 bool isCategoryImpl,
7040 llvm::Value *Receiver,
7041 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007042 const CodeGen::CallArgList &CallArgs,
7043 const ObjCMethodDecl *Method) {
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007044 // ...
7045 // Create and init a super structure; this is a (receiver, class)
7046 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00007047 Address ObjCSuper =
7048 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
7049 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007050
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007051 llvm::Value *ReceiverAsObject =
7052 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007053 CGF.Builder.CreateStore(
7054 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00007055 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007056
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007057 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00007058 llvm::Value *Target;
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007059 if (IsClassMessage)
Fariborz Jahanian85b99da2014-08-28 17:05:17 +00007060 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007061 else
John McCall882987f2013-02-28 19:01:20 +00007062 Target = EmitSuperClassRef(CGF, Class);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007063
Mike Stump18bb9282009-05-16 07:57:57 +00007064 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
7065 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00007066 llvm::Type *ClassTy =
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007067 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
7068 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007069 CGF.Builder.CreateStore(
John McCall7f416cc2015-09-08 08:05:57 +00007070 Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007071
John McCall9e8bb002011-05-14 03:10:52 +00007072 return (isVTableDispatchedSelector(Sel))
7073 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
John McCall7f416cc2015-09-08 08:05:57 +00007074 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall9e8bb002011-05-14 03:10:52 +00007075 true, CallArgs, Method)
7076 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007077 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00007078 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00007079 true, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007080}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007081
John McCall882987f2013-02-28 19:01:20 +00007082llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007083 Selector Sel) {
7084 Address Addr = EmitSelectorAddr(CGF, Sel);
7085
7086 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);
7087 LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
7088 llvm::MDNode::get(VMContext, None));
7089 return LI;
7090}
7091
7092Address CGObjCNonFragileABIMac::EmitSelectorAddr(CodeGenFunction &CGF,
7093 Selector Sel) {
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007094 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007095
John McCall7f416cc2015-09-08 08:05:57 +00007096 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007097 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007098 llvm::Constant *Casted =
7099 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
7100 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007101 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
7102 false, llvm::GlobalValue::PrivateLinkage,
7103 Casted, "OBJC_SELECTOR_REFERENCES_");
Michael Gottesman5c205962013-02-05 23:08:45 +00007104 Entry->setExternallyInitialized(true);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00007105 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
John McCall7f416cc2015-09-08 08:05:57 +00007106 Entry->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00007107 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007108 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007109
John McCall7f416cc2015-09-08 08:05:57 +00007110 return Address(Entry, Align);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007111}
John McCall7f416cc2015-09-08 08:05:57 +00007112
Fariborz Jahanian06292952009-02-16 22:52:32 +00007113/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007114/// objc_assign_ivar (id src, id *dst, ptrdiff_t)
Fariborz Jahanian06292952009-02-16 22:52:32 +00007115///
7116void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00007117 llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +00007118 Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007119 llvm::Value *ivarOffset) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007120 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007121 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007122 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007123 assert(Size <= 8 && "does not support size > 8");
7124 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7125 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007126 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7127 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007128 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7129 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007130 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00007131 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007132}
7133
7134/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
7135/// objc_assign_strongCast (id src, id *dst)
7136///
7137void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007138 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007139 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007140 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007141 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007142 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007143 assert(Size <= 8 && "does not support size > 8");
7144 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007145 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007146 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7147 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007148 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7149 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007150 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007151 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
7152 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007153}
7154
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007155void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007156 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007157 Address DestPtr,
7158 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007159 llvm::Value *Size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007160 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
7161 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007162 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size };
John McCall882987f2013-02-28 19:01:20 +00007163 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007164}
7165
Fariborz Jahanian06292952009-02-16 22:52:32 +00007166/// EmitObjCWeakRead - Code gen for loading value of a __weak
7167/// object: objc_read_weak (id *src)
7168///
7169llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007170 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007171 Address AddrWeakObj) {
7172 llvm::Type *DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007173 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007174 llvm::Value *read_weak =
7175 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00007176 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00007177 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007178 return read_weak;
7179}
7180
7181/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
7182/// objc_assign_weak (id src, id *dst)
7183///
7184void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007185 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007186 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007187 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007188 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007189 assert(Size <= 8 && "does not support size > 8");
7190 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7191 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007192 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7193 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007194 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7195 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007196 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007197 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
7198 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007199}
7200
7201/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
7202/// objc_assign_global (id src, id *dst)
7203///
7204void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007205 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00007206 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007207 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007208 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007209 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007210 assert(Size <= 8 && "does not support size > 8");
7211 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7212 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007213 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7214 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007215 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7216 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007217 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00007218 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00007219 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
7220 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00007221 else
John McCall882987f2013-02-28 19:01:20 +00007222 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
7223 args, "threadlocalassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007224}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007225
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007226void
John McCallbd309292010-07-06 01:34:17 +00007227CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
7228 const ObjCAtSynchronizedStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007229 EmitAtSynchronizedStmt(CGF, S,
7230 cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
7231 cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
John McCallbd309292010-07-06 01:34:17 +00007232}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007233
John McCall2ca705e2010-07-24 00:37:23 +00007234llvm::Constant *
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00007235CGObjCNonFragileABIMac::GetEHType(QualType T) {
John McCall2ca705e2010-07-24 00:37:23 +00007236 // There's a particular fixed type info for 'id'.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007237 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
7238 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007239 if (!IDEHType) {
John McCall2ca705e2010-07-24 00:37:23 +00007240 IDEHType =
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007241 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
7242 llvm::GlobalValue::ExternalLinkage, nullptr,
7243 "OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007244 if (CGM.getTriple().isOSBinFormatCOFF())
7245 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));
7246 }
John McCall2ca705e2010-07-24 00:37:23 +00007247 return IDEHType;
7248 }
7249
7250 // All other types should be Objective-C interface pointer types.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007251 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
John McCall2ca705e2010-07-24 00:37:23 +00007252 assert(PT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007253
John McCall2ca705e2010-07-24 00:37:23 +00007254 const ObjCInterfaceType *IT = PT->getInterfaceType();
7255 assert(IT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007256
John McCall2ca705e2010-07-24 00:37:23 +00007257 return GetInterfaceEHType(IT->getDecl(), false);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007258}
John McCall2ca705e2010-07-24 00:37:23 +00007259
John McCallbd309292010-07-06 01:34:17 +00007260void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
7261 const ObjCAtTryStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007262 EmitTryCatchStmt(CGF, S,
7263 cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
7264 cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
7265 cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +00007266}
7267
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007268/// EmitThrowStmt - Generate code for a throw statement.
7269void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007270 const ObjCAtThrowStmt &S,
7271 bool ClearInsertionPoint) {
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007272 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00007273 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00007274 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007275 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
John McCall17afe452010-10-16 08:21:07 +00007276 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007277 } else {
John McCall882987f2013-02-28 19:01:20 +00007278 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
John McCall17afe452010-10-16 08:21:07 +00007279 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007280 }
7281
John McCall17afe452010-10-16 08:21:07 +00007282 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007283 if (ClearInsertionPoint)
7284 CGF.Builder.ClearInsertionPoint();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007285}
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007286
John McCall2ca705e2010-07-24 00:37:23 +00007287llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007288CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007289 bool ForDefinition) {
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007290 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007291 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007292
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007293 // If we don't need a definition, return the entry if found or check
7294 // if we use an external reference.
7295 if (!ForDefinition) {
7296 if (Entry)
7297 return Entry;
Daniel Dunbard7beeea2009-04-07 06:43:45 +00007298
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007299 // If this type (or a super class) has the __objc_exception__
7300 // attribute, emit an external reference.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007301 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {
7302 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();
7303 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
7304 false, llvm::GlobalValue::ExternalLinkage,
7305 nullptr, EHTypeName);
7306 if (CGM.getTriple().isOSBinFormatCOFF()) {
7307 if (ID->hasAttr<DLLExportAttr>())
7308 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7309 else if (ID->hasAttr<DLLImportAttr>())
7310 Entry->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7311 }
7312 return Entry;
7313 }
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007314 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007315
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007316 // Otherwise we need to either make a new entry or fill in the initializer.
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007317 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007318
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007319 std::string VTableName = "objc_ehtype_vtable";
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007320 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007321 if (!VTableGV) {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007322 VTableGV =
7323 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,
7324 llvm::GlobalValue::ExternalLinkage, nullptr,
7325 VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007326 if (CGM.getTriple().isOSBinFormatCOFF())
7327 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));
7328 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007329
Chris Lattnerece04092012-02-07 00:39:47 +00007330 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00007331 llvm::Constant *Values[] = {
David Blaikiee3b172a2015-04-02 18:55:21 +00007332 llvm::ConstantExpr::getGetElementPtr(VTableGV->getValueType(), VTableGV,
7333 VTableIdx),
7334 GetClassName(ID->getObjCRuntimeNameAsString()),
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007335 GetClassGlobal((getClassSymbolPrefix() + ClassName).str()),
7336 };
7337 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007338
Rafael Espindola554256c2014-02-26 22:25:45 +00007339 llvm::GlobalValue::LinkageTypes L = ForDefinition
7340 ? llvm::GlobalValue::ExternalLinkage
7341 : llvm::GlobalValue::WeakAnyLinkage;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007342 if (Entry) {
7343 Entry->setInitializer(Init);
7344 } else {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007345 Entry =
7346 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, L,
7347 Init, ("OBJC_EHTYPE_$_" + ClassName).str());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007348 if (CGM.getTriple().isOSBinFormatCOFF())
7349 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
7350 if (ID->hasAttr<DLLExportAttr>())
7351 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007352 }
Rafael Espindola554256c2014-02-26 22:25:45 +00007353 assert(Entry->getLinkage() == L);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007354
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007355 if (!CGM.getTriple().isOSBinFormatCOFF())
7356 if (ID->getVisibility() == HiddenVisibility)
7357 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007358
7359 const auto &DL = CGM.getDataLayout();
7360 Entry->setAlignment(DL.getABITypeAlignment(ObjCTypes.EHTypeTy));
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007361
Rafael Espindola554256c2014-02-26 22:25:45 +00007362 if (ForDefinition)
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007363 Entry->setSection("__DATA,__objc_const");
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007364
7365 return Entry;
7366}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007367
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00007368/* *** */
7369
Daniel Dunbarb036db82008-08-13 03:21:16 +00007370CodeGen::CGObjCRuntime *
7371CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00007372 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
7373 case ObjCRuntime::FragileMacOSX:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007374 return new CGObjCMac(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00007375
7376 case ObjCRuntime::MacOSX:
7377 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00007378 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00007379 return new CGObjCNonFragileABIMac(CGM);
7380
David Chisnallb601c962012-07-03 20:49:52 +00007381 case ObjCRuntime::GNUstep:
7382 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +00007383 case ObjCRuntime::ObjFW:
John McCall5fb5df92012-06-20 06:18:46 +00007384 llvm_unreachable("these runtimes are not Mac runtimes");
7385 }
7386 llvm_unreachable("bad runtime");
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007387}