blob: b290ae37239f69ffa521813968115f3faf7a32f3 [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
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
John McCalled1ae862011-01-28 11:13:47 +000015#include "CGCleanup.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000016#include "CGObjCRuntime.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"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000028#include "llvm/ADT/CachedHashString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "llvm/ADT/DenseSet.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallString.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000033#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Module.h"
Daniel Dunbard027a922009-09-07 00:20:42 +000039#include "llvm/Support/raw_ostream.h"
Torok Edwindb714922009-08-24 13:25:12 +000040#include <cstdio>
Daniel Dunbar303e2c22008-08-11 02:45:11 +000041
42using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000043using namespace CodeGen;
Daniel Dunbar303e2c22008-08-11 02:45:11 +000044
45namespace {
Daniel Dunbar8b8683f2008-08-12 00:12:39 +000046
Daniel Dunbar59e476b2009-08-03 17:06:42 +000047// FIXME: We should find a nicer way to make the labels for metadata, string
48// concatenation is lame.
Daniel Dunbarb036db82008-08-13 03:21:16 +000049
Fariborz Jahanian279eda62009-01-21 22:04:16 +000050class ObjCCommonTypesHelper {
Owen Anderson170229f2009-07-14 23:10:40 +000051protected:
52 llvm::LLVMContext &VMContext;
Daniel Dunbar59e476b2009-08-03 17:06:42 +000053
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000054private:
John McCall9dc0db22011-05-15 01:53:33 +000055 // The types of these functions don't really matter because we
56 // should always bitcast before calling them.
57
58 /// id objc_msgSend (id, SEL, ...)
59 ///
60 /// The default messenger, used for sends whose ABI is unchanged from
61 /// the all-integer/pointer case.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000062 llvm::Constant *getMessageSendFn() const {
John McCall31168b02011-06-15 23:02:42 +000063 // Add the non-lazy-bind attribute, since objc_msgSend is likely to
64 // be called a lot.
Chris Lattnera5f58b02011-07-09 17:41:47 +000065 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Bill Wendling8594fcb2013-01-31 00:30:05 +000066 return
67 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
68 params, true),
69 "objc_msgSend",
70 llvm::AttributeSet::get(CGM.getLLVMContext(),
71 llvm::AttributeSet::FunctionIndex,
72 llvm::Attribute::NonLazyBind));
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000073 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000074
John McCall9dc0db22011-05-15 01:53:33 +000075 /// void objc_msgSend_stret (id, SEL, ...)
76 ///
77 /// The messenger used when the return value is an aggregate returned
78 /// by indirect reference in the first argument, and therefore the
79 /// self and selector parameters are shifted over by one.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000080 llvm::Constant *getMessageSendStretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +000081 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +000082 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
83 params, true),
84 "objc_msgSend_stret");
Daniel Dunbar59e476b2009-08-03 17:06:42 +000085
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000086 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +000087
John McCall9dc0db22011-05-15 01:53:33 +000088 /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
89 ///
90 /// The messenger used when the return value is returned on the x87
91 /// floating-point stack; without a special entrypoint, the nil case
92 /// would be unbalanced.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000093 llvm::Constant *getMessageSendFpretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +000094 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
Chris Lattnerece04092012-02-07 00:39:47 +000095 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
96 params, true),
John McCall9dc0db22011-05-15 01:53:33 +000097 "objc_msgSend_fpret");
Daniel Dunbar59e476b2009-08-03 17:06:42 +000098
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +000099 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000100
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000101 /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
102 ///
103 /// The messenger used when the return value is returned in two values on the
104 /// x87 floating point stack; without a special entrypoint, the nil case
105 /// would be unbalanced. Only used on 64-bit X86.
106 llvm::Constant *getMessageSendFp2retFn() const {
107 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
108 llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
109 llvm::Type *resultType =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000110 llvm::StructType::get(longDoubleType, longDoubleType, nullptr);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000111
112 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
113 params, true),
114 "objc_msgSend_fp2ret");
115 }
116
John McCall9dc0db22011-05-15 01:53:33 +0000117 /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
118 ///
119 /// The messenger used for super calls, which have different dispatch
120 /// semantics. The class passed is the superclass of the current
121 /// class.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000122 llvm::Constant *getMessageSendSuperFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000123 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000124 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000125 params, true),
126 "objc_msgSendSuper");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000127 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000128
John McCall9dc0db22011-05-15 01:53:33 +0000129 /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
130 ///
131 /// A slightly different messenger used for super calls. The class
132 /// passed is the current class.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000133 llvm::Constant *getMessageSendSuperFn2() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000135 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000136 params, true),
137 "objc_msgSendSuper2");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000138 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000139
John McCall9dc0db22011-05-15 01:53:33 +0000140 /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
141 /// SEL op, ...)
142 ///
143 /// The messenger used for super calls which return an aggregate indirectly.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000144 llvm::Constant *getMessageSendSuperStretFn() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000145 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000146 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000147 llvm::FunctionType::get(CGM.VoidTy, params, true),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000148 "objc_msgSendSuper_stret");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000149 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000150
John McCall9dc0db22011-05-15 01:53:33 +0000151 /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
152 /// SEL op, ...)
153 ///
154 /// objc_msgSendSuper_stret with the super2 semantics.
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000155 llvm::Constant *getMessageSendSuperStretFn2() const {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000156 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000157 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000158 llvm::FunctionType::get(CGM.VoidTy, params, true),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000159 "objc_msgSendSuper2_stret");
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000160 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000161
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000162 llvm::Constant *getMessageSendSuperFpretFn() const {
163 // There is no objc_msgSendSuper_fpret? How can that work?
164 return getMessageSendSuperFn();
165 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000166
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000167 llvm::Constant *getMessageSendSuperFpretFn2() const {
168 // There is no objc_msgSendSuper_fpret? How can that work?
169 return getMessageSendSuperFn2();
170 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000171
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000172protected:
173 CodeGen::CodeGenModule &CGM;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000174
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000175public:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000176 llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000177 llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
Tim Northover238b5082014-03-29 13:42:40 +0000178 llvm::Type *IvarOffsetVarTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000179
Daniel Dunbar5d715592008-08-12 05:28:47 +0000180 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000181 llvm::Type *ObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000182
Fariborz Jahanian406b1172008-11-18 20:18:11 +0000183 /// PtrObjectPtrTy - LLVM type for id *
Chris Lattnera5f58b02011-07-09 17:41:47 +0000184 llvm::Type *PtrObjectPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000185
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000186 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000187 llvm::Type *SelectorPtrTy;
Douglas Gregor020de322012-01-17 18:36:30 +0000188
189private:
Daniel Dunbarb036db82008-08-13 03:21:16 +0000190 /// ProtocolPtrTy - LLVM type for external protocol handles
191 /// (typeof(Protocol))
Chris Lattnera5f58b02011-07-09 17:41:47 +0000192 llvm::Type *ExternalProtocolPtrTy;
Douglas Gregor020de322012-01-17 18:36:30 +0000193
194public:
195 llvm::Type *getExternalProtocolPtrTy() {
196 if (!ExternalProtocolPtrTy) {
197 // FIXME: It would be nice to unify this with the opaque type, so that the
198 // IR comes out a bit cleaner.
199 CodeGen::CodeGenTypes &Types = CGM.getTypes();
200 ASTContext &Ctx = CGM.getContext();
201 llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
202 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
203 }
204
205 return ExternalProtocolPtrTy;
206 }
207
Daniel Dunbarc722b852008-08-30 03:02:31 +0000208 // SuperCTy - clang type for struct objc_super.
209 QualType SuperCTy;
210 // SuperPtrCTy - clang type for struct objc_super *.
211 QualType SuperPtrCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000212
Daniel Dunbarf6397fe2008-08-23 04:28:29 +0000213 /// SuperTy - LLVM type for struct objc_super.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000214 llvm::StructType *SuperTy;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +0000215 /// SuperPtrTy - LLVM type for struct objc_super *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000216 llvm::Type *SuperPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000217
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000218 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
219 /// in GCC parlance).
Chris Lattnera5f58b02011-07-09 17:41:47 +0000220 llvm::StructType *PropertyTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000221
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000222 /// PropertyListTy - LLVM type for struct objc_property_list
223 /// (_prop_list_t in GCC parlance).
Chris Lattnera5f58b02011-07-09 17:41:47 +0000224 llvm::StructType *PropertyListTy;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000225 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000226 llvm::Type *PropertyListPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000227
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000228 // MethodTy - LLVM type for struct objc_method.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000229 llvm::StructType *MethodTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000230
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000231 /// CacheTy - LLVM type for struct objc_cache.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000232 llvm::Type *CacheTy;
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000233 /// CachePtrTy - LLVM type for struct objc_cache *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000234 llvm::Type *CachePtrTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000235
Chris Lattnerce8754e2009-04-22 02:44:54 +0000236 llvm::Constant *getGetPropertyFn() {
237 CodeGen::CodeGenTypes &Types = CGM.getTypes();
238 ASTContext &Ctx = CGM.getContext();
239 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
John McCall2da83a32010-02-26 00:48:12 +0000240 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
241 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
Benjamin Kramer30934732016-07-02 11:41:41 +0000242 CanQualType Params[] = {
243 IdType, SelType,
244 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy};
Chris Lattner2192fe52011-07-18 04:24:23 +0000245 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000246 Types.GetFunctionType(
247 Types.arrangeBuiltinFunctionDeclaration(IdType, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000248 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
249 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000250
Chris Lattnerce8754e2009-04-22 02:44:54 +0000251 llvm::Constant *getSetPropertyFn() {
252 CodeGen::CodeGenTypes &Types = CGM.getTypes();
253 ASTContext &Ctx = CGM.getContext();
254 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
John McCall2da83a32010-02-26 00:48:12 +0000255 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
256 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
Benjamin Kramer30934732016-07-02 11:41:41 +0000257 CanQualType Params[] = {
258 IdType,
259 SelType,
260 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(),
261 IdType,
262 Ctx.BoolTy,
263 Ctx.BoolTy};
Chris Lattner2192fe52011-07-18 04:24:23 +0000264 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000265 Types.GetFunctionType(
266 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000267 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
268 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000269
Ted Kremeneke65b0862012-03-06 20:05:56 +0000270 llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
271 CodeGen::CodeGenTypes &Types = CGM.getTypes();
272 ASTContext &Ctx = CGM.getContext();
273 // void objc_setProperty_atomic(id self, SEL _cmd,
274 // id newValue, ptrdiff_t offset);
275 // void objc_setProperty_nonatomic(id self, SEL _cmd,
276 // id newValue, ptrdiff_t offset);
277 // void objc_setProperty_atomic_copy(id self, SEL _cmd,
278 // id newValue, ptrdiff_t offset);
279 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
280 // id newValue, ptrdiff_t offset);
281
282 SmallVector<CanQualType,4> Params;
283 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
284 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
285 Params.push_back(IdType);
286 Params.push_back(SelType);
287 Params.push_back(IdType);
288 Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
289 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000290 Types.GetFunctionType(
291 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000292 const char *name;
293 if (atomic && copy)
294 name = "objc_setProperty_atomic_copy";
295 else if (atomic && !copy)
296 name = "objc_setProperty_atomic";
297 else if (!atomic && copy)
298 name = "objc_setProperty_nonatomic_copy";
299 else
300 name = "objc_setProperty_nonatomic";
301
302 return CGM.CreateRuntimeFunction(FTy, name);
303 }
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000304
305 llvm::Constant *getCopyStructFn() {
306 CodeGen::CodeGenTypes &Types = CGM.getTypes();
307 ASTContext &Ctx = CGM.getContext();
308 // void objc_copyStruct (void *, const void *, size_t, bool, bool)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000309 SmallVector<CanQualType,5> Params;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000310 Params.push_back(Ctx.VoidPtrTy);
311 Params.push_back(Ctx.VoidPtrTy);
312 Params.push_back(Ctx.LongTy);
313 Params.push_back(Ctx.BoolTy);
314 Params.push_back(Ctx.BoolTy);
Chris Lattner2192fe52011-07-18 04:24:23 +0000315 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000316 Types.GetFunctionType(
317 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000318 return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
319 }
320
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000321 /// This routine declares and returns address of:
322 /// void objc_copyCppObjectAtomic(
323 /// void *dest, const void *src,
324 /// void (*copyHelper) (void *dest, const void *source));
325 llvm::Constant *getCppAtomicObjectFunction() {
326 CodeGen::CodeGenTypes &Types = CGM.getTypes();
327 ASTContext &Ctx = CGM.getContext();
328 /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
329 SmallVector<CanQualType,3> Params;
330 Params.push_back(Ctx.VoidPtrTy);
331 Params.push_back(Ctx.VoidPtrTy);
332 Params.push_back(Ctx.VoidPtrTy);
333 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000334 Types.GetFunctionType(
335 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +0000336 return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
337 }
338
Chris Lattnerce8754e2009-04-22 02:44:54 +0000339 llvm::Constant *getEnumerationMutationFn() {
Daniel Dunbar9d82da42009-07-11 20:32:50 +0000340 CodeGen::CodeGenTypes &Types = CGM.getTypes();
341 ASTContext &Ctx = CGM.getContext();
Chris Lattnerce8754e2009-04-22 02:44:54 +0000342 // void objc_enumerationMutation (id)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 SmallVector<CanQualType,1> Params;
John McCall2da83a32010-02-26 00:48:12 +0000344 Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
Chris Lattner2192fe52011-07-18 04:24:23 +0000345 llvm::FunctionType *FTy =
John McCallc56a8b32016-03-11 04:30:31 +0000346 Types.GetFunctionType(
347 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
Chris Lattnerce8754e2009-04-22 02:44:54 +0000348 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
349 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000350
Douglas Gregor24ae22c2016-04-01 23:23:52 +0000351 llvm::Constant *getLookUpClassFn() {
352 CodeGen::CodeGenTypes &Types = CGM.getTypes();
353 ASTContext &Ctx = CGM.getContext();
354 // Class objc_lookUpClass (const char *)
355 SmallVector<CanQualType,1> Params;
356 Params.push_back(
357 Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst())));
358 llvm::FunctionType *FTy =
359 Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration(
360 Ctx.getCanonicalType(Ctx.getObjCClassType()),
361 Params));
362 return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass");
363 }
364
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000365 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattnerce8754e2009-04-22 02:44:54 +0000366 llvm::Constant *getGcReadWeakFn() {
367 // id objc_read_weak (id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000368 llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000369 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000370 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattnerce8754e2009-04-22 02:44:54 +0000371 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000372 }
373
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000374 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000375 llvm::Constant *getGcAssignWeakFn() {
376 // id objc_assign_weak (id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000377 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000378 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000379 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner6fdd57c2009-04-17 22:12:36 +0000380 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
381 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000382
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000383 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000384 llvm::Constant *getGcAssignGlobalFn() {
385 // id objc_assign_global(id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000386 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000387 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000388 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000389 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
390 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000391
Fariborz Jahanian217af242010-07-20 20:30:03 +0000392 /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
393 llvm::Constant *getGcAssignThreadLocalFn() {
394 // id objc_assign_threadlocal(id src, id * dest)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000395 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Fariborz Jahanian217af242010-07-20 20:30:03 +0000396 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000397 llvm::FunctionType::get(ObjectPtrTy, args, false);
Fariborz Jahanian217af242010-07-20 20:30:03 +0000398 return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
399 }
400
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000401 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000402 llvm::Constant *getGcAssignIvarFn() {
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000403 // id objc_assign_ivar(id, id *, ptrdiff_t)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000404 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
405 CGM.PtrDiffTy };
Owen Anderson170229f2009-07-14 23:10:40 +0000406 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000407 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000408 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
409 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000410
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000411 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
412 llvm::Constant *GcMemmoveCollectableFn() {
413 // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000414 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
John McCall9dc0db22011-05-15 01:53:33 +0000415 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000416 return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
417 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000418
Fariborz Jahanianeee54df2009-01-22 00:37:21 +0000419 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000420 llvm::Constant *getGcAssignStrongCastFn() {
Fariborz Jahanian217af242010-07-20 20:30:03 +0000421 // id objc_assign_strongCast(id, id *)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000422 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000423 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000424 llvm::FunctionType::get(ObjectPtrTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000425 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
426 }
Anders Carlsson9ab53d12009-02-16 22:59:18 +0000427
428 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000429 llvm::Constant *getExceptionThrowFn() {
430 // void objc_exception_throw(id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000431 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattner0a696a422009-04-22 02:38:11 +0000432 llvm::FunctionType *FTy =
John McCall9dc0db22011-05-15 01:53:33 +0000433 llvm::FunctionType::get(CGM.VoidTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000434 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
435 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000436
Fariborz Jahanian3336de12010-05-28 17:34:43 +0000437 /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
438 llvm::Constant *getExceptionRethrowFn() {
439 // void objc_exception_rethrow(void)
John McCall9dc0db22011-05-15 01:53:33 +0000440 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
Fariborz Jahanian3336de12010-05-28 17:34:43 +0000441 return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
442 }
443
Daniel Dunbar94ceb612009-02-24 01:43:46 +0000444 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerdcceee72009-04-06 16:53:45 +0000445 llvm::Constant *getSyncEnterFn() {
Aaron Ballman9c004462012-09-06 16:44:16 +0000446 // int objc_sync_enter (id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000447 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattnerdcceee72009-04-06 16:53:45 +0000448 llvm::FunctionType *FTy =
Aaron Ballman9c004462012-09-06 16:44:16 +0000449 llvm::FunctionType::get(CGM.IntTy, args, false);
Chris Lattnerdcceee72009-04-06 16:53:45 +0000450 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
451 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000452
Daniel Dunbar94ceb612009-02-24 01:43:46 +0000453 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattner0a696a422009-04-22 02:38:11 +0000454 llvm::Constant *getSyncExitFn() {
Aaron Ballman9c004462012-09-06 16:44:16 +0000455 // int objc_sync_exit (id)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000456 llvm::Type *args[] = { ObjectPtrTy };
Chris Lattner0a696a422009-04-22 02:38:11 +0000457 llvm::FunctionType *FTy =
Aaron Ballman9c004462012-09-06 16:44:16 +0000458 llvm::FunctionType::get(CGM.IntTy, args, false);
Chris Lattner0a696a422009-04-22 02:38:11 +0000459 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
460 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000461
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000462 llvm::Constant *getSendFn(bool IsSuper) const {
463 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
464 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000465
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000466 llvm::Constant *getSendFn2(bool IsSuper) const {
467 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
468 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000469
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000470 llvm::Constant *getSendStretFn(bool IsSuper) const {
471 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
472 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000473
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000474 llvm::Constant *getSendStretFn2(bool IsSuper) const {
475 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
476 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000477
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000478 llvm::Constant *getSendFpretFn(bool IsSuper) const {
479 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
480 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000481
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +0000482 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
483 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
484 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000485
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000486 llvm::Constant *getSendFp2retFn(bool IsSuper) const {
487 return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
488 }
489
490 llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
491 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
492 }
493
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000494 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000495};
Daniel Dunbarf6397fe2008-08-23 04:28:29 +0000496
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000497/// ObjCTypesHelper - Helper class that encapsulates lazy
498/// construction of varies types used during ObjC generation.
499class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000500public:
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000501 /// SymtabTy - LLVM type for struct objc_symtab.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000502 llvm::StructType *SymtabTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000503 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000504 llvm::Type *SymtabPtrTy;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000505 /// ModuleTy - LLVM type for struct objc_module.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000506 llvm::StructType *ModuleTy;
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000507
Daniel Dunbarb036db82008-08-13 03:21:16 +0000508 /// ProtocolTy - LLVM type for struct objc_protocol.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000509 llvm::StructType *ProtocolTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000510 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000511 llvm::Type *ProtocolPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000512 /// ProtocolExtensionTy - LLVM type for struct
513 /// objc_protocol_extension.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000514 llvm::StructType *ProtocolExtensionTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000515 /// ProtocolExtensionTy - LLVM type for struct
516 /// objc_protocol_extension *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000517 llvm::Type *ProtocolExtensionPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000518 /// MethodDescriptionTy - LLVM type for struct
519 /// objc_method_description.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000520 llvm::StructType *MethodDescriptionTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000521 /// MethodDescriptionListTy - LLVM type for struct
522 /// objc_method_description_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000523 llvm::StructType *MethodDescriptionListTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000524 /// MethodDescriptionListPtrTy - LLVM type for struct
525 /// objc_method_description_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000526 llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000527 /// ProtocolListTy - LLVM type for struct objc_property_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000528 llvm::StructType *ProtocolListTy;
Daniel Dunbarb036db82008-08-13 03:21:16 +0000529 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000530 llvm::Type *ProtocolListPtrTy;
Daniel Dunbar938a77f2008-08-22 20:34:54 +0000531 /// CategoryTy - LLVM type for struct objc_category.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000532 llvm::StructType *CategoryTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000533 /// ClassTy - LLVM type for struct objc_class.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000534 llvm::StructType *ClassTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000535 /// ClassPtrTy - LLVM type for struct objc_class *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000536 llvm::Type *ClassPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000537 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000538 llvm::StructType *ClassExtensionTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000539 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000540 llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000541 // IvarTy - LLVM type for struct objc_ivar.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000542 llvm::StructType *IvarTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000543 /// IvarListTy - LLVM type for struct objc_ivar_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000544 llvm::Type *IvarListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000545 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000546 llvm::Type *IvarListPtrTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000547 /// MethodListTy - LLVM type for struct objc_method_list.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000548 llvm::Type *MethodListTy;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000549 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000550 llvm::Type *MethodListPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000551
Anders Carlsson9ff22482008-09-09 10:10:21 +0000552 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000553 llvm::Type *ExceptionDataTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000554
Anders Carlsson9ff22482008-09-09 10:10:21 +0000555 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000556 llvm::Constant *getExceptionTryEnterFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000557 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000558 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000559 llvm::FunctionType::get(CGM.VoidTy, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000560 "objc_exception_try_enter");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000561 }
Anders Carlsson9ff22482008-09-09 10:10:21 +0000562
563 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000564 llvm::Constant *getExceptionTryExitFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000565 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson170229f2009-07-14 23:10:40 +0000566 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000567 llvm::FunctionType::get(CGM.VoidTy, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000568 "objc_exception_try_exit");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000569 }
Anders Carlsson9ff22482008-09-09 10:10:21 +0000570
571 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000572 llvm::Constant *getExceptionExtractFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000573 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000574 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000575 params, false),
Chris Lattnerc6406db2009-04-22 02:26:14 +0000576 "objc_exception_extract");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000577 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000578
Anders Carlsson9ff22482008-09-09 10:10:21 +0000579 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000580 llvm::Constant *getExceptionMatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000581 llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000582 return CGM.CreateRuntimeFunction(
John McCall9dc0db22011-05-15 01:53:33 +0000583 llvm::FunctionType::get(CGM.Int32Ty, params, false),
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000584 "objc_exception_match");
Chris Lattnerc6406db2009-04-22 02:26:14 +0000585 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000586
Anders Carlsson9ff22482008-09-09 10:10:21 +0000587 /// SetJmpFn - LLVM _setjmp function.
Chris Lattnerc6406db2009-04-22 02:26:14 +0000588 llvm::Constant *getSetJmpFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000589 // This is specifically the prototype for x86.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000590 llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
Bill Wendling8594fcb2013-01-31 00:30:05 +0000591 return
592 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
593 params, false),
594 "_setjmp",
595 llvm::AttributeSet::get(CGM.getLLVMContext(),
596 llvm::AttributeSet::FunctionIndex,
597 llvm::Attribute::NonLazyBind));
Chris Lattnerc6406db2009-04-22 02:26:14 +0000598 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000599
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000600public:
601 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000602};
603
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000604/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000605/// modern abi
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000606class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000607public:
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000608 // MethodListnfABITy - LLVM for struct _method_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000609 llvm::StructType *MethodListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000610
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000611 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000612 llvm::Type *MethodListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000613
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000614 // ProtocolnfABITy = LLVM for struct _protocol_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000615 llvm::StructType *ProtocolnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000616
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000617 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000618 llvm::Type *ProtocolnfABIPtrTy;
Daniel Dunbar8de90f02009-02-15 07:36:20 +0000619
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000620 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
Chris Lattnera5f58b02011-07-09 17:41:47 +0000621 llvm::StructType *ProtocolListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000622
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000623 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000624 llvm::Type *ProtocolListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000625
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000626 // ClassnfABITy - LLVM for struct _class_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000627 llvm::StructType *ClassnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000628
Fariborz Jahanian71394042009-01-23 23:53:38 +0000629 // ClassnfABIPtrTy - LLVM for struct _class_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000630 llvm::Type *ClassnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000631
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000632 // IvarnfABITy - LLVM for struct _ivar_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000633 llvm::StructType *IvarnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000634
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000635 // IvarListnfABITy - LLVM for struct _ivar_list_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000636 llvm::StructType *IvarListnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000637
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000638 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000639 llvm::Type *IvarListnfABIPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000640
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000641 // ClassRonfABITy - LLVM for struct _class_ro_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000642 llvm::StructType *ClassRonfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000643
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000644 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000645 llvm::Type *ImpnfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000646
Fariborz Jahanian0232c052009-01-23 01:46:23 +0000647 // CategorynfABITy - LLVM for struct _category_t
Chris Lattnera5f58b02011-07-09 17:41:47 +0000648 llvm::StructType *CategorynfABITy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000649
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000650 // New types for nonfragile abi messaging.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000651
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000652 // MessageRefTy - LLVM for:
653 // struct _message_ref_t {
654 // IMP messenger;
655 // SEL name;
656 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000657 llvm::StructType *MessageRefTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000658 // MessageRefCTy - clang type for struct _message_ref_t
659 QualType MessageRefCTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000660
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000661 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000662 llvm::Type *MessageRefPtrTy;
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +0000663 // MessageRefCPtrTy - clang type for struct _message_ref_t*
664 QualType MessageRefCPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000665
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000666 // SuperMessageRefTy - LLVM for:
667 // struct _super_message_ref_t {
668 // SUPER_IMP messenger;
669 // SEL name;
670 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000671 llvm::StructType *SuperMessageRefTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000672
Fariborz Jahanian82c72e12009-02-03 23:49:23 +0000673 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Chris Lattnera5f58b02011-07-09 17:41:47 +0000674 llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +0000675
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000676 llvm::Constant *getMessageSendFixupFn() {
677 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000678 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000679 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000680 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000681 "objc_msgSend_fixup");
682 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000683
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000684 llvm::Constant *getMessageSendFpretFixupFn() {
685 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000686 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000688 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000689 "objc_msgSend_fpret_fixup");
690 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000691
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000692 llvm::Constant *getMessageSendStretFixupFn() {
693 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000694 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000695 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000696 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000697 "objc_msgSend_stret_fixup");
698 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000699
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000700 llvm::Constant *getMessageSendSuper2FixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000701 // id objc_msgSendSuper2_fixup (struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000702 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000703 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000704 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000705 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000706 "objc_msgSendSuper2_fixup");
707 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000708
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000709 llvm::Constant *getMessageSendSuper2StretFixupFn() {
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000710 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000711 // struct _super_message_ref_t*, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000712 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000713 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000714 params, true),
Chris Lattner2dfdb3e2009-04-22 02:53:24 +0000715 "objc_msgSendSuper2_stret_fixup");
716 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000717
Chris Lattnera7c00b42009-04-22 02:15:23 +0000718 llvm::Constant *getObjCEndCatchFn() {
John McCall9dc0db22011-05-15 01:53:33 +0000719 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000720 "objc_end_catch");
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000721
Chris Lattnera7c00b42009-04-22 02:15:23 +0000722 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000723
Chris Lattnera7c00b42009-04-22 02:15:23 +0000724 llvm::Constant *getObjCBeginCatchFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000725 llvm::Type *params[] = { Int8PtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +0000726 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
John McCall9dc0db22011-05-15 01:53:33 +0000727 params, false),
Chris Lattnera7c00b42009-04-22 02:15:23 +0000728 "objc_begin_catch");
729 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +0000730
Chris Lattnera5f58b02011-07-09 17:41:47 +0000731 llvm::StructType *EHTypeTy;
732 llvm::Type *EHTypePtrTy;
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +0000733
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000734 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000735};
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000736
Saleem Abdulrasool271106c2016-09-16 23:41:13 +0000737enum class ObjCLabelType {
738 ClassName,
739 MethodVarName,
740 MethodVarType,
741 PropertyName,
742};
743
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000744class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000745public:
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000746 class SKIP_SCAN {
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000747 public:
748 unsigned skip;
749 unsigned scan;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000750 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
Daniel Dunbar7b89ace2009-05-03 13:44:42 +0000751 : skip(_skip), scan(_scan) {}
Fariborz Jahaniancbaf73c2009-03-11 20:59:05 +0000752 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000753
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000754 /// opcode for captured block variables layout 'instructions'.
755 /// In the following descriptions, 'I' is the value of the immediate field.
756 /// (field following the opcode).
757 ///
758 enum BLOCK_LAYOUT_OPCODE {
759 /// An operator which affects how the following layout should be
760 /// interpreted.
761 /// I == 0: Halt interpretation and treat everything else as
762 /// a non-pointer. Note that this instruction is equal
763 /// to '\0'.
764 /// I != 0: Currently unused.
765 BLOCK_LAYOUT_OPERATOR = 0,
766
767 /// The next I+1 bytes do not contain a value of object pointer type.
768 /// Note that this can leave the stream unaligned, meaning that
769 /// subsequent word-size instructions do not begin at a multiple of
770 /// the pointer size.
771 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
772
773 /// The next I+1 words do not contain a value of object pointer type.
774 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
775 /// when the required skip quantity is a multiple of the pointer size.
776 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
777
778 /// The next I+1 words are __strong pointers to Objective-C
779 /// objects or blocks.
780 BLOCK_LAYOUT_STRONG = 3,
781
782 /// The next I+1 words are pointers to __block variables.
783 BLOCK_LAYOUT_BYREF = 4,
784
785 /// The next I+1 words are __weak pointers to Objective-C
786 /// objects or blocks.
787 BLOCK_LAYOUT_WEAK = 5,
788
789 /// The next I+1 words are __unsafe_unretained pointers to
790 /// Objective-C objects or blocks.
791 BLOCK_LAYOUT_UNRETAINED = 6
792
793 /// The next I+1 words are block or object pointers with some
794 /// as-yet-unspecified ownership semantics. If we add more
795 /// flavors of ownership semantics, values will be taken from
796 /// this range.
797 ///
798 /// This is included so that older tools can at least continue
799 /// processing the layout past such things.
800 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
801
802 /// All other opcodes are reserved. Halt interpretation and
803 /// treat everything else as opaque.
804 };
805
806 class RUN_SKIP {
807 public:
808 enum BLOCK_LAYOUT_OPCODE opcode;
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000809 CharUnits block_var_bytepos;
810 CharUnits block_var_size;
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000811 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000812 CharUnits BytePos = CharUnits::Zero(),
813 CharUnits Size = CharUnits::Zero())
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000814 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000815
816 // Allow sorting based on byte pos.
817 bool operator<(const RUN_SKIP &b) const {
818 return block_var_bytepos < b.block_var_bytepos;
819 }
820 };
821
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000822protected:
Owen Andersonae86c192009-07-13 04:10:07 +0000823 llvm::LLVMContext &VMContext;
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000824 // FIXME! May not be needing this after all.
Daniel Dunbar8b8683f2008-08-12 00:12:39 +0000825 unsigned ObjCABI;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000826
Fariborz Jahanian196f9382012-10-25 21:15:04 +0000827 // arc/mrr layout of captured block literal variables.
828 SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000829
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000830 /// LazySymbols - Symbols to generate a lazy reference for. See
831 /// DefinedSymbols and FinishModule().
Daniel Dunbard027a922009-09-07 00:20:42 +0000832 llvm::SetVector<IdentifierInfo*> LazySymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000833
Daniel Dunbarc61d0e92008-08-25 06:02:07 +0000834 /// DefinedSymbols - External symbols which are defined by this
835 /// module. The symbols in this list and LazySymbols are used to add
836 /// special linker symbols which ensure that Objective-C modules are
837 /// linked properly.
Daniel Dunbard027a922009-09-07 00:20:42 +0000838 llvm::SetVector<IdentifierInfo*> DefinedSymbols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000839
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +0000840 /// ClassNames - uniqued class names.
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000841 llvm::StringMap<llvm::GlobalVariable*> ClassNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000842
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000843 /// MethodVarNames - uniqued method variable names.
844 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000845
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000846 /// DefinedCategoryNames - list of category names in form Class_Category.
Justin Lebar5e83dfe2016-10-21 21:45:01 +0000847 llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames;
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +0000848
Daniel Dunbarb036db82008-08-13 03:21:16 +0000849 /// MethodVarTypes - uniqued method type signatures. We have to use
850 /// a StringMap here because have no other unique reference.
851 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000852
Daniel Dunbar3c76cb52008-08-26 21:51:14 +0000853 /// MethodDefinitions - map of methods which have been defined in
854 /// this translation unit.
855 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000856
Daniel Dunbar80a840b2008-08-23 00:19:03 +0000857 /// PropertyNames - uniqued method variable names.
858 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000859
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000860 /// ClassReferences - uniqued class references.
861 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000862
Daniel Dunbarcb515c82008-08-12 03:39:23 +0000863 /// SelectorReferences - uniqued selector references.
864 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000865
Daniel Dunbarb036db82008-08-13 03:21:16 +0000866 /// Protocols - Protocols for which an objc_protocol structure has
867 /// been emitted. Forward declarations are handled by creating an
868 /// empty structure whose initializer is filled in when/if defined.
869 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000870
Daniel Dunbarc475d422008-10-29 22:36:39 +0000871 /// DefinedProtocols - Protocols which have actually been
872 /// defined. We should not need this, see FIXME in GenerateProtocol.
873 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000874
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000875 /// DefinedClasses - List of defined classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000876 SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +0000877
878 /// ImplementedClasses - List of @implemented classes.
879 SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000880
881 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000882 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000883
Daniel Dunbar22d82ed2008-08-21 04:36:09 +0000884 /// DefinedCategories - List of defined categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000885 SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000886
Daniel Dunbar9a017d72009-05-15 22:33:15 +0000887 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000888 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000889
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000890 /// GetNameForMethod - Return a name for the given method.
891 /// \param[out] NameOut - The return value.
892 void GetNameForMethod(const ObjCMethodDecl *OMD,
893 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000894 SmallVectorImpl<char> &NameOut);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000895
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000896 /// GetMethodVarName - Return a unique constant for the given
897 /// selector's name. The return value has type char *.
898 llvm::Constant *GetMethodVarName(Selector Sel);
899 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000900
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000901 /// GetMethodVarType - Return a unique constant for the given
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000902 /// method's type encoding string. The return value has type char *.
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000903
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000904 // FIXME: This is a horrible name.
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000905 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
906 bool Extended = false);
Daniel Dunbarf5c18462009-04-20 06:54:31 +0000907 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000908
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000909 /// GetPropertyName - Return a unique constant for the given
910 /// name. The return value has type char *.
911 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000912
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +0000913 // FIXME: This can be dropped once string functions are unified.
914 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
915 const Decl *Container);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000916
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +0000917 /// GetClassName - Return a unique constant for the given selector's
Fariborz Jahanian451b92a2014-07-16 16:16:04 +0000918 /// runtime name (which may change via use of objc_runtime_name attribute on
919 /// class or protocol definition. The return value has type char *.
920 llvm::Constant *GetClassName(StringRef RuntimeName);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000921
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +0000922 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
923
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +0000924 /// BuildIvarLayout - Builds ivar layout bitmap for the class
925 /// implementation for the __strong or __weak case.
926 ///
John McCall460ce582015-10-22 18:38:17 +0000927 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there
928 /// are any weak ivars defined directly in the class. Meaningless unless
929 /// building a weak layout. Does not guarantee that the layout will
930 /// actually have any entries, because the ivar might be under-aligned.
Fariborz Jahanian1bf72882009-03-12 22:50:49 +0000931 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
John McCall3fd13f062015-10-21 18:06:47 +0000932 CharUnits beginOffset,
933 CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +0000934 bool forStrongLayout,
935 bool hasMRCWeakIvars);
936
937 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,
938 CharUnits beginOffset,
939 CharUnits endOffset) {
940 return BuildIvarLayout(OI, beginOffset, endOffset, true, false);
941 }
942
943 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,
944 CharUnits beginOffset,
945 CharUnits endOffset,
946 bool hasMRCWeakIvars) {
947 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);
948 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +0000949
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000950 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
Fariborz Jahanian2dd78192012-11-02 22:51:18 +0000951
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000952 void UpdateRunSkipBlockVars(bool IsByref,
953 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +0000954 CharUnits FieldOffset,
955 CharUnits FieldSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000956
957 void BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000958 CharUnits BytePos, bool &HasUnion,
959 bool ByrefLayout=false);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000960
961 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
962 const RecordDecl *RD,
963 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000964 CharUnits BytePos, bool &HasUnion,
965 bool ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +0000966
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000967 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
968
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000969 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
970
Fariborz Jahanian01dff422009-03-05 19:17:31 +0000971 /// GetIvarLayoutName - Returns a unique constant for the given
972 /// ivar layout bitmap.
973 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
974 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000975
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000976 /// EmitPropertyList - Emit the given property list. The return
977 /// value has type PropertyListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000978 llvm::Constant *EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000979 const Decl *Container,
Fariborz Jahanian066347e2009-01-28 22:18:42 +0000980 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +0000981 const ObjCCommonTypesHelper &ObjCTypes,
982 bool IsClassProperty);
Daniel Dunbar59e476b2009-08-03 17:06:42 +0000983
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000984 /// EmitProtocolMethodTypes - Generate the array of extended method type
985 /// strings. The return value has type Int8PtrPtrTy.
986 llvm::Constant *EmitProtocolMethodTypes(Twine Name,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +0000987 ArrayRef<llvm::Constant*> MethodTypes,
Bob Wilson5f4e3a72011-11-30 01:57:58 +0000988 const ObjCCommonTypesHelper &ObjCTypes);
989
Fariborz Jahanian751c1e72009-12-12 21:26:21 +0000990 /// PushProtocolProperties - Push protocol's property on the input stack.
Bill Wendlinga515b582012-02-09 22:16:49 +0000991 void PushProtocolProperties(
992 llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000993 SmallVectorImpl<llvm::Constant*> &Properties,
Bill Wendlinga515b582012-02-09 22:16:49 +0000994 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000995 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +0000996 const ObjCCommonTypesHelper &ObjCTypes,
997 bool IsClassProperty);
Fariborz Jahanian751c1e72009-12-12 21:26:21 +0000998
Fariborz Jahanian56b3b772009-01-29 19:24:30 +0000999 /// GetProtocolRef - Return a reference to the internal protocol
1000 /// description, creating an empty one if it has not been
1001 /// defined. The return value has type ProtocolPtrTy.
1002 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanian67726212009-03-08 20:18:37 +00001003
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001004 /// Return a reference to the given Class using runtime calls rather than
1005 /// by a symbol reference.
1006 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,
1007 const ObjCInterfaceDecl *ID,
1008 ObjCCommonTypesHelper &ObjCTypes);
1009
John McCall3fd13f062015-10-21 18:06:47 +00001010public:
Daniel Dunbar30c65362009-03-09 20:09:19 +00001011 /// CreateMetadataVar - Create a global variable with internal
1012 /// linkage for use by the Objective-C runtime.
1013 ///
1014 /// This is a convenience wrapper which not only creates the
1015 /// variable, but also sets the section and alignment and adds the
Chris Lattnerf56501c2009-07-17 23:57:13 +00001016 /// global to the "llvm.used" list.
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001017 ///
1018 /// \param Name - The variable name.
1019 /// \param Init - The variable initializer; this is also used to
1020 /// define the type of the variable.
Alp Toker541d5072014-06-07 23:30:53 +00001021 /// \param Section - The section the variable should go into, or empty.
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001022 /// \param Align - The alignment for the variable, or 0.
1023 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar4527d302009-04-14 17:42:51 +00001024 /// "llvm.used".
Alp Toker541d5072014-06-07 23:30:53 +00001025 llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init,
John McCall7f416cc2015-09-08 08:05:57 +00001026 StringRef Section, CharUnits Align,
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00001027 bool AddToUsed);
Daniel Dunbar30c65362009-03-09 20:09:19 +00001028
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00001029 llvm::GlobalVariable *CreateCStringLiteral(StringRef Name,
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00001030 ObjCLabelType LabelType,
1031 bool ForceNonFragileABI = false,
1032 bool NullTerminate = true);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00001033
John McCall3fd13f062015-10-21 18:06:47 +00001034protected:
John McCall9e8bb002011-05-14 03:10:52 +00001035 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1036 ReturnValueSlot Return,
1037 QualType ResultType,
1038 llvm::Value *Sel,
1039 llvm::Value *Arg0,
1040 QualType Arg0Ty,
1041 bool IsSuper,
1042 const CallArgList &CallArgs,
1043 const ObjCMethodDecl *OMD,
John McCall1e3157b2015-09-10 22:27:50 +00001044 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001045 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbarf5c18462009-04-20 06:54:31 +00001046
Daniel Dunbar5e639272010-04-25 20:39:01 +00001047 /// EmitImageInfo - Emit the image info marker used to encode some module
1048 /// level information.
1049 void EmitImageInfo();
1050
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001051public:
Owen Andersonae86c192009-07-13 04:10:07 +00001052 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
John McCalla729c622012-02-17 03:33:10 +00001053 CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001054
John McCall3fd13f062015-10-21 18:06:47 +00001055 bool isNonFragileABI() const {
1056 return ObjCABI == 2;
1057 }
1058
John McCall7f416cc2015-09-08 08:05:57 +00001059 ConstantAddress GenerateConstantString(const StringLiteral *SL) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001060
Craig Topper4f12f102014-03-12 06:41:41 +00001061 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Craig Topper8a13c412014-05-21 05:09:00 +00001062 const ObjCContainerDecl *CD=nullptr) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001063
1064 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001065
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001066 /// GetOrEmitProtocol - Get the protocol object for the given
1067 /// declaration, emitting it if necessary. The return value has type
1068 /// ProtocolPtrTy.
1069 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001070
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001071 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1072 /// object for the given declaration, emitting it if needed. These
1073 /// forward references will be filled in with empty bodies if no
1074 /// definition is seen. The return value has type ProtocolPtrTy.
1075 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Craig Topper4f12f102014-03-12 06:41:41 +00001076 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1077 const CGBlockInfo &blockInfo) override;
1078 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1079 const CGBlockInfo &blockInfo) override;
1080
1081 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1082 QualType T) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001083};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001084
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001085class CGObjCMac : public CGObjCCommonMac {
1086private:
1087 ObjCTypesHelper ObjCTypes;
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001088
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001089 /// EmitModuleInfo - Another marker encoding module level
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001090 /// information.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001091 void EmitModuleInfo();
1092
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001093 /// EmitModuleSymols - Emit module symbols, the list of defined
1094 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00001095 llvm::Constant *EmitModuleSymbols();
1096
Daniel Dunbar3ad53482008-08-11 21:35:06 +00001097 /// FinishModule - Write out global data structures at the end of
1098 /// processing a translation unit.
1099 void FinishModule();
Daniel Dunbarb036db82008-08-13 03:21:16 +00001100
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001101 /// EmitClassExtension - Generate the class extension structure used
1102 /// to store the weak ivar layout and properties. The return value
1103 /// has type ClassExtensionPtrTy.
John McCall3fd13f062015-10-21 18:06:47 +00001104 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,
John McCall460ce582015-10-22 18:38:17 +00001105 CharUnits instanceSize,
Manman Renad0e7912016-01-29 19:22:54 +00001106 bool hasMRCWeakIvars,
1107 bool isClassProperty);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001108
1109 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1110 /// for the given class.
John McCall882987f2013-02-28 19:01:20 +00001111 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001112 const ObjCInterfaceDecl *ID);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001113
John McCall882987f2013-02-28 19:01:20 +00001114 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00001115 IdentifierInfo *II);
Craig Topper4f12f102014-03-12 06:41:41 +00001116
1117 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1118
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001119 /// EmitSuperClassRef - Emits reference to class's main metadata class.
1120 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001121
1122 /// EmitIvarList - Emit the ivar list for the given
1123 /// implementation. If ForClass is true the list of class ivars
1124 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1125 /// interface ivars will be emitted. The return value has type
1126 /// IvarListPtrTy.
1127 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00001128 bool ForClass);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001129
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001130 /// EmitMetaClass - Emit a forward reference to the class structure
1131 /// for the metaclass of the given interface. The return value has
1132 /// type ClassPtrTy.
1133 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1134
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001135 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001136 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001137 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1138 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00001139 ArrayRef<llvm::Constant*> Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001140
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001141 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001142
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001143 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001144
1145 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001146 /// implementation. The return value has type MethodListPtrTy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001147 llvm::Constant *EmitMethodList(Twine Name, StringRef Section,
1148 ArrayRef<llvm::Constant *> Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001149
1150 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001151 /// method declarations.
Daniel Dunbarb036db82008-08-13 03:21:16 +00001152 /// - TypeName: The name for the type containing the methods.
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001153 /// - IsProtocol: True iff these methods are for a protocol.
1154 /// - ClassMethds: True iff these are class methods.
Daniel Dunbarb036db82008-08-13 03:21:16 +00001155 /// - Required: When true, only "required" methods are
1156 /// listed. Similarly, when false only "optional" methods are
1157 /// listed. For classes this should always be true.
1158 /// - begin, end: The method list to output.
1159 ///
1160 /// The return value has type MethodDescriptionListPtrTy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001161 llvm::Constant *EmitMethodDescList(Twine Name, StringRef Section,
1162 ArrayRef<llvm::Constant *> Methods);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001163
Daniel Dunbarc475d422008-10-29 22:36:39 +00001164 /// GetOrEmitProtocol - Get the protocol object for the given
1165 /// declaration, emitting it if necessary. The return value has type
1166 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001167 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001168
1169 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1170 /// object for the given declaration, emitting it if needed. These
1171 /// forward references will be filled in with empty bodies if no
1172 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001173 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbarc475d422008-10-29 22:36:39 +00001174
Daniel Dunbarb036db82008-08-13 03:21:16 +00001175 /// EmitProtocolExtension - Generate the protocol extension
1176 /// structure used to store optional instance and class methods, and
1177 /// protocol properties. The return value has type
1178 /// ProtocolExtensionPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00001179 llvm::Constant *
1180 EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00001181 ArrayRef<llvm::Constant*> OptInstanceMethods,
1182 ArrayRef<llvm::Constant*> OptClassMethods,
1183 ArrayRef<llvm::Constant*> MethodTypesExt);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001184
1185 /// EmitProtocolList - Generate the list of referenced
1186 /// protocols. The return value has type ProtocolListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001187 llvm::Constant *EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00001188 ObjCProtocolDecl::protocol_iterator begin,
1189 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarb036db82008-08-13 03:21:16 +00001190
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001191 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1192 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001193 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1194 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001195
1196public:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001197 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001198
Craig Topper4f12f102014-03-12 06:41:41 +00001199 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001200
Craig Topper4f12f102014-03-12 06:41:41 +00001201 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1202 ReturnValueSlot Return,
1203 QualType ResultType,
1204 Selector Sel, llvm::Value *Receiver,
1205 const CallArgList &CallArgs,
1206 const ObjCInterfaceDecl *Class,
1207 const ObjCMethodDecl *Method) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001208
Craig Topper4f12f102014-03-12 06:41:41 +00001209 CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001210 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001211 ReturnValueSlot Return, QualType ResultType,
1212 Selector Sel, const ObjCInterfaceDecl *Class,
1213 bool isCategoryImpl, llvm::Value *Receiver,
1214 bool IsClassMessage, const CallArgList &CallArgs,
1215 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001216
Craig Topper4f12f102014-03-12 06:41:41 +00001217 llvm::Value *GetClass(CodeGenFunction &CGF,
1218 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001219
John McCall7f416cc2015-09-08 08:05:57 +00001220 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
1221 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001222
1223 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1224 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001225 llvm::Value *GetSelector(CodeGenFunction &CGF,
1226 const ObjCMethodDecl *Method) override;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001227
Craig Topper4f12f102014-03-12 06:41:41 +00001228 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001229
Craig Topper4f12f102014-03-12 06:41:41 +00001230 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001231
Craig Topper4f12f102014-03-12 06:41:41 +00001232 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001233
Craig Topper4f12f102014-03-12 06:41:41 +00001234 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001235
Craig Topper4f12f102014-03-12 06:41:41 +00001236 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1237 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001238
Craig Topper4f12f102014-03-12 06:41:41 +00001239 llvm::Constant *GetPropertyGetFunction() override;
1240 llvm::Constant *GetPropertySetFunction() override;
1241 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1242 bool copy) override;
1243 llvm::Constant *GetGetStructFunction() override;
1244 llvm::Constant *GetSetStructFunction() override;
1245 llvm::Constant *GetCppAtomicObjectGetFunction() override;
1246 llvm::Constant *GetCppAtomicObjectSetFunction() override;
1247 llvm::Constant *EnumerationMutationFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001248
Craig Topper4f12f102014-03-12 06:41:41 +00001249 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1250 const ObjCAtTryStmt &S) override;
1251 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1252 const ObjCAtSynchronizedStmt &S) override;
John McCallbd309292010-07-06 01:34:17 +00001253 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
Craig Topper4f12f102014-03-12 06:41:41 +00001254 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1255 bool ClearInsertionPoint=true) override;
1256 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001257 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001258 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001259 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001260 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001261 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001262 bool threadlocal = false) override;
1263 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001264 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001265 llvm::Value *ivarOffset) override;
1266 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001267 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001268 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001269 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001270 llvm::Value *size) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001271
Craig Topper4f12f102014-03-12 06:41:41 +00001272 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1273 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1274 unsigned CVRQualifiers) override;
1275 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1276 const ObjCInterfaceDecl *Interface,
1277 const ObjCIvarDecl *Ivar) override;
1278
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001279 /// GetClassGlobal - Return the global variable for the Objective-C
1280 /// class of the given name.
Benjamin Kramer0772c422016-02-13 13:42:54 +00001281 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +00001282 bool Weak = false) override {
David Blaikie83d382b2011-09-23 05:06:16 +00001283 llvm_unreachable("CGObjCMac::GetClassGlobal");
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001284 }
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001285};
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001286
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001287class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001288private:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001289 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanian71394042009-01-23 23:53:38 +00001290 llvm::GlobalVariable* ObjCEmptyCacheVar;
1291 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001292
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001293 /// SuperClassReferences - uniqued super class references.
1294 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001295
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001296 /// MetaClassReferences - uniqued meta class references.
1297 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001298
1299 /// EHTypeReferences - uniqued class ehtype references.
1300 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001301
John McCall9e8bb002011-05-14 03:10:52 +00001302 /// VTableDispatchMethods - List of methods for which we generate
1303 /// vtable-based message dispatch.
1304 llvm::DenseSet<Selector> VTableDispatchMethods;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001305
Fariborz Jahanian67260552009-11-17 21:37:35 +00001306 /// DefinedMetaClasses - List of defined meta-classes.
1307 std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1308
John McCall9e8bb002011-05-14 03:10:52 +00001309 /// isVTableDispatchedSelector - Returns true if SEL is a
1310 /// vtable-based selector.
1311 bool isVTableDispatchedSelector(Selector Sel);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001312
Fariborz Jahanian71394042009-01-23 23:53:38 +00001313 /// FinishNonFragileABIModule - Write out global data structures at the end of
1314 /// processing a translation unit.
1315 void FinishNonFragileABIModule();
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001316
Daniel Dunbar19573e72009-05-15 21:48:48 +00001317 /// AddModuleClassList - Add the given list of class pointers to the
1318 /// module with the provided symbol and section names.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001319 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,
1320 StringRef SymbolName, StringRef SectionName);
Daniel Dunbar19573e72009-05-15 21:48:48 +00001321
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001322 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1323 unsigned InstanceStart,
1324 unsigned InstanceSize,
1325 const ObjCImplementationDecl *ID);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001326 llvm::GlobalVariable * BuildClassMetaData(const std::string &ClassName,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001327 llvm::Constant *IsAGV,
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00001328 llvm::Constant *SuperClassGV,
Fariborz Jahanian82208252009-01-31 00:59:10 +00001329 llvm::Constant *ClassRoGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00001330 bool HiddenVisibility,
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00001331 bool Weak);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001332
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00001333 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001334
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00001335 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001336
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00001337 /// EmitMethodList - Emit the method list for the given
1338 /// implementation. The return value has type MethodListnfABITy.
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001339 llvm::Constant *EmitMethodList(Twine Name, StringRef Section,
1340 ArrayRef<llvm::Constant *> Methods);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00001341 /// EmitIvarList - Emit the ivar list for the given
1342 /// implementation. If ForClass is true the list of class ivars
1343 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1344 /// interface ivars will be emitted. The return value has type
1345 /// IvarListnfABIPtrTy.
1346 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001347
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001348 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian3d3426f2009-01-28 01:36:42 +00001349 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00001350 unsigned long int offset);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001351
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001352 /// GetOrEmitProtocol - Get the protocol object for the given
1353 /// declaration, emitting it if necessary. The return value has type
1354 /// ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001355 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001356
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001357 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1358 /// object for the given declaration, emitting it if needed. These
1359 /// forward references will be filled in with empty bodies if no
1360 /// definition is seen. The return value has type ProtocolPtrTy.
Craig Topper4f12f102014-03-12 06:41:41 +00001361 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001362
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001363 /// EmitProtocolList - Generate the list of referenced
1364 /// protocols. The return value has type ProtocolListPtrTy.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001365 llvm::Constant *EmitProtocolList(Twine Name,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00001366 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00001367 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001368
John McCall9e8bb002011-05-14 03:10:52 +00001369 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1370 ReturnValueSlot Return,
1371 QualType ResultType,
1372 Selector Sel,
1373 llvm::Value *Receiver,
1374 QualType Arg0Ty,
1375 bool IsSuper,
1376 const CallArgList &CallArgs,
1377 const ObjCMethodDecl *Method);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00001378
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00001379 /// GetClassGlobal - Return the global variable for the Objective-C
1380 /// class of the given name.
Benjamin Kramer0772c422016-02-13 13:42:54 +00001381 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +00001382 bool Weak = false) override;
Rafael Espindola554256c2014-02-26 22:25:45 +00001383
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00001384 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001385 /// for the given class reference.
John McCall882987f2013-02-28 19:01:20 +00001386 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001387 const ObjCInterfaceDecl *ID);
John McCall31168b02011-06-15 23:02:42 +00001388
John McCall882987f2013-02-28 19:01:20 +00001389 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00001390 IdentifierInfo *II, bool Weak,
1391 const ObjCInterfaceDecl *ID);
Craig Topper4f12f102014-03-12 06:41:41 +00001392
1393 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001394
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00001395 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1396 /// for the given super class reference.
John McCall882987f2013-02-28 19:01:20 +00001397 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001398 const ObjCInterfaceDecl *ID);
1399
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001400 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1401 /// meta-data
John McCall882987f2013-02-28 19:01:20 +00001402 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00001403 const ObjCInterfaceDecl *ID, bool Weak);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00001404
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00001405 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1406 /// the given ivar.
1407 ///
Daniel Dunbara1060522009-04-19 00:31:15 +00001408 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001409 const ObjCInterfaceDecl *ID,
1410 const ObjCIvarDecl *Ivar);
1411
Fariborz Jahanian74b77222009-02-11 20:51:17 +00001412 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1413 /// for the given selector.
John McCall7f416cc2015-09-08 08:05:57 +00001414 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1415 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001416
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001417 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbarb1559a42009-03-01 04:46:24 +00001418 /// interface. The return value has type EHTypePtrTy.
John McCall2ca705e2010-07-24 00:37:23 +00001419 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001420 bool ForDefinition);
Daniel Dunbar15894b72009-04-07 05:48:37 +00001421
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001422 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001423
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00001424 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }
Daniel Dunbar15894b72009-04-07 05:48:37 +00001425
Daniel Dunbar961202372009-05-03 12:57:56 +00001426 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00001427 uint32_t &InstanceStart,
1428 uint32_t &InstanceSize);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001429
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001430 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001431 Selector GetNullarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001432 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1433 return CGM.getContext().Selectors.getSelector(0, &II);
1434 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001435
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001436 Selector GetUnarySelector(const char* name) const {
Fariborz Jahaniane4128642009-05-12 20:06:41 +00001437 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1438 return CGM.getContext().Selectors.getSelector(1, &II);
1439 }
Daniel Dunbar554fd792009-04-19 23:41:48 +00001440
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001441 /// ImplementationIsNonLazy - Check whether the given category or
1442 /// class implementation is "non-lazy".
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00001443 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00001444
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001445 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001446 const ObjCIvarDecl *IV) {
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001447 // Annotate the load as an invariant load iff inside an instance method
1448 // and ivar belongs to instance method's class and one of its super class.
1449 // This check is needed because the ivar offset is a lazily
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001450 // initialised value that may depend on objc_msgSend to perform a fixup on
1451 // the first message dispatch.
1452 //
1453 // An additional opportunity to mark the load as invariant arises when the
1454 // base of the ivar access is a parameter to an Objective C method.
1455 // However, because the parameters are not available in the current
1456 // interface, we cannot perform this check.
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001457 if (const ObjCMethodDecl *MD =
1458 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
Fariborz Jahanian7a583022014-03-04 22:57:32 +00001459 if (MD->isInstanceMethod())
Fariborz Jahaniandafffbe2014-03-04 18:34:52 +00001460 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1461 return IV->getContainingInterface()->isSuperClassOf(ID);
Saleem Abdulrasool5f25bc32013-02-17 04:03:34 +00001462 return false;
1463 }
1464
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001465public:
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00001466 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian71394042009-01-23 23:53:38 +00001467 // FIXME. All stubs for now!
Craig Topper4f12f102014-03-12 06:41:41 +00001468 llvm::Function *ModuleInitFunction() override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001469
Craig Topper4f12f102014-03-12 06:41:41 +00001470 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1471 ReturnValueSlot Return,
1472 QualType ResultType, Selector Sel,
1473 llvm::Value *Receiver,
1474 const CallArgList &CallArgs,
1475 const ObjCInterfaceDecl *Class,
1476 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001477
Craig Topper4f12f102014-03-12 06:41:41 +00001478 CodeGen::RValue
Fariborz Jahanian71394042009-01-23 23:53:38 +00001479 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001480 ReturnValueSlot Return, QualType ResultType,
1481 Selector Sel, const ObjCInterfaceDecl *Class,
1482 bool isCategoryImpl, llvm::Value *Receiver,
1483 bool IsClassMessage, const CallArgList &CallArgs,
1484 const ObjCMethodDecl *Method) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001485
Craig Topper4f12f102014-03-12 06:41:41 +00001486 llvm::Value *GetClass(CodeGenFunction &CGF,
1487 const ObjCInterfaceDecl *ID) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001488
John McCall7f416cc2015-09-08 08:05:57 +00001489 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override
1490 { return EmitSelector(CGF, Sel); }
1491 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override
1492 { return EmitSelectorAddr(CGF, Sel); }
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001493
1494 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1495 /// untyped one.
Craig Topper4f12f102014-03-12 06:41:41 +00001496 llvm::Value *GetSelector(CodeGenFunction &CGF,
1497 const ObjCMethodDecl *Method) override
John McCall882987f2013-02-28 19:01:20 +00001498 { return EmitSelector(CGF, Method->getSelector()); }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001499
Craig Topper4f12f102014-03-12 06:41:41 +00001500 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001501
Craig Topper4f12f102014-03-12 06:41:41 +00001502 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
David Chisnall92d436b2012-01-31 18:59:20 +00001503
Craig Topper4f12f102014-03-12 06:41:41 +00001504 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
David Chisnall92d436b2012-01-31 18:59:20 +00001505
Craig Topper4f12f102014-03-12 06:41:41 +00001506 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1507 const ObjCProtocolDecl *PD) override;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001508
Craig Topper4f12f102014-03-12 06:41:41 +00001509 llvm::Constant *GetEHType(QualType T) override;
John McCall2ca705e2010-07-24 00:37:23 +00001510
Craig Topper4f12f102014-03-12 06:41:41 +00001511 llvm::Constant *GetPropertyGetFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001512 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001513 }
Craig Topper4f12f102014-03-12 06:41:41 +00001514 llvm::Constant *GetPropertySetFunction() override {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001515 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00001516 }
Craig Topper4f12f102014-03-12 06:41:41 +00001517
1518 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1519 bool copy) override {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001520 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1521 }
Craig Topper4f12f102014-03-12 06:41:41 +00001522
1523 llvm::Constant *GetSetStructFunction() override {
David Chisnall168b80f2010-12-26 22:13:16 +00001524 return ObjCTypes.getCopyStructFn();
1525 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001526
Craig Topper4f12f102014-03-12 06:41:41 +00001527 llvm::Constant *GetGetStructFunction() override {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001528 return ObjCTypes.getCopyStructFn();
1529 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001530
Craig Topper4f12f102014-03-12 06:41:41 +00001531 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +00001532 return ObjCTypes.getCppAtomicObjectFunction();
1533 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001534
Craig Topper4f12f102014-03-12 06:41:41 +00001535 llvm::Constant *GetCppAtomicObjectGetFunction() override {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00001536 return ObjCTypes.getCppAtomicObjectFunction();
1537 }
Craig Topper4f12f102014-03-12 06:41:41 +00001538
1539 llvm::Constant *EnumerationMutationFunction() override {
Chris Lattnerce8754e2009-04-22 02:44:54 +00001540 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbard73ea8162009-02-16 18:48:45 +00001541 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001542
Craig Topper4f12f102014-03-12 06:41:41 +00001543 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1544 const ObjCAtTryStmt &S) override;
1545 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1546 const ObjCAtSynchronizedStmt &S) override;
1547 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1548 bool ClearInsertionPoint=true) override;
1549 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001550 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001551 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001552 llvm::Value *src, Address edst) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001553 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001554 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001555 bool threadlocal = false) override;
1556 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001557 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +00001558 llvm::Value *ivarOffset) override;
1559 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001560 llvm::Value *src, Address dest) override;
Craig Topper4f12f102014-03-12 06:41:41 +00001561 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001562 Address dest, Address src,
Craig Topper4f12f102014-03-12 06:41:41 +00001563 llvm::Value *size) override;
1564 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1565 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1566 unsigned CVRQualifiers) override;
1567 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1568 const ObjCInterfaceDecl *Interface,
1569 const ObjCIvarDecl *Ivar) override;
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001570};
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001571
1572/// A helper class for performing the null-initialization of a return
1573/// value.
1574struct NullReturnState {
1575 llvm::BasicBlock *NullBB;
Craig Topper8a13c412014-05-21 05:09:00 +00001576 NullReturnState() : NullBB(nullptr) {}
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001577
John McCall3d1e2c92013-02-12 05:53:35 +00001578 /// Perform a null-check of the given receiver.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001579 void init(CodeGenFunction &CGF, llvm::Value *receiver) {
John McCall3d1e2c92013-02-12 05:53:35 +00001580 // Make blocks for the null-receiver and call edges.
1581 NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1582 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001583
1584 // Check for a null receiver and, if there is one, jump to the
John McCall3d1e2c92013-02-12 05:53:35 +00001585 // null-receiver block. There's no point in trying to avoid it:
1586 // we're always going to put *something* there, because otherwise
1587 // we shouldn't have done this null-check in the first place.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001588 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1589 CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1590
1591 // Otherwise, start performing the call.
1592 CGF.EmitBlock(callBB);
1593 }
1594
John McCall3d1e2c92013-02-12 05:53:35 +00001595 /// Complete the null-return operation. It is valid to call this
1596 /// regardless of whether 'init' has been called.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001597 RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
1598 const CallArgList &CallArgs,
1599 const ObjCMethodDecl *Method) {
John McCall3d1e2c92013-02-12 05:53:35 +00001600 // If we never had to do a null-check, just use the raw result.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001601 if (!NullBB) return result;
John McCall3d1e2c92013-02-12 05:53:35 +00001602
1603 // The continuation block. This will be left null if we don't have an
1604 // IP, which can happen if the method we're calling is marked noreturn.
Craig Topper8a13c412014-05-21 05:09:00 +00001605 llvm::BasicBlock *contBB = nullptr;
1606
John McCall3d1e2c92013-02-12 05:53:35 +00001607 // Finish the call path.
1608 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1609 if (callBB) {
1610 contBB = CGF.createBasicBlock("msgSend.cont");
1611 CGF.Builder.CreateBr(contBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001612 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001613
John McCall3d1e2c92013-02-12 05:53:35 +00001614 // Okay, start emitting the null-receiver block.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001615 CGF.EmitBlock(NullBB);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001616
John McCall3d1e2c92013-02-12 05:53:35 +00001617 // Release any consumed arguments we've got.
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001618 if (Method) {
1619 CallArgList::const_iterator I = CallArgs.begin();
1620 for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1621 e = Method->param_end(); i != e; ++i, ++I) {
1622 const ParmVarDecl *ParamDecl = (*i);
1623 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1624 RValue RV = I->RV;
1625 assert(RV.isScalar() &&
1626 "NullReturnState::complete - arg not on object");
John McCallcdda29c2013-03-13 03:10:54 +00001627 CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001628 }
1629 }
1630 }
John McCall3d1e2c92013-02-12 05:53:35 +00001631
1632 // The phi code below assumes that we haven't needed any control flow yet.
1633 assert(CGF.Builder.GetInsertBlock() == NullBB);
1634
1635 // If we've got a void return, just jump to the continuation block.
1636 if (result.isScalar() && resultType->isVoidType()) {
1637 // No jumps required if the message-send was noreturn.
1638 if (contBB) CGF.EmitBlock(contBB);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001639 return result;
1640 }
1641
John McCall3d1e2c92013-02-12 05:53:35 +00001642 // If we've got a scalar return, build a phi.
1643 if (result.isScalar()) {
1644 // Derive the null-initialization value.
1645 llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
1646
1647 // If no join is necessary, just flow out.
1648 if (!contBB) return RValue::get(null);
1649
1650 // Otherwise, build a phi.
1651 CGF.EmitBlock(contBB);
1652 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1653 phi->addIncoming(result.getScalarVal(), callBB);
1654 phi->addIncoming(null, NullBB);
1655 return RValue::get(phi);
1656 }
1657
1658 // If we've got an aggregate return, null the buffer out.
1659 // FIXME: maybe we should be doing things differently for all the
1660 // cases where the ABI has us returning (1) non-agg values in
1661 // memory or (2) agg values in registers.
1662 if (result.isAggregate()) {
1663 assert(result.isAggregate() && "null init of non-aggregate result?");
John McCall7f416cc2015-09-08 08:05:57 +00001664 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);
John McCall3d1e2c92013-02-12 05:53:35 +00001665 if (contBB) CGF.EmitBlock(contBB);
1666 return result;
1667 }
1668
1669 // Complex types.
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001670 CGF.EmitBlock(contBB);
John McCall3d1e2c92013-02-12 05:53:35 +00001671 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1672
1673 // Find the scalar type and its zero value.
1674 llvm::Type *scalarTy = callResult.first->getType();
1675 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1676
1677 // Build phis for both coordinates.
1678 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1679 real->addIncoming(callResult.first, callBB);
1680 real->addIncoming(scalarZero, NullBB);
1681 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1682 imag->addIncoming(callResult.second, callBB);
1683 imag->addIncoming(scalarZero, NullBB);
1684 return RValue::getComplex(real, imag);
Fariborz Jahanian715fdd52012-01-29 20:27:13 +00001685 }
1686};
1687
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001688} // end anonymous namespace
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001689
1690/* *** Helper Functions *** */
1691
1692/// getConstantGEP() - Help routine to construct simple GEPs.
Owen Anderson170229f2009-07-14 23:10:40 +00001693static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
David Blaikiee3b172a2015-04-02 18:55:21 +00001694 llvm::GlobalVariable *C, unsigned idx0,
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001695 unsigned idx1) {
1696 llvm::Value *Idxs[] = {
Owen Anderson41a75022009-08-13 21:57:51 +00001697 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1698 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001699 };
David Blaikiee3b172a2015-04-02 18:55:21 +00001700 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001701}
1702
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001703/// hasObjCExceptionAttribute - Return true if this class or any super
1704/// class has the __objc_exception__ attribute.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001705static bool hasObjCExceptionAttribute(ASTContext &Context,
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001706 const ObjCInterfaceDecl *OID) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001707 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001708 return true;
1709 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Douglas Gregor78bd61f2009-06-18 16:11:24 +00001710 return hasObjCExceptionAttribute(Context, Super);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00001711 return false;
1712}
1713
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001714/* *** CGObjCMac Public Interface *** */
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001715
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001716CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
Mike Stump11289f42009-09-09 15:08:12 +00001717 ObjCTypes(cgm) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00001718 ObjCABI = 1;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001719 EmitImageInfo();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001720}
1721
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001722/// GetClass - Return a reference to the class for the given interface
1723/// decl.
John McCall882987f2013-02-28 19:01:20 +00001724llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00001725 const ObjCInterfaceDecl *ID) {
John McCall882987f2013-02-28 19:01:20 +00001726 return EmitClassRef(CGF, ID);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001727}
1728
1729/// GetSelector - Return the pointer to the unique'd string for this selector.
John McCall7f416cc2015-09-08 08:05:57 +00001730llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1731 return EmitSelector(CGF, Sel);
1732}
1733Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1734 return EmitSelectorAddr(CGF, Sel);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001735}
John McCall882987f2013-02-28 19:01:20 +00001736llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001737 *Method) {
John McCall882987f2013-02-28 19:01:20 +00001738 return EmitSelector(CGF, Method->getSelector());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001739}
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001740
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001741llvm::Constant *CGObjCMac::GetEHType(QualType T) {
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001742 if (T->isObjCIdType() ||
1743 T->isObjCQualifiedIdType()) {
1744 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001745 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00001746 }
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001747 if (T->isObjCClassType() ||
1748 T->isObjCQualifiedClassType()) {
1749 return CGM.GetAddrOfRTTIDescriptor(
Douglas Gregor97673472011-08-11 20:58:55 +00001750 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001751 }
1752 if (T->isObjCObjectPointerType())
1753 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
1754
John McCall2ca705e2010-07-24 00:37:23 +00001755 llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
John McCall2ca705e2010-07-24 00:37:23 +00001756}
1757
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001758/// Generate a constant CFString object.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001759/*
1760 struct __builtin_CFString {
1761 const int *isa; // point to __CFConstantStringClassReference
1762 int flags;
1763 const char *str;
1764 long length;
1765 };
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00001766*/
1767
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001768/// or Generate a constant NSString object.
1769/*
1770 struct __builtin_NSString {
1771 const int *isa; // point to __NSConstantStringClassReference
1772 const char *str;
1773 unsigned int length;
1774 };
1775*/
1776
John McCall7f416cc2015-09-08 08:05:57 +00001777ConstantAddress CGObjCCommonMac::GenerateConstantString(
David Chisnall481e3a82010-01-23 02:40:42 +00001778 const StringLiteral *SL) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001779 return (CGM.getLangOpts().NoConstantCFStrings == 0 ?
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001780 CGM.GetAddrOfConstantCFString(SL) :
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001781 CGM.GetAddrOfConstantString(SL));
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001782}
1783
Ted Kremeneke65b0862012-03-06 20:05:56 +00001784enum {
1785 kCFTaggedObjectID_Integer = (1 << 1) + 1
1786};
1787
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001788/// Generates a message send where the super is the receiver. This is
1789/// a message send to self with special delivery semantics indicating
1790/// which class's method should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001791CodeGen::RValue
1792CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001793 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001794 QualType ResultType,
1795 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001796 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001797 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001798 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001799 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001800 const CodeGen::CallArgList &CallArgs,
1801 const ObjCMethodDecl *Method) {
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001802 // Create and init a super structure; this is a (receiver, class)
1803 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00001804 Address ObjCSuper =
1805 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
1806 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001807 llvm::Value *ReceiverAsObject =
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001808 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001809 CGF.Builder.CreateStore(
1810 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00001811 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbarf6397fe2008-08-23 04:28:29 +00001812
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001813 // If this is a class message the metaclass is passed as the target.
1814 llvm::Value *Target;
1815 if (IsClassMessage) {
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001816 if (isCategoryImpl) {
1817 // Message sent to 'super' in a class method defined in a category
1818 // implementation requires an odd treatment.
1819 // If we are in a class method, we must retrieve the
1820 // _metaclass_ for the current class, pointed at by
1821 // the class's "isa" pointer. The following assumes that
1822 // isa" is the first ivar in a class (which it must be).
John McCall882987f2013-02-28 19:01:20 +00001823 Target = EmitClassRef(CGF, Class->getSuperClass());
David Blaikie1ed728c2015-04-05 22:45:47 +00001824 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001825 Target = CGF.Builder.CreateAlignedLoad(Target, CGF.getPointerAlign());
Mike Stump658fe022009-07-30 22:28:39 +00001826 } else {
David Blaikie1ed728c2015-04-05 22:45:47 +00001827 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
1828 llvm::Value *SuperPtr =
1829 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00001830 llvm::Value *Super =
1831 CGF.Builder.CreateAlignedLoad(SuperPtr, CGF.getPointerAlign());
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001832 Target = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001833 }
David Blaikie1ed728c2015-04-05 22:45:47 +00001834 } else if (isCategoryImpl)
John McCall882987f2013-02-28 19:01:20 +00001835 Target = EmitClassRef(CGF, Class->getSuperClass());
Fariborz Jahanianda2efb02009-11-14 02:18:31 +00001836 else {
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00001837 llvm::Value *ClassPtr = EmitSuperClassRef(Class);
David Blaikie1ed728c2015-04-05 22:45:47 +00001838 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
John McCall7f416cc2015-09-08 08:05:57 +00001839 Target = CGF.Builder.CreateAlignedLoad(ClassPtr, CGF.getPointerAlign());
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001840 }
Mike Stump18bb9282009-05-16 07:57:57 +00001841 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1842 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00001843 llvm::Type *ClassTy =
Daniel Dunbarc722b852008-08-30 03:02:31 +00001844 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbarc475d422008-10-29 22:36:39 +00001845 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
John McCall7f416cc2015-09-08 08:05:57 +00001846 CGF.Builder.CreateStore(Target,
1847 CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
John McCall9e8bb002011-05-14 03:10:52 +00001848 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00001849 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00001850 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00001851 true, CallArgs, Method, Class, ObjCTypes);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001852}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001853
1854/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +00001855CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001856 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001857 QualType ResultType,
1858 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001859 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001860 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001861 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001862 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00001863 return EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00001864 EmitSelector(CGF, Sel),
John McCall9e8bb002011-05-14 03:10:52 +00001865 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00001866 false, CallArgs, Method, Class, ObjCTypes);
1867}
1868
1869static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
1870 do {
1871 if (ID->isWeakImported())
1872 return true;
1873 } while ((ID = ID->getSuperClass()));
1874
1875 return false;
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00001876}
1877
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001878CodeGen::RValue
John McCall9e8bb002011-05-14 03:10:52 +00001879CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1880 ReturnValueSlot Return,
1881 QualType ResultType,
1882 llvm::Value *Sel,
1883 llvm::Value *Arg0,
1884 QualType Arg0Ty,
1885 bool IsSuper,
1886 const CallArgList &CallArgs,
1887 const ObjCMethodDecl *Method,
John McCall1e3157b2015-09-10 22:27:50 +00001888 const ObjCInterfaceDecl *ClassReceiver,
John McCall9e8bb002011-05-14 03:10:52 +00001889 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc722b852008-08-30 03:02:31 +00001890 CallArgList ActualArgs;
Fariborz Jahanian969bc682009-04-24 21:07:43 +00001891 if (!IsSuper)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001892 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001893 ActualArgs.add(RValue::get(Arg0), Arg0Ty);
1894 ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001895 ActualArgs.addFrom(CallArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001896
John McCalla729c622012-02-17 03:33:10 +00001897 // If we're calling a method, use the formal signature.
1898 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001899
Anders Carlsson280e61f12010-06-21 20:59:55 +00001900 if (Method)
Alp Toker314cc812014-01-25 16:55:45 +00001901 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
1902 CGM.getContext().getCanonicalType(ResultType) &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00001903 "Result type mismatch!");
1904
John McCall1e3157b2015-09-10 22:27:50 +00001905 bool ReceiverCanBeNull = true;
1906
1907 // Super dispatch assumes that self is non-null; even the messenger
1908 // doesn't have a null check internally.
1909 if (IsSuper) {
1910 ReceiverCanBeNull = false;
1911
1912 // If this is a direct dispatch of a class method, check whether the class,
1913 // or anything in its hierarchy, was weak-linked.
1914 } else if (ClassReceiver && Method && Method->isClassMethod()) {
1915 ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver);
1916
1917 // If we're emitting a method, and self is const (meaning just ARC, for now),
1918 // and the receiver is a load of self, then self is a valid object.
1919 } else if (auto CurMethod =
1920 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
1921 auto Self = CurMethod->getSelfDecl();
1922 if (Self->getType().isConstQualified()) {
1923 if (auto LI = dyn_cast<llvm::LoadInst>(Arg0->stripPointerCasts())) {
1924 llvm::Value *SelfAddr = CGF.GetAddrOfLocalVar(Self).getPointer();
1925 if (SelfAddr == LI->getPointerOperand()) {
1926 ReceiverCanBeNull = false;
1927 }
1928 }
1929 }
1930 }
1931
John McCall5880fb82011-05-14 21:12:11 +00001932 NullReturnState nullReturn;
1933
Craig Topper8a13c412014-05-21 05:09:00 +00001934 llvm::Constant *Fn = nullptr;
Tim Northovere77cc392014-03-29 13:28:05 +00001935 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall1e3157b2015-09-10 22:27:50 +00001936 if (ReceiverCanBeNull) nullReturn.init(CGF, Arg0);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00001937 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001938 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001939 } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1940 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
1941 : ObjCTypes.getSendFpretFn(IsSuper);
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001942 } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
1943 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
1944 : ObjCTypes.getSendFp2retFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00001945 } else {
Tim Northovere77cc392014-03-29 13:28:05 +00001946 // arm64 uses objc_msgSend for stret methods and yet null receiver check
1947 // must be made for it.
Ahmed Bougachaa3df87b2015-10-02 22:41:59 +00001948 if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
Tim Northovere77cc392014-03-29 13:28:05 +00001949 nullReturn.init(CGF, Arg0);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00001950 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00001951 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar3c683f5b2008-10-17 03:24:53 +00001952 }
John McCall1e3157b2015-09-10 22:27:50 +00001953
1954 // Emit a null-check if there's a consumed argument other than the receiver.
1955 bool RequiresNullCheck = false;
1956 if (ReceiverCanBeNull && CGM.getLangOpts().ObjCAutoRefCount && Method) {
David Majnemer59f77922016-06-24 04:05:48 +00001957 for (const auto *ParamDecl : Method->parameters()) {
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001958 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1959 if (!nullReturn.NullBB)
1960 nullReturn.init(CGF, Arg0);
John McCall1e3157b2015-09-10 22:27:50 +00001961 RequiresNullCheck = true;
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001962 break;
1963 }
1964 }
John McCall1e3157b2015-09-10 22:27:50 +00001965 }
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001966
John McCall1e3157b2015-09-10 22:27:50 +00001967 llvm::Instruction *CallSite;
John McCalla729c622012-02-17 03:33:10 +00001968 Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
John McCall1e3157b2015-09-10 22:27:50 +00001969 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00001970 CGCalleeInfo(), &CallSite);
John McCall1e3157b2015-09-10 22:27:50 +00001971
1972 // Mark the call as noreturn if the method is marked noreturn and the
1973 // receiver cannot be null.
1974 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {
1975 llvm::CallSite(CallSite).setDoesNotReturn();
1976 }
1977
Fariborz Jahanianf2bda692012-01-30 21:40:37 +00001978 return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
John McCall1e3157b2015-09-10 22:27:50 +00001979 RequiresNullCheck ? Method : nullptr);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00001980}
1981
John McCall3fd13f062015-10-21 18:06:47 +00001982static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT,
1983 bool pointee = false) {
1984 // Note that GC qualification applies recursively to C pointer types
1985 // that aren't otherwise decorated. This is weird, but it's probably
1986 // an intentional workaround to the unreliable placement of GC qualifiers.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001987 if (FQT.isObjCGCStrong())
1988 return Qualifiers::Strong;
John McCall3fd13f062015-10-21 18:06:47 +00001989
1990 if (FQT.isObjCGCWeak())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00001991 return Qualifiers::Weak;
John McCall3fd13f062015-10-21 18:06:47 +00001992
1993 if (auto ownership = FQT.getObjCLifetime()) {
1994 // Ownership does not apply recursively to C pointer types.
1995 if (pointee) return Qualifiers::GCNone;
1996 switch (ownership) {
1997 case Qualifiers::OCL_Weak: return Qualifiers::Weak;
1998 case Qualifiers::OCL_Strong: return Qualifiers::Strong;
1999 case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone;
2000 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");
2001 case Qualifiers::OCL_None: llvm_unreachable("known nonzero");
2002 }
2003 llvm_unreachable("bad objc ownership");
2004 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002005
John McCall3fd13f062015-10-21 18:06:47 +00002006 // Treat unqualified retainable pointers as strong.
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002007 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2008 return Qualifiers::Strong;
2009
John McCall3fd13f062015-10-21 18:06:47 +00002010 // Walk into C pointer types, but only in GC.
2011 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {
2012 if (const PointerType *PT = FQT->getAs<PointerType>())
2013 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);
2014 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002015
2016 return Qualifiers::GCNone;
2017}
2018
John McCall3fd13f062015-10-21 18:06:47 +00002019namespace {
2020 struct IvarInfo {
2021 CharUnits Offset;
2022 uint64_t SizeInWords;
2023 IvarInfo(CharUnits offset, uint64_t sizeInWords)
2024 : Offset(offset), SizeInWords(sizeInWords) {}
2025
2026 // Allow sorting based on byte pos.
2027 bool operator<(const IvarInfo &other) const {
2028 return Offset < other.Offset;
2029 }
2030 };
2031
2032 /// A helper class for building GC layout strings.
2033 class IvarLayoutBuilder {
2034 CodeGenModule &CGM;
2035
2036 /// The start of the layout. Offsets will be relative to this value,
2037 /// and entries less than this value will be silently discarded.
2038 CharUnits InstanceBegin;
2039
2040 /// The end of the layout. Offsets will never exceed this value.
2041 CharUnits InstanceEnd;
2042
2043 /// Whether we're generating the strong layout or the weak layout.
2044 bool ForStrongLayout;
2045
2046 /// Whether the offsets in IvarsInfo might be out-of-order.
2047 bool IsDisordered = false;
2048
2049 llvm::SmallVector<IvarInfo, 8> IvarsInfo;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002050
John McCall3fd13f062015-10-21 18:06:47 +00002051 public:
2052 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,
2053 CharUnits instanceEnd, bool forStrongLayout)
2054 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),
2055 ForStrongLayout(forStrongLayout) {
2056 }
2057
2058 void visitRecord(const RecordType *RT, CharUnits offset);
2059
2060 template <class Iterator, class GetOffsetFn>
2061 void visitAggregate(Iterator begin, Iterator end,
2062 CharUnits aggrOffset,
2063 const GetOffsetFn &getOffset);
2064
2065 void visitField(const FieldDecl *field, CharUnits offset);
2066
2067 /// Add the layout of a block implementation.
2068 void visitBlock(const CGBlockInfo &blockInfo);
2069
2070 /// Is there any information for an interesting bitmap?
2071 bool hasBitmapData() const { return !IvarsInfo.empty(); }
2072
2073 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,
2074 llvm::SmallVectorImpl<unsigned char> &buffer);
2075
2076 static void dump(ArrayRef<unsigned char> buffer) {
2077 const unsigned char *s = buffer.data();
2078 for (unsigned i = 0, e = buffer.size(); i < e; i++)
2079 if (!(s[i] & 0xf0))
2080 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2081 else
2082 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
2083 printf("\n");
2084 }
2085 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002086} // end anonymous namespace
John McCall3fd13f062015-10-21 18:06:47 +00002087
John McCall351762c2011-02-07 10:33:21 +00002088llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
2089 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002090
Chris Lattnerece04092012-02-07 00:39:47 +00002091 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
John McCall460ce582015-10-22 18:38:17 +00002092 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
John McCall351762c2011-02-07 10:33:21 +00002093 return nullPtr;
2094
John McCall3fd13f062015-10-21 18:06:47 +00002095 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,
2096 /*for strong layout*/ true);
2097
2098 builder.visitBlock(blockInfo);
2099
2100 if (!builder.hasBitmapData())
2101 return nullPtr;
2102
2103 llvm::SmallVector<unsigned char, 32> buffer;
2104 llvm::Constant *C = builder.buildBitmap(*this, buffer);
John McCallf5ea0722015-10-29 23:36:14 +00002105 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
John McCall3fd13f062015-10-21 18:06:47 +00002106 printf("\n block variable layout for block: ");
2107 builder.dump(buffer);
2108 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002109
John McCall3fd13f062015-10-21 18:06:47 +00002110 return C;
2111}
2112
2113void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {
Fariborz Jahaniancfddabf2010-09-09 00:21:45 +00002114 // __isa is the first field in block descriptor and must assume by runtime's
2115 // convention that it is GC'able.
John McCall3fd13f062015-10-21 18:06:47 +00002116 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));
John McCall351762c2011-02-07 10:33:21 +00002117
2118 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2119
John McCall351762c2011-02-07 10:33:21 +00002120 // Ignore the optional 'this' capture: C++ objects are not assumed
2121 // to be GC'ed.
2122
John McCall3fd13f062015-10-21 18:06:47 +00002123 CharUnits lastFieldOffset;
2124
John McCall351762c2011-02-07 10:33:21 +00002125 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002126 for (const auto &CI : blockDecl->captures()) {
2127 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00002128 QualType type = variable->getType();
2129
2130 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2131
2132 // Ignore constant captures.
2133 if (capture.isConstant()) continue;
2134
John McCall3fd13f062015-10-21 18:06:47 +00002135 CharUnits fieldOffset = capture.getOffset();
2136
2137 // Block fields are not necessarily ordered; if we detect that we're
2138 // adding them out-of-order, make sure we sort later.
2139 if (fieldOffset < lastFieldOffset)
2140 IsDisordered = true;
2141 lastFieldOffset = fieldOffset;
John McCall351762c2011-02-07 10:33:21 +00002142
2143 // __block variables are passed by their descriptor address.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002144 if (CI.isByRef()) {
John McCall3fd13f062015-10-21 18:06:47 +00002145 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
Fariborz Jahanian933c6722010-09-11 01:27:29 +00002146 continue;
John McCall351762c2011-02-07 10:33:21 +00002147 }
2148
2149 assert(!type->isArrayType() && "array variable should not be caught");
2150 if (const RecordType *record = type->getAs<RecordType>()) {
John McCall3fd13f062015-10-21 18:06:47 +00002151 visitRecord(record, fieldOffset);
Fariborz Jahanian903aba32010-08-05 21:00:25 +00002152 continue;
2153 }
Fariborz Jahanianf95e3582010-08-06 16:28:55 +00002154
John McCall351762c2011-02-07 10:33:21 +00002155 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
John McCall351762c2011-02-07 10:33:21 +00002156
John McCall3fd13f062015-10-21 18:06:47 +00002157 if (GCAttr == Qualifiers::Strong) {
2158 assert(CGM.getContext().getTypeSize(type)
2159 == CGM.getTarget().getPointerWidth(0));
2160 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));
2161 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00002162 }
Fariborz Jahanianc05349e2010-08-04 16:57:49 +00002163}
2164
Fariborz Jahanian2c96d302012-11-04 18:19:40 +00002165/// getBlockCaptureLifetime - This routine returns life time of the captured
2166/// block variable for the purpose of block layout meta-data generation. FQT is
2167/// the type of the variable captured in the block.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002168Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2169 bool ByrefLayout) {
John McCall460ce582015-10-22 18:38:17 +00002170 // If it has an ownership qualifier, we're done.
2171 if (auto lifetime = FQT.getObjCLifetime())
2172 return lifetime;
2173
2174 // If it doesn't, and this is ARC, it has no ownership.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002175 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00002176 return Qualifiers::OCL_None;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002177
John McCall460ce582015-10-22 18:38:17 +00002178 // In MRC, retainable pointers are owned by non-__block variables.
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002179 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002180 return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
Fariborz Jahanian2dd78192012-11-02 22:51:18 +00002181
2182 return Qualifiers::OCL_None;
2183}
2184
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002185void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2186 Qualifiers::ObjCLifetime LifeTime,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002187 CharUnits FieldOffset,
2188 CharUnits FieldSize) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002189 // __block variables are passed by their descriptor address.
2190 if (IsByref)
2191 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002192 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002193 else if (LifeTime == Qualifiers::OCL_Strong)
2194 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002195 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002196 else if (LifeTime == Qualifiers::OCL_Weak)
2197 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002198 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002199 else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2200 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002201 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002202 else
2203 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2204 FieldOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002205 FieldSize));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002206}
2207
2208void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2209 const RecordDecl *RD,
2210 ArrayRef<const FieldDecl*> RecFields,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002211 CharUnits BytePos, bool &HasUnion,
2212 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002213 bool IsUnion = (RD && RD->isUnion());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002214 CharUnits MaxUnionSize = CharUnits::Zero();
Craig Topper8a13c412014-05-21 05:09:00 +00002215 const FieldDecl *MaxField = nullptr;
2216 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002217 CharUnits MaxFieldOffset = CharUnits::Zero();
2218 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002219
2220 if (RecFields.empty())
2221 return;
John McCallc8e01702013-04-16 22:48:15 +00002222 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002223
2224 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2225 const FieldDecl *Field = RecFields[i];
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002226 // Note that 'i' here is actually the field index inside RD of Field,
2227 // although this dependency is hidden.
2228 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002229 CharUnits FieldOffset =
2230 CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002231
2232 // Skip over unnamed or bitfields
2233 if (!Field->getIdentifier() || Field->isBitField()) {
2234 LastFieldBitfieldOrUnnamed = Field;
2235 LastBitfieldOrUnnamedOffset = FieldOffset;
2236 continue;
2237 }
Craig Topper8a13c412014-05-21 05:09:00 +00002238
2239 LastFieldBitfieldOrUnnamed = nullptr;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002240 QualType FQT = Field->getType();
2241 if (FQT->isRecordType() || FQT->isUnionType()) {
2242 if (FQT->isUnionType())
2243 HasUnion = true;
2244
2245 BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
2246 BytePos + FieldOffset, HasUnion);
2247 continue;
2248 }
2249
2250 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2251 const ConstantArrayType *CArray =
2252 dyn_cast_or_null<ConstantArrayType>(Array);
2253 uint64_t ElCount = CArray->getSize().getZExtValue();
2254 assert(CArray && "only array with known element size is supported");
2255 FQT = CArray->getElementType();
2256 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2257 const ConstantArrayType *CArray =
2258 dyn_cast_or_null<ConstantArrayType>(Array);
2259 ElCount *= CArray->getSize().getZExtValue();
2260 FQT = CArray->getElementType();
2261 }
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002262 if (FQT->isRecordType() && ElCount) {
2263 int OldIndex = RunSkipBlockVars.size() - 1;
2264 const RecordType *RT = FQT->getAs<RecordType>();
2265 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
2266 HasUnion);
2267
2268 // Replicate layout information for each array element. Note that
2269 // one element is already done.
2270 uint64_t ElIx = 1;
2271 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002272 CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002273 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2274 RunSkipBlockVars.push_back(
2275 RUN_SKIP(RunSkipBlockVars[i].opcode,
2276 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2277 RunSkipBlockVars[i].block_var_size));
2278 }
2279 continue;
2280 }
2281 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002282 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002283 if (IsUnion) {
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002284 CharUnits UnionIvarSize = FieldSize;
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002285 if (UnionIvarSize > MaxUnionSize) {
2286 MaxUnionSize = UnionIvarSize;
2287 MaxField = Field;
2288 MaxFieldOffset = FieldOffset;
2289 }
2290 } else {
2291 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002292 getBlockCaptureLifetime(FQT, ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002293 BytePos + FieldOffset,
2294 FieldSize);
2295 }
2296 }
2297
2298 if (LastFieldBitfieldOrUnnamed) {
2299 if (LastFieldBitfieldOrUnnamed->isBitField()) {
2300 // Last field was a bitfield. Must update the info.
2301 uint64_t BitFieldSize
2302 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002303 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
Eli Friedman8cbca202012-11-06 22:15:52 +00002304 ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002305 CharUnits Size = CharUnits::fromQuantity(UnsSize);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002306 Size += LastBitfieldOrUnnamedOffset;
2307 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002308 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2309 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002310 BytePos + LastBitfieldOrUnnamedOffset,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002311 Size);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002312 } else {
2313 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2314 // Last field was unnamed. Must update skip info.
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002315 CharUnits FieldSize
2316 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002317 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002318 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2319 ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002320 BytePos + LastBitfieldOrUnnamedOffset,
2321 FieldSize);
2322 }
2323 }
2324
2325 if (MaxField)
2326 UpdateRunSkipBlockVars(false,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002327 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002328 BytePos + MaxFieldOffset,
2329 MaxUnionSize);
2330}
2331
2332void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002333 CharUnits BytePos,
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002334 bool &HasUnion,
2335 bool ByrefLayout) {
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002336 const RecordDecl *RD = RT->getDecl();
Aaron Ballman62e47c42014-03-10 13:43:55 +00002337 SmallVector<const FieldDecl*, 16> Fields(RD->fields());
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002338 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2339 const llvm::StructLayout *RecLayout =
2340 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
2341
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002342 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002343}
2344
Fariborz Jahanian23290b02012-11-01 18:32:55 +00002345/// InlineLayoutInstruction - This routine produce an inline instruction for the
2346/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2347/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2348/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2349/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2350/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2351/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2352/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2353/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2354uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2355 SmallVectorImpl<unsigned char> &Layout) {
2356 uint64_t Result = 0;
2357 if (Layout.size() <= 3) {
2358 unsigned size = Layout.size();
2359 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2360 unsigned char inst;
2361 enum BLOCK_LAYOUT_OPCODE opcode ;
2362 switch (size) {
2363 case 3:
2364 inst = Layout[0];
2365 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2366 if (opcode == BLOCK_LAYOUT_STRONG)
2367 strong_word_count = (inst & 0xF)+1;
2368 else
2369 return 0;
2370 inst = Layout[1];
2371 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2372 if (opcode == BLOCK_LAYOUT_BYREF)
2373 byref_word_count = (inst & 0xF)+1;
2374 else
2375 return 0;
2376 inst = Layout[2];
2377 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2378 if (opcode == BLOCK_LAYOUT_WEAK)
2379 weak_word_count = (inst & 0xF)+1;
2380 else
2381 return 0;
2382 break;
2383
2384 case 2:
2385 inst = Layout[0];
2386 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2387 if (opcode == BLOCK_LAYOUT_STRONG) {
2388 strong_word_count = (inst & 0xF)+1;
2389 inst = Layout[1];
2390 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2391 if (opcode == BLOCK_LAYOUT_BYREF)
2392 byref_word_count = (inst & 0xF)+1;
2393 else if (opcode == BLOCK_LAYOUT_WEAK)
2394 weak_word_count = (inst & 0xF)+1;
2395 else
2396 return 0;
2397 }
2398 else if (opcode == BLOCK_LAYOUT_BYREF) {
2399 byref_word_count = (inst & 0xF)+1;
2400 inst = Layout[1];
2401 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2402 if (opcode == BLOCK_LAYOUT_WEAK)
2403 weak_word_count = (inst & 0xF)+1;
2404 else
2405 return 0;
2406 }
2407 else
2408 return 0;
2409 break;
2410
2411 case 1:
2412 inst = Layout[0];
2413 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2414 if (opcode == BLOCK_LAYOUT_STRONG)
2415 strong_word_count = (inst & 0xF)+1;
2416 else if (opcode == BLOCK_LAYOUT_BYREF)
2417 byref_word_count = (inst & 0xF)+1;
2418 else if (opcode == BLOCK_LAYOUT_WEAK)
2419 weak_word_count = (inst & 0xF)+1;
2420 else
2421 return 0;
2422 break;
2423
2424 default:
2425 return 0;
2426 }
2427
2428 // Cannot inline when any of the word counts is 15. Because this is one less
2429 // than the actual work count (so 15 means 16 actual word counts),
2430 // and we can only display 0 thru 15 word counts.
2431 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2432 return 0;
2433
2434 unsigned count =
2435 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
2436
2437 if (size == count) {
2438 if (strong_word_count)
2439 Result = strong_word_count;
2440 Result <<= 4;
2441 if (byref_word_count)
2442 Result += byref_word_count;
2443 Result <<= 4;
2444 if (weak_word_count)
2445 Result += weak_word_count;
2446 }
2447 }
2448 return Result;
2449}
2450
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002451llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2452 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2453 if (RunSkipBlockVars.empty())
2454 return nullPtr;
John McCallc8e01702013-04-16 22:48:15 +00002455 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2456 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002457 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2458
2459 // Sort on byte position; captures might not be allocated in order,
2460 // and unions can do funny things.
2461 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2462 SmallVector<unsigned char, 16> Layout;
2463
2464 unsigned size = RunSkipBlockVars.size();
2465 for (unsigned i = 0; i < size; i++) {
2466 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2467 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2468 CharUnits end_byte_pos = start_byte_pos;
2469 unsigned j = i+1;
2470 while (j < size) {
2471 if (opcode == RunSkipBlockVars[j].opcode) {
2472 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2473 i++;
2474 }
2475 else
2476 break;
2477 }
2478 CharUnits size_in_bytes =
2479 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2480 if (j < size) {
2481 CharUnits gap =
2482 RunSkipBlockVars[j].block_var_bytepos -
2483 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2484 size_in_bytes += gap;
2485 }
2486 CharUnits residue_in_bytes = CharUnits::Zero();
2487 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2488 residue_in_bytes = size_in_bytes % WordSizeInBytes;
2489 size_in_bytes -= residue_in_bytes;
2490 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2491 }
2492
2493 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2494 while (size_in_words >= 16) {
2495 // Note that value in imm. is one less that the actual
2496 // value. So, 0xf means 16 words follow!
2497 unsigned char inst = (opcode << 4) | 0xf;
2498 Layout.push_back(inst);
2499 size_in_words -= 16;
2500 }
2501 if (size_in_words > 0) {
2502 // Note that value in imm. is one less that the actual
2503 // value. So, we subtract 1 away!
2504 unsigned char inst = (opcode << 4) | (size_in_words-1);
2505 Layout.push_back(inst);
2506 }
2507 if (residue_in_bytes > CharUnits::Zero()) {
2508 unsigned char inst =
2509 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2510 Layout.push_back(inst);
2511 }
2512 }
2513
John McCall7f416cc2015-09-08 08:05:57 +00002514 while (!Layout.empty()) {
2515 unsigned char inst = Layout.back();
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002516 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2517 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2518 Layout.pop_back();
2519 else
2520 break;
2521 }
2522
2523 uint64_t Result = InlineLayoutInstruction(Layout);
2524 if (Result != 0) {
2525 // Block variable layout instruction has been inlined.
2526 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2527 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002528 printf("\n Inline BYREF variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002529 else
John McCall7f416cc2015-09-08 08:05:57 +00002530 printf("\n Inline block variable layout: ");
2531 printf("0x0%" PRIx64 "", Result);
2532 if (auto numStrong = (Result & 0xF00) >> 8)
2533 printf(", BL_STRONG:%d", (int) numStrong);
2534 if (auto numByref = (Result & 0x0F0) >> 4)
2535 printf(", BL_BYREF:%d", (int) numByref);
2536 if (auto numWeak = (Result & 0x00F) >> 0)
2537 printf(", BL_WEAK:%d", (int) numWeak);
2538 printf(", BL_OPERATOR:0\n");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002539 }
Vedant Kumar3ed0df02015-12-21 19:43:25 +00002540 return llvm::ConstantInt::get(CGM.IntPtrTy, Result);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002541 }
2542
2543 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2544 Layout.push_back(inst);
2545 std::string BitMap;
2546 for (unsigned i = 0, e = Layout.size(); i != e; i++)
2547 BitMap += Layout[i];
2548
2549 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2550 if (ComputeByrefLayout)
John McCall7f416cc2015-09-08 08:05:57 +00002551 printf("\n Byref variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002552 else
John McCall7f416cc2015-09-08 08:05:57 +00002553 printf("\n Block variable layout: ");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002554 for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2555 unsigned char inst = BitMap[i];
2556 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2557 unsigned delta = 1;
2558 switch (opcode) {
2559 case BLOCK_LAYOUT_OPERATOR:
2560 printf("BL_OPERATOR:");
2561 delta = 0;
2562 break;
2563 case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2564 printf("BL_NON_OBJECT_BYTES:");
2565 break;
2566 case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2567 printf("BL_NON_OBJECT_WORD:");
2568 break;
2569 case BLOCK_LAYOUT_STRONG:
2570 printf("BL_STRONG:");
2571 break;
2572 case BLOCK_LAYOUT_BYREF:
2573 printf("BL_BYREF:");
2574 break;
2575 case BLOCK_LAYOUT_WEAK:
2576 printf("BL_WEAK:");
2577 break;
2578 case BLOCK_LAYOUT_UNRETAINED:
2579 printf("BL_UNRETAINED:");
2580 break;
2581 }
2582 // Actual value of word count is one more that what is in the imm.
2583 // field of the instruction
2584 printf("%d", (inst & 0xf) + delta);
2585 if (i < e-1)
2586 printf(", ");
2587 else
2588 printf("\n");
2589 }
2590 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002591
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00002592 auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName,
2593 /*ForceNonFragileABI=*/true,
2594 /*NullTerminate=*/false);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002595 return getConstantGEP(VMContext, Entry, 0, 0);
2596}
2597
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002598llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2599 const CGBlockInfo &blockInfo) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002600 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2601
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002602 RunSkipBlockVars.clear();
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002603 bool hasUnion = false;
2604
John McCallc8e01702013-04-16 22:48:15 +00002605 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2606 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002607 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2608
2609 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2610
2611 // Calculate the basic layout of the block structure.
2612 const llvm::StructLayout *layout =
2613 CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
2614
2615 // Ignore the optional 'this' capture: C++ objects are not assumed
2616 // to be GC'ed.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +00002617 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2618 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2619 blockInfo.BlockHeaderForcedGapOffset,
2620 blockInfo.BlockHeaderForcedGapSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002621 // Walk the captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +00002622 for (const auto &CI : blockDecl->captures()) {
2623 const VarDecl *variable = CI.getVariable();
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002624 QualType type = variable->getType();
2625
2626 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2627
2628 // Ignore constant captures.
2629 if (capture.isConstant()) continue;
2630
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002631 CharUnits fieldOffset =
2632 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002633
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002634 assert(!type->isArrayType() && "array variable should not be caught");
Aaron Ballman9371dd22014-03-14 18:34:04 +00002635 if (!CI.isByRef())
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002636 if (const RecordType *record = type->getAs<RecordType>()) {
2637 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2638 continue;
2639 }
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002640 CharUnits fieldSize;
Aaron Ballman9371dd22014-03-14 18:34:04 +00002641 if (CI.isByRef())
Fariborz Jahanian7778d612012-11-07 20:00:32 +00002642 fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2643 else
2644 fieldSize = CGM.getContext().getTypeSizeInChars(type);
Aaron Ballman9371dd22014-03-14 18:34:04 +00002645 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
Fariborz Jahanian39319c42012-10-30 20:05:29 +00002646 fieldOffset, fieldSize);
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002647 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002648 return getBitmapBlockLayout(false);
2649}
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002650
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002651llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2652 QualType T) {
2653 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2654 assert(!T->isArrayType() && "__block array variable should not be caught");
2655 CharUnits fieldOffset;
2656 RunSkipBlockVars.clear();
2657 bool hasUnion = false;
2658 if (const RecordType *record = T->getAs<RecordType>()) {
2659 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2660 llvm::Constant *Result = getBitmapBlockLayout(true);
Vedant Kumar2f5bb1152015-12-21 20:21:15 +00002661 if (isa<llvm::ConstantInt>(Result))
2662 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002663 return Result;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002664 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002665 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2666 return nullPtr;
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +00002667}
2668
John McCall882987f2013-02-28 19:01:20 +00002669llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002670 const ObjCProtocolDecl *PD) {
Daniel Dunbar7050c552008-09-04 04:33:15 +00002671 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002672 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar7050c552008-09-04 04:33:15 +00002673 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2674
Owen Andersonade90fd2009-07-29 18:54:39 +00002675 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00002676 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar303e2c22008-08-11 02:45:11 +00002677}
2678
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002679void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stump18bb9282009-05-16 07:57:57 +00002680 // FIXME: We shouldn't need this, the protocol decl should contain enough
2681 // information to tell us whether this was a declaration or a definition.
Daniel Dunbarc475d422008-10-29 22:36:39 +00002682 DefinedProtocols.insert(PD->getIdentifier());
2683
2684 // If we have generated a forward reference to this protocol, emit
2685 // it now. Otherwise do nothing, the protocol objects are lazily
2686 // emitted.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002687 if (Protocols.count(PD->getIdentifier()))
Daniel Dunbarc475d422008-10-29 22:36:39 +00002688 GetOrEmitProtocol(PD);
2689}
2690
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00002691llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002692 if (DefinedProtocols.count(PD->getIdentifier()))
2693 return GetOrEmitProtocol(PD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002694
Daniel Dunbarc475d422008-10-29 22:36:39 +00002695 return GetOrEmitProtocolRef(PD);
2696}
2697
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002698llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(
2699 CodeGenFunction &CGF,
2700 const ObjCInterfaceDecl *ID,
2701 ObjCCommonTypesHelper &ObjCTypes) {
2702 llvm::Constant *lookUpClassFn = ObjCTypes.getLookUpClassFn();
2703
2704 llvm::Value *className =
2705 CGF.CGM.GetAddrOfConstantCString(ID->getObjCRuntimeNameAsString())
2706 .getPointer();
2707 ASTContext &ctx = CGF.CGM.getContext();
2708 className =
2709 CGF.Builder.CreateBitCast(className,
2710 CGF.ConvertType(
2711 ctx.getPointerType(ctx.CharTy.withConst())));
2712 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);
2713 call->setDoesNotThrow();
2714 return call;
2715}
2716
Daniel Dunbarb036db82008-08-13 03:21:16 +00002717/*
Rafael Espindolaf9e1e5e2014-02-20 14:09:04 +00002718// Objective-C 1.0 extensions
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002719struct _objc_protocol {
2720struct _objc_protocol_extension *isa;
2721char *protocol_name;
2722struct _objc_protocol_list *protocol_list;
2723struct _objc__method_prototype_list *instance_methods;
2724struct _objc__method_prototype_list *class_methods
2725};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002726
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002727See EmitProtocolExtension().
Daniel Dunbarb036db82008-08-13 03:21:16 +00002728*/
Daniel Dunbarc475d422008-10-29 22:36:39 +00002729llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00002730 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbarc475d422008-10-29 22:36:39 +00002731
2732 // Early exit if a defining object has already been generated.
2733 if (Entry && Entry->hasInitializer())
2734 return Entry;
2735
Douglas Gregora715bff2012-01-01 19:51:50 +00002736 // Use the protocol definition, if there is one.
2737 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2738 PD = Def;
2739
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002740 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stump18bb9282009-05-16 07:57:57 +00002741 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00002742 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2743
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002744 // Construct method lists.
2745 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2746 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002747 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002748 for (const auto *MD : PD->instance_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002749 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002750 if (!C)
2751 return GetOrEmitProtocolRef(PD);
2752
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002753 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2754 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002755 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002756 } else {
2757 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002758 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002759 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002760 }
2761
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002762 for (const auto *MD : PD->class_methods()) {
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002763 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00002764 if (!C)
2765 return GetOrEmitProtocolRef(PD);
2766
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002767 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2768 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002769 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002770 } else {
2771 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002772 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002773 }
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002774 }
2775
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002776 MethodTypesExt.insert(MethodTypesExt.end(),
2777 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
2778
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002779 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002780 EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
2781 MethodTypesExt),
2782 GetClassName(PD->getObjCRuntimeNameAsString()),
2783 EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
2784 PD->protocol_begin(), PD->protocol_end()),
2785 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
2786 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2787 InstanceMethods),
2788 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
2789 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2790 ClassMethods)};
Owen Anderson0e0189d2009-07-27 22:29:56 +00002791 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00002792 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002793
Daniel Dunbarb036db82008-08-13 03:21:16 +00002794 if (Entry) {
Rafael Espindola5d117f32014-03-06 01:10:46 +00002795 // Already created, update the initializer.
Rafael Espindolab3262952014-05-09 00:43:37 +00002796 assert(Entry->hasPrivateLinkage());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002797 Entry->setInitializer(Init);
2798 } else {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002799 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2800 false, llvm::GlobalValue::PrivateLinkage,
2801 Init, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002802 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002803 // FIXME: Is this necessary? Why only for protocol?
2804 Entry->setAlignment(4);
John McCallf9582a72012-03-30 21:29:05 +00002805
2806 Protocols[PD->getIdentifier()] = Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002807 }
Rafael Espindola060062a2014-03-06 22:15:10 +00002808 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbarc475d422008-10-29 22:36:39 +00002809
2810 return Entry;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002811}
2812
Daniel Dunbarc475d422008-10-29 22:36:39 +00002813llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00002814 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
2815
2816 if (!Entry) {
Daniel Dunbarc475d422008-10-29 22:36:39 +00002817 // We use the initializer as a marker of whether this is a forward
2818 // reference or not. At module finalization we add the empty
2819 // contents for protocols which were referenced but never defined.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002820 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
2821 false, llvm::GlobalValue::PrivateLinkage,
2822 nullptr, "OBJC_PROTOCOL_" + PD->getName());
Daniel Dunbarb036db82008-08-13 03:21:16 +00002823 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbarb036db82008-08-13 03:21:16 +00002824 // FIXME: Is this necessary? Why only for protocol?
2825 Entry->setAlignment(4);
2826 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002827
Daniel Dunbarb036db82008-08-13 03:21:16 +00002828 return Entry;
2829}
2830
2831/*
2832 struct _objc_protocol_extension {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002833 uint32_t size;
2834 struct objc_method_description_list *optional_instance_methods;
2835 struct objc_method_description_list *optional_class_methods;
2836 struct objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00002837 const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00002838 struct objc_property_list *class_properties;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002839 };
2840*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00002841llvm::Constant *
2842CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002843 ArrayRef<llvm::Constant*> OptInstanceMethods,
2844 ArrayRef<llvm::Constant*> OptClassMethods,
2845 ArrayRef<llvm::Constant*> MethodTypesExt) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002846 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00002847 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002848 llvm::Constant *Values[] = {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002849 llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
2850 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getName(),
2851 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2852 OptInstanceMethods),
2853 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
2854 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2855 OptClassMethods),
2856 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
Manman Renad0e7912016-01-29 19:22:54 +00002857 ObjCTypes, false),
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00002858 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
Manman Rence7bff52016-01-29 23:46:55 +00002859 MethodTypesExt, ObjCTypes),
2860 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,
2861 PD, ObjCTypes, true)};
Daniel Dunbarb036db82008-08-13 03:21:16 +00002862
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002863 // Return null if no extension bits are used.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002864 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
Manman Rence7bff52016-01-29 23:46:55 +00002865 Values[3]->isNullValue() && Values[4]->isNullValue() &&
2866 Values[5]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00002867 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002868
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002869 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00002870 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002871
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002872 // No special section, but goes in llvm.used
Alp Toker541d5072014-06-07 23:30:53 +00002873 return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00002874 StringRef(), CGM.getPointerAlign(), true);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002875}
2876
2877/*
2878 struct objc_protocol_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002879 struct objc_protocol_list *next;
2880 long count;
2881 Protocol *list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00002882 };
2883*/
Daniel Dunbardec75f82008-08-21 21:57:41 +00002884llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002885CGObjCMac::EmitProtocolList(Twine Name,
Daniel Dunbardec75f82008-08-21 21:57:41 +00002886 ObjCProtocolDecl::protocol_iterator begin,
2887 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002888 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbarb036db82008-08-13 03:21:16 +00002889
Daniel Dunbardec75f82008-08-21 21:57:41 +00002890 for (; begin != end; ++begin)
2891 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002892
2893 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002894 if (ProtocolRefs.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00002895 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002896
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002897 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00002898 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
Daniel Dunbarb036db82008-08-13 03:21:16 +00002899
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002900 llvm::Constant *Values[3];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00002901 // This field is only used by the runtime.
Owen Anderson0b75f232009-07-31 20:28:54 +00002902 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002903 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002904 ProtocolRefs.size() - 1);
2905 Values[2] =
2906 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
2907 ProtocolRefs.size()),
Daniel Dunbarb036db82008-08-13 03:21:16 +00002908 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002909
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002910 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002911 llvm::GlobalVariable *GV =
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00002912 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00002913 CGM.getPointerAlign(), false);
Owen Andersonade90fd2009-07-29 18:54:39 +00002914 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00002915}
2916
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002917void CGObjCCommonMac::
2918PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002919 SmallVectorImpl<llvm::Constant *> &Properties,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00002920 const Decl *Container,
Aaron Ballmandc4bea42014-03-13 18:47:37 +00002921 const ObjCProtocolDecl *Proto,
Manman Renad0e7912016-01-29 19:22:54 +00002922 const ObjCCommonTypesHelper &ObjCTypes,
2923 bool IsClassProperty) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002924 for (const auto *P : Proto->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002925 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2926 IsClassProperty);
2927
2928 for (const auto *PD : Proto->properties()) {
2929 if (IsClassProperty != PD->isClassProperty())
2930 continue;
David Blaikie82e95a32014-11-19 07:49:47 +00002931 if (!PropertySet.insert(PD->getIdentifier()).second)
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002932 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002933 llvm::Constant *Prop[] = {
2934 GetPropertyName(PD->getIdentifier()),
2935 GetPropertyTypeString(PD, Container)
2936 };
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002937 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2938 }
2939}
2940
Daniel Dunbarb036db82008-08-13 03:21:16 +00002941/*
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002942 struct _objc_property {
Bill Wendlinga515b582012-02-09 22:16:49 +00002943 const char * const name;
2944 const char * const attributes;
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002945 };
2946
2947 struct _objc_property_list {
Bill Wendlinga515b582012-02-09 22:16:49 +00002948 uint32_t entsize; // sizeof (struct _objc_property)
2949 uint32_t prop_count;
2950 struct _objc_property[prop_count];
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002951 };
2952*/
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002953llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00002954 const Decl *Container,
2955 const ObjCContainerDecl *OCD,
Manman Renad0e7912016-01-29 19:22:54 +00002956 const ObjCCommonTypesHelper &ObjCTypes,
2957 bool IsClassProperty) {
Manman Ren01b705e2016-04-19 19:05:03 +00002958 if (IsClassProperty) {
2959 // Make this entry NULL for OS X with deployment target < 10.11, for iOS
2960 // with deployment target < 9.0.
2961 const llvm::Triple &Triple = CGM.getTarget().getTriple();
2962 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||
2963 (Triple.isiOS() && Triple.isOSVersionLT(9)))
2964 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2965 }
2966
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002967 SmallVector<llvm::Constant *, 16> Properties;
Fariborz Jahanian751c1e72009-12-12 21:26:21 +00002968 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
Nico Weber08c93332015-12-03 17:44:51 +00002969
2970 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2971 llvm::Constant *Prop[] = {GetPropertyName(PD->getIdentifier()),
2972 GetPropertyTypeString(PD, Container)};
2973 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2974 };
2975 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
2976 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
Manman Renad0e7912016-01-29 19:22:54 +00002977 for (auto *PD : ClassExt->properties()) {
2978 if (IsClassProperty != PD->isClassProperty())
2979 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002980 PropertySet.insert(PD->getIdentifier());
2981 AddProperty(PD);
2982 }
Manman Renad0e7912016-01-29 19:22:54 +00002983
2984 for (const auto *PD : OCD->properties()) {
2985 if (IsClassProperty != PD->isClassProperty())
2986 continue;
Nico Weber08c93332015-12-03 17:44:51 +00002987 // Don't emit duplicate metadata for properties that were already in a
2988 // class extension.
2989 if (!PropertySet.insert(PD->getIdentifier()).second)
2990 continue;
2991 AddProperty(PD);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00002992 }
Nico Weber08c93332015-12-03 17:44:51 +00002993
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00002994 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002995 for (const auto *P : OID->all_referenced_protocols())
Manman Renad0e7912016-01-29 19:22:54 +00002996 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
2997 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00002998 }
2999 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003000 for (const auto *P : CD->protocols())
Manman Renad0e7912016-01-29 19:22:54 +00003001 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes,
3002 IsClassProperty);
Fariborz Jahanian7966aff2010-06-22 16:33:55 +00003003 }
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003004
3005 // Return null for empty list.
3006 if (Properties.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003007 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003008
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003009 unsigned PropertySize =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003010 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003011 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003012 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
3013 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003014 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003015 Properties.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003016 Values[2] = llvm::ConstantArray::get(AT, Properties);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003017 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003018
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003019 llvm::GlobalVariable *GV =
3020 CreateMetadataVar(Name, Init,
3021 (ObjCABI == 2) ? "__DATA, __objc_const" :
Daniel Dunbarb25452a2009-04-15 02:56:18 +00003022 "__OBJC,__property,regular,no_dead_strip",
John McCall7f416cc2015-09-08 08:05:57 +00003023 CGM.getPointerAlign(),
Daniel Dunbarb25452a2009-04-15 02:56:18 +00003024 true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003025 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003026}
3027
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003028llvm::Constant *
3029CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
3030 ArrayRef<llvm::Constant*> MethodTypes,
3031 const ObjCCommonTypesHelper &ObjCTypes) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003032 // Return null for empty list.
3033 if (MethodTypes.empty())
3034 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
3035
3036 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3037 MethodTypes.size());
3038 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
3039
Alp Toker541d5072014-06-07 23:30:53 +00003040 llvm::GlobalVariable *GV = CreateMetadataVar(
3041 Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(),
John McCall7f416cc2015-09-08 08:05:57 +00003042 CGM.getPointerAlign(), true);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00003043 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
3044}
3045
Daniel Dunbar80a840b2008-08-23 00:19:03 +00003046/*
Daniel Dunbarb036db82008-08-13 03:21:16 +00003047 struct objc_method_description_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003048 int count;
3049 struct objc_method_description list[];
Daniel Dunbarb036db82008-08-13 03:21:16 +00003050 };
3051*/
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003052llvm::Constant *
3053CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003054 llvm::Constant *Desc[] = {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003055 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003056 ObjCTypes.SelectorPtrTy),
3057 GetMethodVarType(MD)
3058 };
Douglas Gregora9d84932011-05-27 01:19:52 +00003059 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00003060 return nullptr;
3061
Owen Anderson0e0189d2009-07-27 22:29:56 +00003062 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003063 Desc);
3064}
Daniel Dunbarb036db82008-08-13 03:21:16 +00003065
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003066llvm::Constant *
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003067CGObjCMac::EmitMethodDescList(Twine Name, StringRef Section,
3068 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbarb036db82008-08-13 03:21:16 +00003069 // Return null for empty list.
3070 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003071 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003072
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003073 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003074 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003075 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003076 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003077 Values[1] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003078 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbarb036db82008-08-13 03:21:16 +00003079
John McCall7f416cc2015-09-08 08:05:57 +00003080 llvm::GlobalVariable *GV =
3081 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003082 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbarb036db82008-08-13 03:21:16 +00003083 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003084}
3085
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003086/*
3087 struct _objc_category {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003088 char *category_name;
3089 char *class_name;
3090 struct _objc_method_list *instance_methods;
3091 struct _objc_method_list *class_methods;
3092 struct _objc_protocol_list *protocols;
3093 uint32_t size; // <rdar://4585769>
3094 struct _objc_property_list *instance_properties;
Manman Ren96df0b32016-01-29 23:45:01 +00003095 struct _objc_property_list *class_properties;
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003096 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003097*/
Daniel Dunbar92992502008-08-15 22:20:32 +00003098void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00003099 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003100
Mike Stump18bb9282009-05-16 07:57:57 +00003101 // FIXME: This is poor design, the OCD should have a pointer to the category
3102 // decl. Additionally, note that Category can be null for the @implementation
3103 // w/o an @interface case. Sema should just create one for us as it does for
3104 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003105 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003106 const ObjCCategoryDecl *Category =
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003107 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003108
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003109 SmallString<256> ExtName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003110 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
3111 << OCD->getName();
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003112
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003113 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003114 for (const auto *I : OCD->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003115 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003116 InstanceMethods.push_back(GetMethodConstant(I));
3117
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003118 for (const auto *I : OCD->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003119 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003120 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003121
Manman Ren96df0b32016-01-29 23:45:01 +00003122 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003123 Values[0] = GetClassName(OCD->getName());
3124 Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString());
Fariborz Jahaniane55f8662009-04-29 20:40:05 +00003125 LazySymbols.insert(Interface->getIdentifier());
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003126 Values[2] = EmitMethodList("OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
3127 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
3128 InstanceMethods);
3129 Values[3] = EmitMethodList("OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
3130 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
3131 ClassMethods);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003132 if (Category) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003133 Values[4] =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003134 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
3135 Category->protocol_begin(), Category->protocol_end());
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003136 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003137 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003138 }
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003139 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003140
3141 // If there is no category @interface then there can be no properties.
3142 if (Category) {
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00003143 Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00003144 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00003145 Values[7] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
3146 OCD, Category, ObjCTypes, true);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003147 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003148 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00003149 Values[7] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Daniel Dunbar28e76ca2008-08-26 23:03:11 +00003150 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003151
Owen Anderson0e0189d2009-07-27 22:29:56 +00003152 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003153 Values);
3154
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003155 llvm::GlobalVariable *GV =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003156 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003157 "__OBJC,__category,regular,no_dead_strip",
3158 CGM.getPointerAlign(), true);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003159 DefinedCategories.push_back(GV);
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003160 DefinedCategoryNames.insert(llvm::CachedHashString(ExtName));
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003161 // method definition entries must be clear for next implementation.
3162 MethodDefinitions.clear();
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003163}
3164
John McCallef19dbb2012-10-17 04:53:23 +00003165enum FragileClassFlags {
John McCall460ce582015-10-22 18:38:17 +00003166 /// Apparently: is not a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003167 FragileABI_Class_Factory = 0x00001,
John McCall460ce582015-10-22 18:38:17 +00003168
3169 /// Is a meta-class.
John McCallef19dbb2012-10-17 04:53:23 +00003170 FragileABI_Class_Meta = 0x00002,
John McCall460ce582015-10-22 18:38:17 +00003171
3172 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003173 FragileABI_Class_HasCXXStructors = 0x02000,
John McCall460ce582015-10-22 18:38:17 +00003174
3175 /// Has hidden visibility.
John McCall09ec1ec2015-10-21 22:06:03 +00003176 FragileABI_Class_Hidden = 0x20000,
John McCall460ce582015-10-22 18:38:17 +00003177
3178 /// Class implementation was compiled under ARC.
3179 FragileABI_Class_CompiledByARC = 0x04000000,
3180
3181 /// Class implementation was compiled under MRC and has MRC weak ivars.
3182 /// Exclusive with CompiledByARC.
3183 FragileABI_Class_HasMRCWeakIvars = 0x08000000,
John McCallef19dbb2012-10-17 04:53:23 +00003184};
3185
3186enum NonFragileClassFlags {
3187 /// Is a meta-class.
3188 NonFragileABI_Class_Meta = 0x00001,
3189
3190 /// Is a root class.
3191 NonFragileABI_Class_Root = 0x00002,
3192
John McCall460ce582015-10-22 18:38:17 +00003193 /// Has a non-trivial constructor or destructor.
John McCallef19dbb2012-10-17 04:53:23 +00003194 NonFragileABI_Class_HasCXXStructors = 0x00004,
3195
3196 /// Has hidden visibility.
3197 NonFragileABI_Class_Hidden = 0x00010,
3198
3199 /// Has the exception attribute.
3200 NonFragileABI_Class_Exception = 0x00020,
3201
3202 /// (Obsolete) ARC-specific: this class has a .release_ivars method
3203 NonFragileABI_Class_HasIvarReleaser = 0x00040,
3204
3205 /// Class implementation was compiled under ARC.
John McCall0d54a172012-10-17 04:53:31 +00003206 NonFragileABI_Class_CompiledByARC = 0x00080,
3207
3208 /// Class has non-trivial destructors, but zero-initialization is okay.
John McCall460ce582015-10-22 18:38:17 +00003209 NonFragileABI_Class_HasCXXDestructorOnly = 0x00100,
3210
3211 /// Class implementation was compiled under MRC and has MRC weak ivars.
3212 /// Exclusive with CompiledByARC.
3213 NonFragileABI_Class_HasMRCWeakIvars = 0x00200,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003214};
3215
John McCall460ce582015-10-22 18:38:17 +00003216static bool hasWeakMember(QualType type) {
3217 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {
3218 return true;
3219 }
3220
3221 if (auto recType = type->getAs<RecordType>()) {
3222 for (auto field : recType->getDecl()->fields()) {
3223 if (hasWeakMember(field->getType()))
3224 return true;
3225 }
3226 }
3227
3228 return false;
3229}
3230
3231/// For compatibility, we only want to set the "HasMRCWeakIvars" flag
3232/// (and actually fill in a layout string) if we really do have any
3233/// __weak ivars.
3234static bool hasMRCWeakIvars(CodeGenModule &CGM,
3235 const ObjCImplementationDecl *ID) {
3236 if (!CGM.getLangOpts().ObjCWeak) return false;
3237 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
3238
3239 for (const ObjCIvarDecl *ivar =
3240 ID->getClassInterface()->all_declared_ivar_begin();
3241 ivar; ivar = ivar->getNextIvar()) {
3242 if (hasWeakMember(ivar->getType()))
3243 return true;
3244 }
3245
3246 return false;
3247}
3248
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003249/*
3250 struct _objc_class {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003251 Class isa;
3252 Class super_class;
3253 const char *name;
3254 long version;
3255 long info;
3256 long instance_size;
3257 struct _objc_ivar_list *ivars;
3258 struct _objc_method_list *methods;
3259 struct _objc_cache *cache;
3260 struct _objc_protocol_list *protocols;
3261 // Objective-C 1.0 extensions (<rdr://4585769>)
3262 const char *ivar_layout;
3263 struct _objc_class_ext *ext;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003264 };
3265
3266 See EmitClassExtension();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003267*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003268void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003269 DefinedSymbols.insert(ID->getIdentifier());
3270
Chris Lattner86d7d912008-11-24 03:54:41 +00003271 std::string ClassName = ID->getNameAsString();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003272 // FIXME: Gross
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003273 ObjCInterfaceDecl *Interface =
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003274 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003275 llvm::Constant *Protocols =
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003276 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3277 Interface->all_referenced_protocol_begin(),
3278 Interface->all_referenced_protocol_end());
John McCallef19dbb2012-10-17 04:53:23 +00003279 unsigned Flags = FragileABI_Class_Factory;
John McCall0d54a172012-10-17 04:53:31 +00003280 if (ID->hasNonZeroConstructors() || ID->hasDestructors())
John McCallef19dbb2012-10-17 04:53:23 +00003281 Flags |= FragileABI_Class_HasCXXStructors;
John McCall09ec1ec2015-10-21 22:06:03 +00003282
John McCall460ce582015-10-22 18:38:17 +00003283 bool hasMRCWeak = false;
3284
John McCall09ec1ec2015-10-21 22:06:03 +00003285 if (CGM.getLangOpts().ObjCAutoRefCount)
3286 Flags |= FragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00003287 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
3288 Flags |= FragileABI_Class_HasMRCWeakIvars;
John McCall09ec1ec2015-10-21 22:06:03 +00003289
John McCall3fd13f062015-10-21 18:06:47 +00003290 CharUnits Size =
3291 CGM.getContext().getASTObjCImplementationLayout(ID).getSize();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003292
3293 // FIXME: Set CXX-structors flag.
John McCall457a04e2010-10-22 21:05:15 +00003294 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003295 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003296
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003297 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003298 for (const auto *I : ID->instance_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003299 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003300 InstanceMethods.push_back(GetMethodConstant(I));
3301
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003302 for (const auto *I : ID->class_methods())
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003303 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00003304 ClassMethods.push_back(GetMethodConstant(I));
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003305
Aaron Ballmand85eff42014-03-14 15:02:45 +00003306 for (const auto *PID : ID->property_impls()) {
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003307 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3308 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3309
3310 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3311 if (llvm::Constant *C = GetMethodConstant(MD))
3312 InstanceMethods.push_back(C);
3313 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3314 if (llvm::Constant *C = GetMethodConstant(MD))
3315 InstanceMethods.push_back(C);
3316 }
3317 }
3318
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003319 llvm::Constant *Values[12];
Daniel Dunbarccf61832009-05-03 08:56:52 +00003320 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003321 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00003322 // Record a reference to the super class.
3323 LazySymbols.insert(Super->getIdentifier());
3324
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003325 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003326 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003327 ObjCTypes.ClassPtrTy);
3328 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003329 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003330 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003331 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003332 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003333 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3334 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
John McCall3fd13f062015-10-21 18:06:47 +00003335 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size.getQuantity());
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003336 Values[ 6] = EmitIvarList(ID, false);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003337 Values[7] = EmitMethodList("OBJC_INSTANCE_METHODS_" + ID->getName(),
3338 "__OBJC,__inst_meth,regular,no_dead_strip",
3339 InstanceMethods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003340 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003341 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003342 Values[ 9] = Protocols;
John McCall460ce582015-10-22 18:38:17 +00003343 Values[10] = BuildStrongIvarLayout(ID, CharUnits::Zero(), Size);
Manman Renad0e7912016-01-29 19:22:54 +00003344 Values[11] = EmitClassExtension(ID, Size, hasMRCWeak,
3345 false/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003346 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003347 Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003348 std::string Name("OBJC_CLASS_");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003349 Name += ClassName;
3350 const char *Section = "__OBJC,__class,regular,no_dead_strip";
3351 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003352 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003353 if (GV) {
3354 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3355 "Forward metaclass reference has incorrect type.");
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003356 GV->setInitializer(Init);
3357 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003358 GV->setAlignment(CGM.getPointerAlign().getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00003359 CGM.addCompilerUsedGlobal(GV);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003360 } else
John McCall7f416cc2015-09-08 08:05:57 +00003361 GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003362 DefinedClasses.push_back(GV);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00003363 ImplementedClasses.push_back(Interface);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00003364 // method definition entries must be clear for next implementation.
3365 MethodDefinitions.clear();
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003366}
3367
3368llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3369 llvm::Constant *Protocols,
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00003370 ArrayRef<llvm::Constant*> Methods) {
John McCallef19dbb2012-10-17 04:53:23 +00003371 unsigned Flags = FragileABI_Class_Meta;
Micah Villmowdd31ca12012-10-08 16:25:52 +00003372 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003373
John McCall457a04e2010-10-22 21:05:15 +00003374 if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
John McCallef19dbb2012-10-17 04:53:23 +00003375 Flags |= FragileABI_Class_Hidden;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003376
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003377 llvm::Constant *Values[12];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003378 // The isa for the metaclass is the root of the hierarchy.
3379 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3380 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3381 Root = Super;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003382 Values[ 0] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003383 llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003384 ObjCTypes.ClassPtrTy);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00003385 // The super class for the metaclass is emitted as the name of the
3386 // super class. The runtime fixes this up to point to the
3387 // *metaclass* for the super class.
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003388 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003389 Values[ 1] =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003390 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003391 ObjCTypes.ClassPtrTy);
3392 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00003393 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003394 }
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00003395 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003396 // Version is always 0.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003397 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3398 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
3399 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003400 Values[ 6] = EmitIvarList(ID, true);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003401 Values[7] =
3402 EmitMethodList("OBJC_CLASS_METHODS_" + ID->getNameAsString(),
3403 "__OBJC,__cls_meth,regular,no_dead_strip", Methods);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003404 // cache is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003405 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003406 Values[ 9] = Protocols;
3407 // ivar_layout for metaclass is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00003408 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Renad0e7912016-01-29 19:22:54 +00003409 // The class extension is used to store class properties for metaclasses.
3410 Values[11] = EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,
3411 true/*isClassProperty*/);
Owen Anderson0e0189d2009-07-27 22:29:56 +00003412 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003413 Values);
3414
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003415 std::string Name("OBJC_METACLASS_");
Benjamin Kramer1bbcbd02012-07-31 11:45:39 +00003416 Name += ID->getName();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003417
3418 // Check for a forward reference.
Rafael Espindola554256c2014-02-26 22:25:45 +00003419 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003420 if (GV) {
3421 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3422 "Forward metaclass reference has incorrect type.");
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003423 GV->setInitializer(Init);
3424 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003425 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003426 llvm::GlobalValue::PrivateLinkage,
Owen Andersonc10c8d32009-07-08 19:05:04 +00003427 Init, Name);
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003428 }
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003429 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbarae333842009-03-09 22:18:41 +00003430 GV->setAlignment(4);
Rafael Espindola060062a2014-03-06 22:15:10 +00003431 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003432
3433 return GV;
3434}
3435
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003436llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003437 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003438
Mike Stump18bb9282009-05-16 07:57:57 +00003439 // FIXME: Should we look these up somewhere other than the module. Its a bit
3440 // silly since we only generate these while processing an implementation, so
3441 // exactly one pointer would work if know when we entered/exitted an
3442 // implementation block.
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003443
3444 // Check for an existing forward reference.
Fariborz Jahanian475831b2009-01-07 20:11:22 +00003445 // Previously, metaclass with internal linkage may have been defined.
3446 // pass 'true' as 2nd argument so it is returned.
Rafael Espindola21039aa2014-02-27 16:26:32 +00003447 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3448 if (!GV)
3449 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003450 llvm::GlobalValue::PrivateLinkage, nullptr,
3451 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003452
3453 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3454 "Forward metaclass reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003455 return GV;
Daniel Dunbarca8531a2008-08-25 08:19:24 +00003456}
3457
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003458llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003459 std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
Rafael Espindola21039aa2014-02-27 16:26:32 +00003460 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3461
3462 if (!GV)
3463 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00003464 llvm::GlobalValue::PrivateLinkage, nullptr,
3465 Name);
Rafael Espindola21039aa2014-02-27 16:26:32 +00003466
3467 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3468 "Forward class metadata reference has incorrect type.");
Rafael Espindola21039aa2014-02-27 16:26:32 +00003469 return GV;
Fariborz Jahanianeb80c982009-11-12 20:14:24 +00003470}
3471
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003472/*
John McCall3fd13f062015-10-21 18:06:47 +00003473 Emit a "class extension", which in this specific context means extra
3474 data that doesn't fit in the normal fragile-ABI class structure, and
3475 has nothing to do with the language concept of a class extension.
3476
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003477 struct objc_class_ext {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003478 uint32_t size;
3479 const char *weak_ivar_layout;
3480 struct _objc_property_list *properties;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003481 };
3482*/
3483llvm::Constant *
John McCall3fd13f062015-10-21 18:06:47 +00003484CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,
Manman Renad0e7912016-01-29 19:22:54 +00003485 CharUnits InstanceSize, bool hasMRCWeakIvars,
3486 bool isClassProperty) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003487 uint64_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00003488 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003489
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003490 llvm::Constant *Values[3];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003491 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Manman Ren92e0a712016-02-21 05:31:05 +00003492 if (isClassProperty) {
3493 llvm::Type *PtrTy = CGM.Int8PtrTy;
3494 Values[1] = llvm::Constant::getNullValue(PtrTy);
3495 } else
Manman Renad0e7912016-01-29 19:22:54 +00003496 Values[1] = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,
3497 hasMRCWeakIvars);
3498 if (isClassProperty)
3499 Values[2] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getName(),
3500 ID, ID->getClassInterface(), ObjCTypes, true);
3501 else
3502 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
3503 ID, ID->getClassInterface(), ObjCTypes, false);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003504
3505 // Return null if no extension bits are used.
Manman Renad0e7912016-01-29 19:22:54 +00003506 if ((!Values[1] || Values[1]->isNullValue()) && Values[2]->isNullValue())
Owen Anderson0b75f232009-07-31 20:28:54 +00003507 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003508
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003509 llvm::Constant *Init =
Owen Anderson0e0189d2009-07-27 22:29:56 +00003510 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003511 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003512 "__OBJC,__class_ext,regular,no_dead_strip",
3513 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003514}
3515
3516/*
3517 struct objc_ivar {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003518 char *ivar_name;
3519 char *ivar_type;
3520 int ivar_offset;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003521 };
3522
3523 struct objc_ivar_list {
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003524 int ivar_count;
3525 struct objc_ivar list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003526 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003527*/
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003528llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianb042a592009-01-28 19:12:34 +00003529 bool ForClass) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003530 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003531
3532 // When emitting the root class GCC emits ivar entries for the
3533 // actual class structure. It is not clear if we need to follow this
3534 // behavior; for now lets try and get away with not doing it. If so,
3535 // the cleanest solution would be to make up an ObjCInterfaceDecl
3536 // for the class.
3537 if (ForClass)
Owen Anderson0b75f232009-07-31 20:28:54 +00003538 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003539
Jordy Rosea91768e2011-07-22 02:08:32 +00003540 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003541
Jordy Rosea91768e2011-07-22 02:08:32 +00003542 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00003543 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00003544 // Ignore unnamed bit-fields.
3545 if (!IVD->getDeclName())
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003546 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003547 llvm::Constant *Ivar[] = {
3548 GetMethodVarName(IVD->getIdentifier()),
3549 GetMethodVarType(IVD),
3550 llvm::ConstantInt::get(ObjCTypes.IntTy,
Eli Friedman8cbca202012-11-06 22:15:52 +00003551 ComputeIvarBaseOffset(CGM, OID, IVD))
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003552 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003553 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003554 }
3555
3556 // Return null for empty list.
3557 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003558 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003559
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003560 llvm::Constant *Values[2];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003561 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003562 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003563 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003564 Values[1] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003565 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003566
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003567 llvm::GlobalVariable *GV;
3568 if (ForClass)
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003569 GV =
3570 CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003571 "__OBJC,__class_vars,regular,no_dead_strip",
3572 CGM.getPointerAlign(), true);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00003573 else
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00003574 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), Init,
John McCall7f416cc2015-09-08 08:05:57 +00003575 "__OBJC,__instance_vars,regular,no_dead_strip",
3576 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00003577 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003578}
3579
3580/*
3581 struct objc_method {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003582 SEL method_name;
3583 char *method_types;
3584 void *method;
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003585 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003586
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003587 struct objc_method_list {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003588 struct objc_method_list *obsolete;
3589 int count;
3590 struct objc_method methods_list[count];
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003591 };
3592*/
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003593
3594/// GetMethodConstant - Return a struct objc_method constant for the
3595/// given method if it has been defined. The result is null if the
3596/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbareb1f9a22008-08-27 02:31:56 +00003597llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00003598 llvm::Function *Fn = GetMethodDefinition(MD);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003599 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00003600 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003601
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003602 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00003603 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00003604 ObjCTypes.SelectorPtrTy),
3605 GetMethodVarType(MD),
3606 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
3607 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00003608 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003609}
3610
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00003611llvm::Constant *CGObjCMac::EmitMethodList(Twine Name, StringRef Section,
3612 ArrayRef<llvm::Constant *> Methods) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003613 // Return null for empty list.
3614 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00003615 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003616
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003617 llvm::Constant *Values[3];
Owen Anderson0b75f232009-07-31 20:28:54 +00003618 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003619 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00003620 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003621 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00003622 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003623 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00003624
John McCall7f416cc2015-09-08 08:05:57 +00003625 llvm::GlobalVariable *GV =
3626 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00003627 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003628}
3629
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00003630llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003631 const ObjCContainerDecl *CD) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003632 SmallString<256> Name;
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003633 GetNameForMethod(OMD, CD, Name);
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003634
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003635 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003636 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003637 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003638 llvm::Function *Method =
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00003639 llvm::Function::Create(MethodTy,
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003640 llvm::GlobalValue::InternalLinkage,
Daniel Dunbard2386812009-10-19 01:21:19 +00003641 Name.str(),
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003642 &CGM.getModule());
Daniel Dunbar3c76cb52008-08-26 21:51:14 +00003643 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003644
Daniel Dunbara94ecd22008-08-16 03:19:19 +00003645 return Method;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003646}
3647
Alp Toker541d5072014-06-07 23:30:53 +00003648llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
3649 llvm::Constant *Init,
3650 StringRef Section,
John McCall7f416cc2015-09-08 08:05:57 +00003651 CharUnits Align,
Alp Toker541d5072014-06-07 23:30:53 +00003652 bool AddToUsed) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003653 llvm::Type *Ty = Init->getType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003654 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00003655 new llvm::GlobalVariable(CGM.getModule(), Ty, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00003656 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alp Toker541d5072014-06-07 23:30:53 +00003657 if (!Section.empty())
Daniel Dunbar30c65362009-03-09 20:09:19 +00003658 GV->setSection(Section);
John McCall7f416cc2015-09-08 08:05:57 +00003659 GV->setAlignment(Align.getQuantity());
Daniel Dunbar463cc8a2009-03-09 20:50:13 +00003660 if (AddToUsed)
Rafael Espindola060062a2014-03-06 22:15:10 +00003661 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar30c65362009-03-09 20:09:19 +00003662 return GV;
3663}
3664
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003665llvm::GlobalVariable *
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003666CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type,
3667 bool ForceNonFragileABI,
3668 bool NullTerminate) {
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003669 StringRef Label;
3670 switch (Type) {
3671 case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break;
3672 case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break;
3673 case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break;
3674 case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break;
3675 }
3676
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003677 bool NonFragile = ForceNonFragileABI || isNonFragileABI();
3678
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003679 StringRef Section;
3680 switch (Type) {
3681 case ObjCLabelType::ClassName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003682 Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals"
3683 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003684 break;
3685 case ObjCLabelType::MethodVarName:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003686 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"
3687 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003688 break;
3689 case ObjCLabelType::MethodVarType:
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003690 Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals"
3691 : "__TEXT,__cstring,cstring_literals";
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003692 break;
3693 case ObjCLabelType::PropertyName:
3694 Section = "__TEXT,__cstring,cstring_literals";
3695 break;
3696 }
3697
Saleem Abdulrasool82f6add2016-09-20 18:38:54 +00003698 llvm::Constant *Value =
3699 llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003700 llvm::GlobalVariable *GV =
Saleem Abdulrasool0c54dc82016-09-18 16:12:04 +00003701 new llvm::GlobalVariable(CGM.getModule(), Value->getType(),
3702 /*isConstant=*/true,
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003703 llvm::GlobalValue::PrivateLinkage, Value, Label);
Saleem Abdulrasool3f307512016-09-18 16:12:14 +00003704 if (CGM.getTriple().isOSBinFormatMachO())
3705 GV->setSection(Section);
3706 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00003707 GV->setAlignment(CharUnits::One().getQuantity());
3708 CGM.addCompilerUsedGlobal(GV);
3709
3710 return GV;
3711}
3712
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003713llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00003714 // Abuse this interface function as a place to finalize.
3715 FinishModule();
Craig Topper8a13c412014-05-21 05:09:00 +00003716 return nullptr;
Daniel Dunbar303e2c22008-08-11 02:45:11 +00003717}
3718
Chris Lattnerd4808922009-03-22 21:03:39 +00003719llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003720 return ObjCTypes.getGetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003721}
3722
Chris Lattnerd4808922009-03-22 21:03:39 +00003723llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003724 return ObjCTypes.getSetPropertyFn();
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003725}
3726
Ted Kremeneke65b0862012-03-06 20:05:56 +00003727llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
3728 bool copy) {
3729 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
3730}
3731
David Chisnall168b80f2010-12-26 22:13:16 +00003732llvm::Constant *CGObjCMac::GetGetStructFunction() {
3733 return ObjCTypes.getCopyStructFn();
3734}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003735
David Chisnall168b80f2010-12-26 22:13:16 +00003736llvm::Constant *CGObjCMac::GetSetStructFunction() {
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003737 return ObjCTypes.getCopyStructFn();
3738}
3739
David Chisnall0d75e062012-12-17 18:54:24 +00003740llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
3741 return ObjCTypes.getCppAtomicObjectFunction();
3742}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003743
David Chisnall0d75e062012-12-17 18:54:24 +00003744llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003745 return ObjCTypes.getCppAtomicObjectFunction();
3746}
3747
Chris Lattnerd4808922009-03-22 21:03:39 +00003748llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnerce8754e2009-04-22 02:44:54 +00003749 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson3f35a262008-08-31 04:05:03 +00003750}
3751
John McCallbd309292010-07-06 01:34:17 +00003752void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
3753 return EmitTryOrSynchronizedStmt(CGF, S);
3754}
3755
3756void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
3757 const ObjCAtSynchronizedStmt &S) {
3758 return EmitTryOrSynchronizedStmt(CGF, S);
3759}
3760
John McCall65bea082010-07-21 06:59:36 +00003761namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00003762 struct PerformFragileFinally final : EHScopeStack::Cleanup {
John McCall65bea082010-07-21 06:59:36 +00003763 const Stmt &S;
John McCall7f416cc2015-09-08 08:05:57 +00003764 Address SyncArgSlot;
3765 Address CallTryExitVar;
3766 Address ExceptionData;
John McCall65bea082010-07-21 06:59:36 +00003767 ObjCTypesHelper &ObjCTypes;
3768 PerformFragileFinally(const Stmt *S,
John McCall7f416cc2015-09-08 08:05:57 +00003769 Address SyncArgSlot,
3770 Address CallTryExitVar,
3771 Address ExceptionData,
John McCall65bea082010-07-21 06:59:36 +00003772 ObjCTypesHelper *ObjCTypes)
John McCall2dd7d442010-08-04 05:59:32 +00003773 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
John McCall65bea082010-07-21 06:59:36 +00003774 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
3775
Craig Topper4f12f102014-03-12 06:41:41 +00003776 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall65bea082010-07-21 06:59:36 +00003777 // Check whether we need to call objc_exception_try_exit.
3778 // In optimized code, this branch will always be folded.
3779 llvm::BasicBlock *FinallyCallExit =
3780 CGF.createBasicBlock("finally.call_exit");
3781 llvm::BasicBlock *FinallyNoCallExit =
3782 CGF.createBasicBlock("finally.no_call_exit");
3783 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
3784 FinallyCallExit, FinallyNoCallExit);
3785
3786 CGF.EmitBlock(FinallyCallExit);
John McCall882987f2013-02-28 19:01:20 +00003787 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
John McCall7f416cc2015-09-08 08:05:57 +00003788 ExceptionData.getPointer());
John McCall65bea082010-07-21 06:59:36 +00003789
3790 CGF.EmitBlock(FinallyNoCallExit);
3791
3792 if (isa<ObjCAtTryStmt>(S)) {
3793 if (const ObjCAtFinallyStmt* FinallyStmt =
John McCallcebe0ca2010-08-11 00:16:14 +00003794 cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
John McCall638d4f52013-04-03 00:56:07 +00003795 // Don't try to do the @finally if this is an EH cleanup.
3796 if (flags.isForEHCleanup()) return;
3797
John McCallcebe0ca2010-08-11 00:16:14 +00003798 // Save the current cleanup destination in case there's
3799 // control flow inside the finally statement.
3800 llvm::Value *CurCleanupDest =
3801 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
3802
John McCall65bea082010-07-21 06:59:36 +00003803 CGF.EmitStmt(FinallyStmt->getFinallyBody());
3804
John McCallcebe0ca2010-08-11 00:16:14 +00003805 if (CGF.HaveInsertPoint()) {
3806 CGF.Builder.CreateStore(CurCleanupDest,
3807 CGF.getNormalCleanupDestSlot());
3808 } else {
3809 // Currently, the end of the cleanup must always exist.
3810 CGF.EnsureInsertPoint();
3811 }
3812 }
John McCall65bea082010-07-21 06:59:36 +00003813 } else {
3814 // Emit objc_sync_exit(expr); as finally's sole statement for
3815 // @synchronized.
John McCall2dd7d442010-08-04 05:59:32 +00003816 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
John McCall882987f2013-02-28 19:01:20 +00003817 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
John McCall65bea082010-07-21 06:59:36 +00003818 }
3819 }
3820 };
John McCall42227ed2010-07-31 23:20:56 +00003821
3822 class FragileHazards {
3823 CodeGenFunction &CGF;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003824 SmallVector<llvm::Value*, 20> Locals;
John McCall42227ed2010-07-31 23:20:56 +00003825 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
3826
3827 llvm::InlineAsm *ReadHazard;
3828 llvm::InlineAsm *WriteHazard;
3829
3830 llvm::FunctionType *GetAsmFnType();
3831
3832 void collectLocals();
3833 void emitReadHazard(CGBuilderTy &Builder);
3834
3835 public:
3836 FragileHazards(CodeGenFunction &CGF);
John McCall2dd7d442010-08-04 05:59:32 +00003837
John McCall42227ed2010-07-31 23:20:56 +00003838 void emitWriteHazard();
John McCall2dd7d442010-08-04 05:59:32 +00003839 void emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00003840 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003841} // end anonymous namespace
John McCall42227ed2010-07-31 23:20:56 +00003842
3843/// Create the fragile-ABI read and write hazards based on the current
3844/// state of the function, which is presumed to be immediately prior
3845/// to a @try block. These hazards are used to maintain correct
3846/// semantics in the face of optimization and the fragile ABI's
3847/// cavalier use of setjmp/longjmp.
3848FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
3849 collectLocals();
3850
3851 if (Locals.empty()) return;
3852
3853 // Collect all the blocks in the function.
3854 for (llvm::Function::iterator
3855 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
3856 BlocksBeforeTry.insert(&*I);
3857
3858 llvm::FunctionType *AsmFnTy = GetAsmFnType();
3859
3860 // Create a read hazard for the allocas. This inhibits dead-store
3861 // optimizations and forces the values to memory. This hazard is
3862 // inserted before any 'throwing' calls in the protected scope to
3863 // reflect the possibility that the variables might be read from the
3864 // catch block if the call throws.
3865 {
3866 std::string Constraint;
3867 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3868 if (I) Constraint += ',';
3869 Constraint += "*m";
3870 }
3871
3872 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3873 }
3874
3875 // Create a write hazard for the allocas. This inhibits folding
3876 // loads across the hazard. This hazard is inserted at the
3877 // beginning of the catch path to reflect the possibility that the
3878 // variables might have been written within the protected scope.
3879 {
3880 std::string Constraint;
3881 for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3882 if (I) Constraint += ',';
3883 Constraint += "=*m";
3884 }
3885
3886 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3887 }
3888}
3889
3890/// Emit a write hazard at the current location.
3891void FragileHazards::emitWriteHazard() {
3892 if (Locals.empty()) return;
3893
John McCall882987f2013-02-28 19:01:20 +00003894 CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
John McCall42227ed2010-07-31 23:20:56 +00003895}
3896
John McCall42227ed2010-07-31 23:20:56 +00003897void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
3898 assert(!Locals.empty());
John McCall882987f2013-02-28 19:01:20 +00003899 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
3900 call->setDoesNotThrow();
3901 call->setCallingConv(CGF.getRuntimeCC());
John McCall42227ed2010-07-31 23:20:56 +00003902}
3903
3904/// Emit read hazards in all the protected blocks, i.e. all the blocks
3905/// which have been inserted since the beginning of the try.
John McCall2dd7d442010-08-04 05:59:32 +00003906void FragileHazards::emitHazardsInNewBlocks() {
John McCall42227ed2010-07-31 23:20:56 +00003907 if (Locals.empty()) return;
3908
John McCall7f416cc2015-09-08 08:05:57 +00003909 CGBuilderTy Builder(CGF, CGF.getLLVMContext());
John McCall42227ed2010-07-31 23:20:56 +00003910
3911 // Iterate through all blocks, skipping those prior to the try.
3912 for (llvm::Function::iterator
3913 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
3914 llvm::BasicBlock &BB = *FI;
3915 if (BlocksBeforeTry.count(&BB)) continue;
3916
3917 // Walk through all the calls in the block.
3918 for (llvm::BasicBlock::iterator
3919 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
3920 llvm::Instruction &I = *BI;
3921
3922 // Ignore instructions that aren't non-intrinsic calls.
3923 // These are the only calls that can possibly call longjmp.
3924 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
3925 if (isa<llvm::IntrinsicInst>(I))
3926 continue;
3927
3928 // Ignore call sites marked nounwind. This may be questionable,
3929 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
3930 llvm::CallSite CS(&I);
3931 if (CS.doesNotThrow()) continue;
3932
John McCall2dd7d442010-08-04 05:59:32 +00003933 // Insert a read hazard before the call. This will ensure that
3934 // any writes to the locals are performed before making the
3935 // call. If the call throws, then this is sufficient to
3936 // guarantee correctness as long as it doesn't also write to any
3937 // locals.
John McCall42227ed2010-07-31 23:20:56 +00003938 Builder.SetInsertPoint(&BB, BI);
3939 emitReadHazard(Builder);
3940 }
3941 }
3942}
3943
3944static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
3945 if (V) S.insert(V);
3946}
3947
John McCall7f416cc2015-09-08 08:05:57 +00003948static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) {
3949 if (V.isValid()) S.insert(V.getPointer());
3950}
3951
John McCall42227ed2010-07-31 23:20:56 +00003952void FragileHazards::collectLocals() {
3953 // Compute a set of allocas to ignore.
3954 llvm::DenseSet<llvm::Value*> AllocasToIgnore;
3955 addIfPresent(AllocasToIgnore, CGF.ReturnValue);
3956 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
John McCall42227ed2010-07-31 23:20:56 +00003957
3958 // Collect all the allocas currently in the function. This is
3959 // probably way too aggressive.
3960 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
3961 for (llvm::BasicBlock::iterator
3962 I = Entry.begin(), E = Entry.end(); I != E; ++I)
3963 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
3964 Locals.push_back(&*I);
3965}
3966
3967llvm::FunctionType *FragileHazards::GetAsmFnType() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003968 SmallVector<llvm::Type *, 16> tys(Locals.size());
John McCall9dc0db22011-05-15 01:53:33 +00003969 for (unsigned i = 0, e = Locals.size(); i != e; ++i)
3970 tys[i] = Locals[i]->getType();
3971 return llvm::FunctionType::get(CGF.VoidTy, tys, false);
John McCall65bea082010-07-21 06:59:36 +00003972}
3973
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003974/*
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003975
Daniel Dunbar59e476b2009-08-03 17:06:42 +00003976 Objective-C setjmp-longjmp (sjlj) Exception Handling
3977 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00003978
John McCallbd309292010-07-06 01:34:17 +00003979 A catch buffer is a setjmp buffer plus:
3980 - a pointer to the exception that was caught
3981 - a pointer to the previous exception data buffer
3982 - two pointers of reserved storage
3983 Therefore catch buffers form a stack, with a pointer to the top
3984 of the stack kept in thread-local storage.
3985
3986 objc_exception_try_enter pushes a catch buffer onto the EH stack.
3987 objc_exception_try_exit pops the given catch buffer, which is
3988 required to be the top of the EH stack.
3989 objc_exception_throw pops the top of the EH stack, writes the
3990 thrown exception into the appropriate field, and longjmps
3991 to the setjmp buffer. It crashes the process (with a printf
3992 and an abort()) if there are no catch buffers on the stack.
3993 objc_exception_extract just reads the exception pointer out of the
3994 catch buffer.
3995
3996 There's no reason an implementation couldn't use a light-weight
3997 setjmp here --- something like __builtin_setjmp, but API-compatible
3998 with the heavyweight setjmp. This will be more important if we ever
3999 want to implement correct ObjC/C++ exception interactions for the
4000 fragile ABI.
4001
4002 Note that for this use of setjmp/longjmp to be correct, we may need
4003 to mark some local variables volatile: if a non-volatile local
4004 variable is modified between the setjmp and the longjmp, it has
4005 indeterminate value. For the purposes of LLVM IR, it may be
4006 sufficient to make loads and stores within the @try (to variables
4007 declared outside the @try) volatile. This is necessary for
4008 optimized correctness, but is not currently being done; this is
4009 being tracked as rdar://problem/8160285
4010
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004011 The basic framework for a @try-catch-finally is as follows:
4012 {
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004013 objc_exception_data d;
4014 id _rethrow = null;
Anders Carlssonda0e4562009-02-07 21:26:04 +00004015 bool _call_try_exit = true;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004016
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004017 objc_exception_try_enter(&d);
4018 if (!setjmp(d.jmp_buf)) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004019 ... try body ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004020 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004021 // exception path
4022 id _caught = objc_exception_extract(&d);
4023
4024 // enter new try scope for handlers
4025 if (!setjmp(d.jmp_buf)) {
4026 ... match exception and execute catch blocks ...
4027
4028 // fell off end, rethrow.
4029 _rethrow = _caught;
4030 ... jump-through-finally to finally_rethrow ...
4031 } else {
4032 // exception in catch block
4033 _rethrow = objc_exception_extract(&d);
4034 _call_try_exit = false;
4035 ... jump-through-finally to finally_rethrow ...
4036 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004037 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004038 ... jump-through-finally to finally_end ...
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004039
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004040 finally:
Anders Carlssonda0e4562009-02-07 21:26:04 +00004041 if (_call_try_exit)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004042 objc_exception_try_exit(&d);
Anders Carlssonda0e4562009-02-07 21:26:04 +00004043
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004044 ... finally block ....
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004045 ... dispatch to finally destination ...
4046
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004047 finally_rethrow:
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004048 objc_exception_throw(_rethrow);
4049
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004050 finally_end:
4051 }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004052
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004053 This framework differs slightly from the one gcc uses, in that gcc
4054 uses _rethrow to determine if objc_exception_try_exit should be called
4055 and if the object should be rethrown. This breaks in the face of
4056 throwing nil and introduces unnecessary branches.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004057
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004058 We specialize this framework for a few particular circumstances:
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004059
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004060 - If there are no catch blocks, then we avoid emitting the second
4061 exception handling context.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004062
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004063 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
4064 e)) we avoid emitting the code to rethrow an uncaught exception.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004065
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004066 - FIXME: If there is no @finally block we can do a few more
4067 simplifications.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004068
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004069 Rethrows and Jumps-Through-Finally
4070 --
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004071
John McCallbd309292010-07-06 01:34:17 +00004072 '@throw;' is supported by pushing the currently-caught exception
4073 onto ObjCEHStack while the @catch blocks are emitted.
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004074
John McCallbd309292010-07-06 01:34:17 +00004075 Branches through the @finally block are handled with an ordinary
4076 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
4077 exceptions are not compatible with C++ exceptions, and this is
4078 hardly the only place where this will go wrong.
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004079
John McCallbd309292010-07-06 01:34:17 +00004080 @synchronized(expr) { stmt; } is emitted as if it were:
4081 id synch_value = expr;
4082 objc_sync_enter(synch_value);
4083 @try { stmt; } @finally { objc_sync_exit(synch_value); }
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004084*/
4085
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00004086void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4087 const Stmt &S) {
4088 bool isTry = isa<ObjCAtTryStmt>(S);
John McCallbd309292010-07-06 01:34:17 +00004089
4090 // A destination for the fall-through edges of the catch handlers to
4091 // jump to.
4092 CodeGenFunction::JumpDest FinallyEnd =
4093 CGF.getJumpDestInCurrentScope("finally.end");
4094
4095 // A destination for the rethrow edge of the catch handlers to jump
4096 // to.
4097 CodeGenFunction::JumpDest FinallyRethrow =
4098 CGF.getJumpDestInCurrentScope("finally.rethrow");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004099
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004100 // For @synchronized, call objc_sync_enter(sync.expr). The
4101 // evaluation of the expression must occur before we enter the
John McCall2dd7d442010-08-04 05:59:32 +00004102 // @synchronized. We can't avoid a temp here because we need the
4103 // value to be preserved. If the backend ever does liveness
4104 // correctly after setjmp, this will be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00004105 Address SyncArgSlot = Address::invalid();
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004106 if (!isTry) {
John McCall2dd7d442010-08-04 05:59:32 +00004107 llvm::Value *SyncArg =
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004108 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4109 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004110 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
John McCall2dd7d442010-08-04 05:59:32 +00004111
John McCall7f416cc2015-09-08 08:05:57 +00004112 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),
4113 CGF.getPointerAlign(), "sync.arg");
John McCall2dd7d442010-08-04 05:59:32 +00004114 CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
Daniel Dunbar94ceb612009-02-24 01:43:46 +00004115 }
Daniel Dunbar2efd5382008-09-30 01:06:03 +00004116
John McCall2dd7d442010-08-04 05:59:32 +00004117 // Allocate memory for the setjmp buffer. This needs to be kept
4118 // live throughout the try and catch blocks.
John McCall7f416cc2015-09-08 08:05:57 +00004119 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
4120 CGF.getPointerAlign(),
4121 "exceptiondata.ptr");
John McCall2dd7d442010-08-04 05:59:32 +00004122
John McCall42227ed2010-07-31 23:20:56 +00004123 // Create the fragile hazards. Note that this will not capture any
4124 // of the allocas required for exception processing, but will
4125 // capture the current basic block (which extends all the way to the
4126 // setjmp call) as "before the @try".
4127 FragileHazards Hazards(CGF);
4128
John McCallbd309292010-07-06 01:34:17 +00004129 // Create a flag indicating whether the cleanup needs to call
4130 // objc_exception_try_exit. This is true except when
4131 // - no catches match and we're branching through the cleanup
4132 // just to rethrow the exception, or
4133 // - a catch matched and we're falling out of the catch handler.
John McCall2dd7d442010-08-04 05:59:32 +00004134 // The setjmp-safety rule here is that we should always store to this
4135 // variable in a place that dominates the branch through the cleanup
4136 // without passing through any setjmps.
John McCall7f416cc2015-09-08 08:05:57 +00004137 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
4138 CharUnits::One(),
4139 "_call_try_exit");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004140
John McCall9916e3f2010-10-04 23:42:51 +00004141 // A slot containing the exception to rethrow. Only needed when we
4142 // have both a @catch and a @finally.
John McCall7f416cc2015-09-08 08:05:57 +00004143 Address PropagatingExnVar = Address::invalid();
John McCall9916e3f2010-10-04 23:42:51 +00004144
John McCallbd309292010-07-06 01:34:17 +00004145 // Push a normal cleanup to leave the try scope.
John McCall638d4f52013-04-03 00:56:07 +00004146 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
John McCall2dd7d442010-08-04 05:59:32 +00004147 SyncArgSlot,
John McCallcda666c2010-07-21 07:22:38 +00004148 CallTryExitVar,
4149 ExceptionData,
4150 &ObjCTypes);
John McCallbd309292010-07-06 01:34:17 +00004151
4152 // Enter a try block:
4153 // - Call objc_exception_try_enter to push ExceptionData on top of
4154 // the EH stack.
Nico Weber6307cf02015-02-26 20:43:00 +00004155 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004156 ExceptionData.getPointer());
John McCallbd309292010-07-06 01:34:17 +00004157
4158 // - Call setjmp on the exception data buffer.
4159 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
4160 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
David Blaikie6b2a8302015-04-03 17:47:16 +00004161 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
John McCall7f416cc2015-09-08 08:05:57 +00004162 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes,
4163 "setjmp_buffer");
Nico Weber6307cf02015-02-26 20:43:00 +00004164 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
4165 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004166 SetJmpResult->setCanReturnTwice();
John McCallbd309292010-07-06 01:34:17 +00004167
4168 // If setjmp returned 0, enter the protected block; otherwise,
4169 // branch to the handler.
Daniel Dunbar75283ff2008-11-11 02:29:29 +00004170 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4171 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
John McCallbd309292010-07-06 01:34:17 +00004172 llvm::Value *DidCatch =
John McCallcebe0ca2010-08-11 00:16:14 +00004173 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4174 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004175
John McCallbd309292010-07-06 01:34:17 +00004176 // Emit the protected block.
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004177 CGF.EmitBlock(TryBlock);
John McCall2dd7d442010-08-04 05:59:32 +00004178 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004179 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
John McCallbd309292010-07-06 01:34:17 +00004180 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
John McCall2dd7d442010-08-04 05:59:32 +00004181
4182 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004183
John McCallbd309292010-07-06 01:34:17 +00004184 // Emit the exception handler block.
Daniel Dunbar7f086782008-09-27 23:30:04 +00004185 CGF.EmitBlock(TryHandler);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004186
John McCall42227ed2010-07-31 23:20:56 +00004187 // Don't optimize loads of the in-scope locals across this point.
4188 Hazards.emitWriteHazard();
4189
John McCallbd309292010-07-06 01:34:17 +00004190 // For a @synchronized (or a @try with no catches), just branch
4191 // through the cleanup to the rethrow block.
4192 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
4193 // Tell the cleanup not to re-pop the exit.
John McCall2dd7d442010-08-04 05:59:32 +00004194 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004195 CGF.EmitBranchThroughCleanup(FinallyRethrow);
John McCallbd309292010-07-06 01:34:17 +00004196
4197 // Otherwise, we have to match against the caught exceptions.
4198 } else {
John McCall2dd7d442010-08-04 05:59:32 +00004199 // Retrieve the exception object. We may emit multiple blocks but
4200 // nothing can cross this so the value is already in SSA form.
4201 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004202 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004203 ExceptionData.getPointer(), "caught");
John McCall2dd7d442010-08-04 05:59:32 +00004204
John McCallbd309292010-07-06 01:34:17 +00004205 // Push the exception to rethrow onto the EH value stack for the
4206 // benefit of any @throws in the handlers.
4207 CGF.ObjCEHValueStack.push_back(Caught);
4208
Douglas Gregor96c79492010-04-23 22:50:49 +00004209 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004210
Craig Topper8a13c412014-05-21 05:09:00 +00004211 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
John McCallbd309292010-07-06 01:34:17 +00004212
Craig Topper8a13c412014-05-21 05:09:00 +00004213 llvm::BasicBlock *CatchBlock = nullptr;
4214 llvm::BasicBlock *CatchHandler = nullptr;
John McCall2dd7d442010-08-04 05:59:32 +00004215 if (HasFinally) {
John McCall9916e3f2010-10-04 23:42:51 +00004216 // Save the currently-propagating exception before
4217 // objc_exception_try_enter clears the exception slot.
4218 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
John McCall7f416cc2015-09-08 08:05:57 +00004219 CGF.getPointerAlign(),
John McCall9916e3f2010-10-04 23:42:51 +00004220 "propagating_exception");
4221 CGF.Builder.CreateStore(Caught, PropagatingExnVar);
4222
John McCall2dd7d442010-08-04 05:59:32 +00004223 // Enter a new exception try block (in case a @catch block
4224 // throws an exception).
John McCall882987f2013-02-28 19:01:20 +00004225 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004226 ExceptionData.getPointer());
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004227
John McCall2dd7d442010-08-04 05:59:32 +00004228 llvm::CallInst *SetJmpResult =
John McCall882987f2013-02-28 19:01:20 +00004229 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
4230 SetJmpBuffer, "setjmp.result");
Bill Wendlingbd26cf92011-12-19 23:53:28 +00004231 SetJmpResult->setCanReturnTwice();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004232
John McCall2dd7d442010-08-04 05:59:32 +00004233 llvm::Value *Threw =
4234 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
4235
4236 CatchBlock = CGF.createBasicBlock("catch");
4237 CatchHandler = CGF.createBasicBlock("catch_for_catch");
4238 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
4239
4240 CGF.EmitBlock(CatchBlock);
4241 }
4242
4243 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004244
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004245 // Handle catch list. As a special case we check if everything is
4246 // matched and avoid generating code for falling off the end if
4247 // so.
4248 bool AllMatched = false;
Douglas Gregor96c79492010-04-23 22:50:49 +00004249 for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
4250 const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004251
Douglas Gregor46a572b2010-04-26 16:46:50 +00004252 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00004253 const ObjCObjectPointerType *OPT = nullptr;
Daniel Dunbar523208f2008-09-27 07:36:24 +00004254
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004255 // catch(...) always matches.
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004256 if (!CatchParam) {
4257 AllMatched = true;
4258 } else {
John McCall9dd450b2009-09-21 23:43:11 +00004259 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004260
John McCallbd309292010-07-06 01:34:17 +00004261 // catch(id e) always matches under this ABI, since only
4262 // ObjC exceptions end up here in the first place.
Daniel Dunbar86919f42008-09-27 22:21:14 +00004263 // FIXME: For the time being we also match id<X>; this should
4264 // be rejected by Sema instead.
Eli Friedman55179ca2009-07-11 00:57:02 +00004265 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004266 AllMatched = true;
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004267 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004268
John McCallbd309292010-07-06 01:34:17 +00004269 // If this is a catch-all, we don't need to test anything.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004270 if (AllMatched) {
John McCallbd309292010-07-06 01:34:17 +00004271 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4272
Anders Carlsson9396a892008-09-11 09:15:33 +00004273 if (CatchParam) {
John McCall1c9c3fd2010-10-15 04:57:14 +00004274 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004275 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
John McCallbd309292010-07-06 01:34:17 +00004276
4277 // These types work out because ConvertType(id) == i8*.
John McCall17f02752015-10-30 00:56:02 +00004278 EmitInitOfCatchParam(CGF, Caught, CatchParam);
Anders Carlsson9396a892008-09-11 09:15:33 +00004279 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004280
Anders Carlsson9396a892008-09-11 09:15:33 +00004281 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004282
4283 // The scope of the catch variable ends right here.
4284 CatchVarCleanups.ForceCleanup();
4285
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004286 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004287 break;
4288 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004289
Steve Naroff7cae42b2009-07-10 23:34:53 +00004290 assert(OPT && "Unexpected non-object pointer type in @catch");
John McCall96fa4842010-05-17 21:00:27 +00004291 const ObjCObjectType *ObjTy = OPT->getObjectType();
John McCallbd309292010-07-06 01:34:17 +00004292
4293 // FIXME: @catch (Class c) ?
John McCall96fa4842010-05-17 21:00:27 +00004294 ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
4295 assert(IDecl && "Catch parameter must have Objective-C type!");
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004296
4297 // Check if the @catch block matches the exception object.
John McCall882987f2013-02-28 19:01:20 +00004298 llvm::Value *Class = EmitClassRef(CGF, IDecl);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004299
John McCall882987f2013-02-28 19:01:20 +00004300 llvm::Value *matchArgs[] = { Class, Caught };
John McCallbd309292010-07-06 01:34:17 +00004301 llvm::CallInst *Match =
John McCall882987f2013-02-28 19:01:20 +00004302 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
4303 matchArgs, "match");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004304
John McCallbd309292010-07-06 01:34:17 +00004305 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
4306 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004307
4308 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar7f086782008-09-27 23:30:04 +00004309 MatchedBlock, NextCatchBlock);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004310
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004311 // Emit the @catch block.
4312 CGF.EmitBlock(MatchedBlock);
John McCallbd309292010-07-06 01:34:17 +00004313
4314 // Collect any cleanups for the catch variable. The scope lasts until
4315 // the end of the catch body.
John McCall2dd7d442010-08-04 05:59:32 +00004316 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
John McCallbd309292010-07-06 01:34:17 +00004317
John McCall1c9c3fd2010-10-15 04:57:14 +00004318 CGF.EmitAutoVarDecl(*CatchParam);
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004319 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004320
John McCallbd309292010-07-06 01:34:17 +00004321 // Initialize the catch variable.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004322 llvm::Value *Tmp =
4323 CGF.Builder.CreateBitCast(Caught,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004324 CGF.ConvertType(CatchParam->getType()));
John McCall17f02752015-10-30 00:56:02 +00004325 EmitInitOfCatchParam(CGF, Tmp, CatchParam);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004326
Anders Carlsson9396a892008-09-11 09:15:33 +00004327 CGF.EmitStmt(CatchStmt->getCatchBody());
John McCallbd309292010-07-06 01:34:17 +00004328
4329 // We're done with the catch variable.
4330 CatchVarCleanups.ForceCleanup();
4331
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004332 CGF.EmitBranchThroughCleanup(FinallyEnd);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004333
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004334 CGF.EmitBlock(NextCatchBlock);
4335 }
4336
John McCallbd309292010-07-06 01:34:17 +00004337 CGF.ObjCEHValueStack.pop_back();
4338
John McCall2dd7d442010-08-04 05:59:32 +00004339 // If nothing wanted anything to do with the caught exception,
4340 // kill the extract call.
4341 if (Caught->use_empty())
4342 Caught->eraseFromParent();
4343
4344 if (!AllMatched)
4345 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4346
4347 if (HasFinally) {
4348 // Emit the exception handler for the @catch blocks.
4349 CGF.EmitBlock(CatchHandler);
4350
4351 // In theory we might now need a write hazard, but actually it's
4352 // unnecessary because there's no local-accessing code between
4353 // the try's write hazard and here.
4354 //Hazards.emitWriteHazard();
4355
John McCall9916e3f2010-10-04 23:42:51 +00004356 // Extract the new exception and save it to the
4357 // propagating-exception slot.
John McCall7f416cc2015-09-08 08:05:57 +00004358 assert(PropagatingExnVar.isValid());
John McCall9916e3f2010-10-04 23:42:51 +00004359 llvm::CallInst *NewCaught =
John McCall882987f2013-02-28 19:01:20 +00004360 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004361 ExceptionData.getPointer(), "caught");
John McCall9916e3f2010-10-04 23:42:51 +00004362 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4363
John McCall2dd7d442010-08-04 05:59:32 +00004364 // Don't pop the catch handler; the throw already did.
4365 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004366 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbarb22ff592008-09-27 07:03:52 +00004367 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004368 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004369
John McCall42227ed2010-07-31 23:20:56 +00004370 // Insert read hazards as required in the new blocks.
John McCall2dd7d442010-08-04 05:59:32 +00004371 Hazards.emitHazardsInNewBlocks();
John McCall42227ed2010-07-31 23:20:56 +00004372
John McCallbd309292010-07-06 01:34:17 +00004373 // Pop the cleanup.
John McCall2dd7d442010-08-04 05:59:32 +00004374 CGF.Builder.restoreIP(TryFallthroughIP);
4375 if (CGF.HaveInsertPoint())
4376 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
John McCallbd309292010-07-06 01:34:17 +00004377 CGF.PopCleanupBlock();
John McCall2dd7d442010-08-04 05:59:32 +00004378 CGF.EmitBlock(FinallyEnd.getBlock(), true);
Anders Carlssonbfee7e92009-02-09 20:38:58 +00004379
John McCallbd309292010-07-06 01:34:17 +00004380 // Emit the rethrow block.
John McCall42227ed2010-07-31 23:20:56 +00004381 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
John McCallad5d61e2010-07-23 21:56:41 +00004382 CGF.EmitBlock(FinallyRethrow.getBlock(), true);
John McCallbd309292010-07-06 01:34:17 +00004383 if (CGF.HaveInsertPoint()) {
John McCall9916e3f2010-10-04 23:42:51 +00004384 // If we have a propagating-exception variable, check it.
4385 llvm::Value *PropagatingExn;
John McCall7f416cc2015-09-08 08:05:57 +00004386 if (PropagatingExnVar.isValid()) {
John McCall9916e3f2010-10-04 23:42:51 +00004387 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
John McCall2dd7d442010-08-04 05:59:32 +00004388
John McCall9916e3f2010-10-04 23:42:51 +00004389 // Otherwise, just look in the buffer for the exception to throw.
4390 } else {
4391 llvm::CallInst *Caught =
John McCall882987f2013-02-28 19:01:20 +00004392 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004393 ExceptionData.getPointer());
John McCall9916e3f2010-10-04 23:42:51 +00004394 PropagatingExn = Caught;
4395 }
4396
John McCall882987f2013-02-28 19:01:20 +00004397 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4398 PropagatingExn);
John McCallbd309292010-07-06 01:34:17 +00004399 CGF.Builder.CreateUnreachable();
Fariborz Jahaniane2caaaa2008-11-21 19:21:53 +00004400 }
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004401
John McCall42227ed2010-07-31 23:20:56 +00004402 CGF.Builder.restoreIP(SavedIP);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004403}
4404
4405void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004406 const ObjCAtThrowStmt &S,
4407 bool ClearInsertionPoint) {
Anders Carlssone005aa12008-09-09 16:16:55 +00004408 llvm::Value *ExceptionAsObject;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004409
Anders Carlssone005aa12008-09-09 16:16:55 +00004410 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00004411 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004412 ExceptionAsObject =
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004413 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
Anders Carlssone005aa12008-09-09 16:16:55 +00004414 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004415 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbard3dcb4f82008-09-28 01:03:14 +00004416 "Unexpected rethrow outside @catch block.");
Anders Carlssonbf8a1be2009-02-07 21:37:21 +00004417 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlssone005aa12008-09-09 16:16:55 +00004418 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004419
John McCall882987f2013-02-28 19:01:20 +00004420 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
John McCallbd309292010-07-06 01:34:17 +00004421 ->setDoesNotReturn();
Anders Carlsson4f1c7c32008-09-09 17:59:25 +00004422 CGF.Builder.CreateUnreachable();
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004423
4424 // Clear the insertion point to indicate we are in unreachable code.
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00004425 if (ClearInsertionPoint)
4426 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00004427}
4428
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004429/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004430/// object: objc_read_weak (id *src)
4431///
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004432llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004433 Address AddrWeakObj) {
4434 llvm::Type* DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004435 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
4436 ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00004437 llvm::Value *read_weak =
4438 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004439 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00004440 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004441 return read_weak;
4442}
4443
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004444/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4445/// objc_assign_weak (id src, id *dst)
4446///
4447void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004448 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004449 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004450 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004451 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004452 assert(Size <= 8 && "does not support size > 8");
4453 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004454 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004455 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4456 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004457 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4458 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004459 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004460 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4461 args, "weakassign");
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004462}
4463
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004464/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4465/// objc_assign_global (id src, id *dst)
4466///
4467void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004468 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00004469 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004470 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004471 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004472 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004473 assert(Size <= 8 && "does not support size > 8");
4474 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004475 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004476 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4477 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004478 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4479 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004480 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00004481 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00004482 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4483 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00004484 else
John McCall882987f2013-02-28 19:01:20 +00004485 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4486 args, "threadlocalassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004487}
4488
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004489/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004490/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004491///
4492void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004493 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004494 llvm::Value *ivarOffset) {
4495 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00004496 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004497 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004498 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004499 assert(Size <= 8 && "does not support size > 8");
4500 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004501 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004502 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4503 }
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004504 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4505 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004506 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00004507 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004508}
4509
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004510/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4511/// objc_assign_strongCast (id src, id *dst)
4512///
4513void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004514 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004515 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004516 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004517 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00004518 assert(Size <= 8 && "does not support size > 8");
4519 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004520 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00004521 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4522 }
Fariborz Jahanian50a12702008-11-19 17:34:06 +00004523 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4524 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004525 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00004526 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
John McCall7f416cc2015-09-08 08:05:57 +00004527 args, "strongassign");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004528}
4529
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004530void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004531 Address DestPtr,
4532 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004533 llvm::Value *size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004534 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
4535 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00004536 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size };
John McCall882987f2013-02-28 19:01:20 +00004537 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004538}
4539
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004540/// EmitObjCValueForIvar - Code Gen for ivar reference.
4541///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004542LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
4543 QualType ObjectTy,
4544 llvm::Value *BaseValue,
4545 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004546 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004547 const ObjCInterfaceDecl *ID =
4548 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004549 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4550 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004551}
4552
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004553llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004554 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004555 const ObjCIvarDecl *Ivar) {
Eli Friedman8cbca202012-11-06 22:15:52 +00004556 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
4557 return llvm::ConstantInt::get(
4558 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
4559 Offset);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004560}
4561
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004562/* *** Private Interface *** */
4563
4564/// EmitImageInfo - Emit the image info marker used to encode some module
4565/// level information.
4566///
4567/// See: <rdr://4810609&4810587&4810587>
4568/// struct IMAGE_INFO {
4569/// unsigned version;
4570/// unsigned flags;
4571/// };
4572enum ImageInfoFlags {
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004573 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004574 eImageInfo_GarbageCollected = (1 << 1),
4575 eImageInfo_GCOnly = (1 << 2),
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004576 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
Daniel Dunbar75e909f2009-04-20 07:11:47 +00004577
Daniel Dunbar5e639272010-04-25 20:39:01 +00004578 // A flag indicating that the module has no instances of a @synthesize of a
4579 // superclass variable. <rdar://problem/6803242>
Fariborz Jahanian39c17a82014-01-14 22:01:08 +00004580 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
Manman Ren96df0b32016-01-29 23:45:01 +00004581 eImageInfo_ImageIsSimulated = (1 << 5),
4582 eImageInfo_ClassProperties = (1 << 6)
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004583};
4584
Daniel Dunbar5e639272010-04-25 20:39:01 +00004585void CGObjCCommonMac::EmitImageInfo() {
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004586 unsigned version = 0; // Version is unused?
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004587 const char *Section = (ObjCABI == 1) ?
4588 "__OBJC, __image_info,regular" :
4589 "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004590
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004591 // Generate module-level named metadata to convey this information to the
4592 // linker and code-gen.
4593 llvm::Module &Mod = CGM.getModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004594
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004595 // Add the ObjC ABI version to the module flags.
4596 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
4597 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
4598 version);
4599 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
4600 llvm::MDString::get(VMContext,Section));
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004601
David Blaikiebbafb8a2012-03-11 07:00:24 +00004602 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004603 // Non-GC overrides those files which specify GC.
4604 Mod.addModuleFlag(llvm::Module::Override,
4605 "Objective-C Garbage Collection", (uint32_t)0);
4606 } else {
4607 // Add the ObjC garbage collection value.
4608 Mod.addModuleFlag(llvm::Module::Error,
4609 "Objective-C Garbage Collection",
4610 eImageInfo_GarbageCollected);
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00004611
David Blaikiebbafb8a2012-03-11 07:00:24 +00004612 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004613 // Add the ObjC GC Only value.
4614 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
4615 eImageInfo_GCOnly);
4616
4617 // Require that GC be specified and set to eImageInfo_GarbageCollected.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004618 llvm::Metadata *Ops[2] = {
4619 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
4620 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4621 llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
Bill Wendlingb6f795e2012-02-16 01:13:30 +00004622 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
4623 llvm::MDNode::get(VMContext, Ops));
4624 }
4625 }
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004626
4627 // Indicate whether we're compiling this to run on a simulator.
4628 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Tim Northover756447a2015-10-30 16:30:36 +00004629 if ((Triple.isiOS() || Triple.isWatchOS()) &&
Bill Wendling1e60a2c2012-04-24 11:04:57 +00004630 (Triple.getArch() == llvm::Triple::x86 ||
4631 Triple.getArch() == llvm::Triple::x86_64))
4632 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
4633 eImageInfo_ImageIsSimulated);
Manman Ren96df0b32016-01-29 23:45:01 +00004634
4635 // Indicate whether we are generating class properties.
4636 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",
4637 eImageInfo_ClassProperties);
Daniel Dunbar3ad53482008-08-11 21:35:06 +00004638}
4639
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004640// struct objc_module {
4641// unsigned long version;
4642// unsigned long size;
4643// const char *name;
4644// Symtab symtab;
4645// };
4646
4647// FIXME: Get from somewhere
4648static const int ModuleVersion = 7;
4649
4650void CGObjCMac::EmitModuleInfo() {
Micah Villmowdd31ca12012-10-08 16:25:52 +00004651 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004652
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004653 llvm::Constant *Values[] = {
4654 llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
4655 llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
4656 // This used to be the filename, now it is unused. <rdr://4327263>
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004657 GetClassName(StringRef("")),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00004658 EmitModuleSymbols()
4659 };
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004660 CreateMetadataVar("OBJC_MODULES",
Owen Anderson0e0189d2009-07-27 22:29:56 +00004661 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
John McCall7f416cc2015-09-08 08:05:57 +00004662 "__OBJC,__module_info,regular,no_dead_strip",
4663 CGM.getPointerAlign(), true);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004664}
4665
4666llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004667 unsigned NumClasses = DefinedClasses.size();
4668 unsigned NumCategories = DefinedCategories.size();
4669
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004670 // Return null if no symbols were defined.
4671 if (!NumClasses && !NumCategories)
Owen Anderson0b75f232009-07-31 20:28:54 +00004672 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00004673
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004674 llvm::Constant *Values[5];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004675 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
Owen Anderson0b75f232009-07-31 20:28:54 +00004676 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00004677 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
4678 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004679
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004680 // The runtime expects exactly the list of defined classes followed
4681 // by the list of defined categories, in a single array.
Chris Lattner3def9ae2012-02-06 22:16:34 +00004682 SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004683 for (unsigned i=0; i<NumClasses; i++) {
4684 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
4685 assert(ID);
4686 if (ObjCImplementationDecl *IMP = ID->getImplementation())
4687 // We are implementing a weak imported interface. Give it external linkage
4688 if (ID->isWeakImported() && !IMP->isWeakImported())
4689 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
4690
Owen Andersonade90fd2009-07-29 18:54:39 +00004691 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004692 ObjCTypes.Int8PtrTy);
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00004693 }
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004694 for (unsigned i=0; i<NumCategories; i++)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004695 Symbols[NumClasses + i] =
Owen Andersonade90fd2009-07-29 18:54:39 +00004696 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
Daniel Dunbar938a77f2008-08-22 20:34:54 +00004697 ObjCTypes.Int8PtrTy);
4698
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004699 Values[4] =
Owen Anderson9793f0e2009-07-29 22:16:19 +00004700 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00004701 Symbols.size()),
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004702 Symbols);
4703
Chris Lattnere64d7ba2011-06-20 04:01:35 +00004704 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004705
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004706 llvm::GlobalVariable *GV = CreateMetadataVar(
John McCall7f416cc2015-09-08 08:05:57 +00004707 "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip",
4708 CGM.getPointerAlign(), true);
Owen Andersonade90fd2009-07-29 18:54:39 +00004709 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004710}
4711
John McCall882987f2013-02-28 19:01:20 +00004712llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
4713 IdentifierInfo *II) {
John McCall31168b02011-06-15 23:02:42 +00004714 LazySymbols.insert(II);
4715
4716 llvm::GlobalVariable *&Entry = ClassReferences[II];
4717
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004718 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004719 llvm::Constant *Casted =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004720 llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
John McCall31168b02011-06-15 23:02:42 +00004721 ObjCTypes.ClassPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004722 Entry = CreateMetadataVar(
4723 "OBJC_CLASS_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004724 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
4725 CGM.getPointerAlign(), true);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00004726 }
John McCall31168b02011-06-15 23:02:42 +00004727
John McCall7f416cc2015-09-08 08:05:57 +00004728 return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign());
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004729}
4730
John McCall882987f2013-02-28 19:01:20 +00004731llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00004732 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00004733 // If the class has the objc_runtime_visible attribute, we need to
4734 // use the Objective-C runtime to get the class.
4735 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
4736 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
4737
John McCall882987f2013-02-28 19:01:20 +00004738 return EmitClassRefFromId(CGF, ID->getIdentifier());
John McCall31168b02011-06-15 23:02:42 +00004739}
4740
John McCall882987f2013-02-28 19:01:20 +00004741llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00004742 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
John McCall882987f2013-02-28 19:01:20 +00004743 return EmitClassRefFromId(CGF, II);
John McCall31168b02011-06-15 23:02:42 +00004744}
4745
John McCall7f416cc2015-09-08 08:05:57 +00004746llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {
4747 return CGF.Builder.CreateLoad(EmitSelectorAddr(CGF, Sel));
4748}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004749
John McCall7f416cc2015-09-08 08:05:57 +00004750Address CGObjCMac::EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel) {
4751 CharUnits Align = CGF.getPointerAlign();
4752
4753 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004754 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004755 llvm::Constant *Casted =
Owen Andersonade90fd2009-07-29 18:54:39 +00004756 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004757 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004758 Entry = CreateMetadataVar(
4759 "OBJC_SELECTOR_REFERENCES_", Casted,
John McCall7f416cc2015-09-08 08:05:57 +00004760 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);
Michael Gottesman5c205962013-02-05 23:08:45 +00004761 Entry->setExternallyInitialized(true);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004762 }
4763
John McCall7f416cc2015-09-08 08:05:57 +00004764 return Address(Entry, Align);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00004765}
4766
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004767llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
4768 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
4769 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00004770 Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004771 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00004772}
4773
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004774llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
4775 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
4776 I = MethodDefinitions.find(MD);
4777 if (I != MethodDefinitions.end())
4778 return I->second;
4779
Craig Topper8a13c412014-05-21 05:09:00 +00004780 return nullptr;
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00004781}
4782
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004783/// GetIvarLayoutName - Returns a unique constant for the given
4784/// ivar layout bitmap.
4785llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004786 const ObjCCommonTypesHelper &ObjCTypes) {
Owen Anderson0b75f232009-07-31 20:28:54 +00004787 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian01dff422009-03-05 19:17:31 +00004788}
4789
John McCall3fd13f062015-10-21 18:06:47 +00004790void IvarLayoutBuilder::visitRecord(const RecordType *RT,
4791 CharUnits offset) {
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004792 const RecordDecl *RD = RT->getDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004793
John McCall3fd13f062015-10-21 18:06:47 +00004794 // If this is a union, remember that we had one, because it might mess
4795 // up the ordering of layout entries.
4796 if (RD->isUnion())
4797 IsDisordered = true;
4798
4799 const ASTRecordLayout *recLayout = nullptr;
4800 visitAggregate(RD->field_begin(), RD->field_end(), offset,
4801 [&](const FieldDecl *field) -> CharUnits {
4802 if (!recLayout)
4803 recLayout = &CGM.getContext().getASTRecordLayout(RD);
4804 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());
4805 return CGM.getContext().toCharUnitsFromBits(offsetInBits);
4806 });
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004807}
4808
John McCall3fd13f062015-10-21 18:06:47 +00004809template <class Iterator, class GetOffsetFn>
4810void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,
4811 CharUnits aggregateOffset,
4812 const GetOffsetFn &getOffset) {
4813 for (; begin != end; ++begin) {
4814 auto field = *begin;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004815
John McCall3fd13f062015-10-21 18:06:47 +00004816 // Skip over bitfields.
4817 if (field->isBitField()) {
4818 continue;
4819 }
4820
4821 // Compute the offset of the field within the aggregate.
4822 CharUnits fieldOffset = aggregateOffset + getOffset(field);
4823
4824 visitField(field, fieldOffset);
4825 }
4826}
4827
4828/// Collect layout information for the given fields into IvarsInfo.
4829void IvarLayoutBuilder::visitField(const FieldDecl *field,
4830 CharUnits fieldOffset) {
4831 QualType fieldType = field->getType();
4832
4833 // Drill down into arrays.
4834 uint64_t numElts = 1;
4835 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {
4836 numElts *= arrayType->getSize().getZExtValue();
4837 fieldType = arrayType->getElementType();
4838 }
4839
4840 assert(!fieldType->isArrayType() && "ivar of non-constant array type?");
4841
4842 // If we ended up with a zero-sized array, we've done what we can do within
4843 // the limits of this layout encoding.
4844 if (numElts == 0) return;
4845
4846 // Recurse if the base element type is a record type.
4847 if (auto recType = fieldType->getAs<RecordType>()) {
4848 size_t oldEnd = IvarsInfo.size();
4849
4850 visitRecord(recType, fieldOffset);
4851
4852 // If we have an array, replicate the first entry's layout information.
4853 auto numEltEntries = IvarsInfo.size() - oldEnd;
4854 if (numElts != 1 && numEltEntries != 0) {
4855 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);
4856 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {
4857 // Copy the last numEltEntries onto the end of the array, adjusting
4858 // each for the element size.
4859 for (size_t i = 0; i != numEltEntries; ++i) {
4860 auto firstEntry = IvarsInfo[oldEnd + i];
4861 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,
4862 firstEntry.SizeInWords));
4863 }
4864 }
4865 }
4866
Fariborz Jahanian524bb202009-03-10 16:22:08 +00004867 return;
Fariborz Jahanian3b0f8862009-03-11 00:07:04 +00004868 }
Daniel Dunbar15bd8882009-05-03 14:10:34 +00004869
John McCall3fd13f062015-10-21 18:06:47 +00004870 // Classify the element type.
4871 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00004872
John McCall3fd13f062015-10-21 18:06:47 +00004873 // If it matches what we're looking for, add an entry.
4874 if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
4875 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
4876 assert(CGM.getContext().getTypeSizeInChars(fieldType)
4877 == CGM.getPointerSize());
4878 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));
4879 }
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00004880}
4881
John McCall3fd13f062015-10-21 18:06:47 +00004882/// buildBitmap - This routine does the horsework of taking the offsets of
4883/// strong/weak references and creating a bitmap. The bitmap is also
4884/// returned in the given buffer, suitable for being passed to \c dump().
4885llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,
4886 llvm::SmallVectorImpl<unsigned char> &buffer) {
4887 // The bitmap is a series of skip/scan instructions, aligned to word
4888 // boundaries. The skip is performed first.
4889 const unsigned char MaxNibble = 0xF;
4890 const unsigned char SkipMask = 0xF0, SkipShift = 4;
4891 const unsigned char ScanMask = 0x0F, ScanShift = 0;
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00004892
John McCall3fd13f062015-10-21 18:06:47 +00004893 assert(!IvarsInfo.empty() && "generating bitmap for no data");
4894
4895 // Sort the ivar info on byte position in case we encounterred a
4896 // union nested in the ivar list.
4897 if (IsDisordered) {
4898 // This isn't a stable sort, but our algorithm should handle it fine.
4899 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
4900 } else {
Craig Toppera3467052016-01-03 19:43:20 +00004901 assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end()));
John McCall3fd13f062015-10-21 18:06:47 +00004902 }
4903 assert(IvarsInfo.back().Offset < InstanceEnd);
4904
4905 assert(buffer.empty());
4906
4907 // Skip the next N words.
4908 auto skip = [&](unsigned numWords) {
4909 assert(numWords > 0);
4910
4911 // Try to merge into the previous byte. Since scans happen second, we
4912 // can't do this if it includes a scan.
4913 if (!buffer.empty() && !(buffer.back() & ScanMask)) {
4914 unsigned lastSkip = buffer.back() >> SkipShift;
4915 if (lastSkip < MaxNibble) {
4916 unsigned claimed = std::min(MaxNibble - lastSkip, numWords);
4917 numWords -= claimed;
4918 lastSkip += claimed;
4919 buffer.back() = (lastSkip << SkipShift);
4920 }
4921 }
4922
4923 while (numWords >= MaxNibble) {
4924 buffer.push_back(MaxNibble << SkipShift);
4925 numWords -= MaxNibble;
4926 }
4927 if (numWords) {
4928 buffer.push_back(numWords << SkipShift);
4929 }
4930 };
4931
4932 // Scan the next N words.
4933 auto scan = [&](unsigned numWords) {
4934 assert(numWords > 0);
4935
4936 // Try to merge into the previous byte. Since scans happen second, we can
4937 // do this even if it includes a skip.
4938 if (!buffer.empty()) {
4939 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;
4940 if (lastScan < MaxNibble) {
4941 unsigned claimed = std::min(MaxNibble - lastScan, numWords);
4942 numWords -= claimed;
4943 lastScan += claimed;
4944 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);
4945 }
4946 }
4947
4948 while (numWords >= MaxNibble) {
4949 buffer.push_back(MaxNibble << ScanShift);
4950 numWords -= MaxNibble;
4951 }
4952 if (numWords) {
4953 buffer.push_back(numWords << ScanShift);
4954 }
4955 };
4956
4957 // One past the end of the last scan.
4958 unsigned endOfLastScanInWords = 0;
4959 const CharUnits WordSize = CGM.getPointerSize();
4960
4961 // Consider all the scan requests.
4962 for (auto &request : IvarsInfo) {
4963 CharUnits beginOfScan = request.Offset - InstanceBegin;
4964
4965 // Ignore scan requests that don't start at an even multiple of the
4966 // word size. We can't encode them.
4967 if ((beginOfScan % WordSize) != 0) continue;
4968
4969 // Ignore scan requests that start before the instance start.
4970 // This assumes that scans never span that boundary. The boundary
4971 // isn't the true start of the ivars, because in the fragile-ARC case
4972 // it's rounded up to word alignment, but the test above should leave
4973 // us ignoring that possibility.
4974 if (beginOfScan.isNegative()) {
4975 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);
4976 continue;
4977 }
4978
4979 unsigned beginOfScanInWords = beginOfScan / WordSize;
4980 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;
4981
4982 // If the scan starts some number of words after the last one ended,
4983 // skip forward.
4984 if (beginOfScanInWords > endOfLastScanInWords) {
4985 skip(beginOfScanInWords - endOfLastScanInWords);
4986
4987 // Otherwise, start scanning where the last left off.
4988 } else {
4989 beginOfScanInWords = endOfLastScanInWords;
4990
4991 // If that leaves us with nothing to scan, ignore this request.
4992 if (beginOfScanInWords >= endOfScanInWords) continue;
4993 }
4994
4995 // Scan to the end of the request.
4996 assert(beginOfScanInWords < endOfScanInWords);
4997 scan(endOfScanInWords - beginOfScanInWords);
4998 endOfLastScanInWords = endOfScanInWords;
4999 }
5000
John McCallf5ea0722015-10-29 23:36:14 +00005001 if (buffer.empty())
5002 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
5003
John McCall3fd13f062015-10-21 18:06:47 +00005004 // For GC layouts, emit a skip to the end of the allocation so that we
5005 // have precise information about the entire thing. This isn't useful
5006 // or necessary for the ARC-style layout strings.
5007 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
5008 unsigned lastOffsetInWords =
5009 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;
5010 if (lastOffsetInWords > endOfLastScanInWords) {
5011 skip(lastOffsetInWords - endOfLastScanInWords);
5012 }
5013 }
5014
5015 // Null terminate the string.
5016 buffer.push_back(0);
5017
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005018 auto *Entry = CGObjC.CreateCStringLiteral(
5019 reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName);
John McCall3fd13f062015-10-21 18:06:47 +00005020 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005021}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005022
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005023/// BuildIvarLayout - Builds ivar layout bitmap for the class
5024/// implementation for the __strong or __weak case.
5025/// The layout map displays which words in ivar list must be skipped
5026/// and which must be scanned by GC (see below). String is built of bytes.
5027/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
5028/// of words to skip and right nibble is count of words to scan. So, each
5029/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
5030/// represented by a 0x00 byte which also ends the string.
5031/// 1. when ForStrongLayout is true, following ivars are scanned:
5032/// - id, Class
5033/// - object *
5034/// - __strong anything
5035///
5036/// 2. When ForStrongLayout is false, following ivars are scanned:
5037/// - __weak anything
5038///
John McCall3fd13f062015-10-21 18:06:47 +00005039llvm::Constant *
5040CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,
5041 CharUnits beginOffset, CharUnits endOffset,
John McCall460ce582015-10-22 18:38:17 +00005042 bool ForStrongLayout, bool HasMRCWeakIvars) {
5043 // If this is MRC, and we're either building a strong layout or there
5044 // are no weak ivars, bail out early.
Chris Lattnerece04092012-02-07 00:39:47 +00005045 llvm::Type *PtrTy = CGM.Int8PtrTy;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005046 if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
John McCall460ce582015-10-22 18:38:17 +00005047 !CGM.getLangOpts().ObjCAutoRefCount &&
5048 (ForStrongLayout || !HasMRCWeakIvars))
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005049 return llvm::Constant::getNullValue(PtrTy);
5050
Jordy Rosea91768e2011-07-22 02:08:32 +00005051 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
John McCall3fd13f062015-10-21 18:06:47 +00005052 SmallVector<const ObjCIvarDecl*, 32> ivars;
5053
5054 // GC layout strings include the complete object layout, possibly
5055 // inaccurately in the non-fragile ABI; the runtime knows how to fix this
5056 // up.
5057 //
5058 // ARC layout strings only include the class's ivars. In non-fragile
John McCallf5ea0722015-10-29 23:36:14 +00005059 // runtimes, that means starting at InstanceStart, rounded up to word
5060 // alignment. In fragile runtimes, there's no InstanceStart, so it means
John McCalld80218f2015-11-19 02:27:55 +00005061 // starting at the offset of the first ivar, rounded up to word alignment.
John McCall460ce582015-10-22 18:38:17 +00005062 //
5063 // MRC weak layout strings follow the ARC style.
John McCall3fd13f062015-10-21 18:06:47 +00005064 CharUnits baseOffset;
John McCall460ce582015-10-22 18:38:17 +00005065 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005066 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005067 IVD; IVD = IVD->getNextIvar())
John McCall3fd13f062015-10-21 18:06:47 +00005068 ivars.push_back(IVD);
5069
5070 if (isNonFragileABI()) {
5071 baseOffset = beginOffset; // InstanceStart
John McCalld80218f2015-11-19 02:27:55 +00005072 } else if (!ivars.empty()) {
5073 baseOffset =
5074 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));
John McCall3fd13f062015-10-21 18:06:47 +00005075 } else {
5076 baseOffset = CharUnits::Zero();
5077 }
John McCallf5ea0722015-10-29 23:36:14 +00005078
Rui Ueyama83aa9792016-01-14 21:00:27 +00005079 baseOffset = baseOffset.alignTo(CGM.getPointerAlign());
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005080 }
5081 else {
John McCall3fd13f062015-10-21 18:06:47 +00005082 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005083
John McCall3fd13f062015-10-21 18:06:47 +00005084 baseOffset = CharUnits::Zero();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00005085 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005086
John McCall3fd13f062015-10-21 18:06:47 +00005087 if (ivars.empty())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005088 return llvm::Constant::getNullValue(PtrTy);
5089
John McCall3fd13f062015-10-21 18:06:47 +00005090 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005091
John McCall3fd13f062015-10-21 18:06:47 +00005092 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),
5093 [&](const ObjCIvarDecl *ivar) -> CharUnits {
5094 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));
5095 });
5096
5097 if (!builder.hasBitmapData())
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005098 return llvm::Constant::getNullValue(PtrTy);
John McCall3fd13f062015-10-21 18:06:47 +00005099
5100 llvm::SmallVector<unsigned char, 4> buffer;
5101 llvm::Constant *C = builder.buildBitmap(*this, buffer);
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005102
John McCallf5ea0722015-10-29 23:36:14 +00005103 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005104 printf("\n%s ivar layout for class '%s': ",
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005105 ForStrongLayout ? "strong" : "weak",
Ben Langmuire013bdc2014-07-11 00:43:47 +00005106 OMD->getClassInterface()->getName().str().c_str());
John McCall3fd13f062015-10-21 18:06:47 +00005107 builder.dump(buffer);
Fariborz Jahanian80c9ce22009-04-20 22:03:45 +00005108 }
Fariborz Jahanian9659f6b2010-08-04 23:55:24 +00005109 return C;
Fariborz Jahanianc559f3f2009-03-05 22:39:55 +00005110}
5111
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005112llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005113 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
Chris Lattner3def9ae2012-02-06 22:16:34 +00005114 // FIXME: Avoid std::string in "Sel.getAsString()"
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005115 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005116 Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName);
Owen Anderson170229f2009-07-14 23:10:40 +00005117 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005118}
5119
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005120// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005121llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005122 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
5123}
5124
Daniel Dunbarf5c18462009-04-20 06:54:31 +00005125llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005126 std::string TypeStr;
5127 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
5128
5129 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005130 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005131 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005132 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbarcb515c82008-08-12 03:39:23 +00005133}
5134
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005135llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
5136 bool Extended) {
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005137 std::string TypeStr;
Bill Wendlinge22bef72012-02-09 22:45:21 +00005138 if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
Craig Topper8a13c412014-05-21 05:09:00 +00005139 return nullptr;
Devang Patel4b6e4bb2009-03-04 18:21:39 +00005140
5141 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar3241fae2009-04-14 23:14:47 +00005142 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005143 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);
Owen Anderson170229f2009-07-14 23:10:40 +00005144 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005145}
5146
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005147// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005148llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005149 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005150 if (!Entry)
Saleem Abdulrasool271106c2016-09-16 23:41:13 +00005151 Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName);
Owen Anderson170229f2009-07-14 23:10:40 +00005152 return getConstantGEP(VMContext, Entry, 0, 0);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005153}
5154
5155// FIXME: Merge into a single cstring creation function.
Daniel Dunbar4932b362008-08-28 04:38:10 +00005156// FIXME: This Decl should be more precise.
Daniel Dunbarc2d4b622009-03-09 21:49:58 +00005157llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005158CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
5159 const Decl *Container) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005160 std::string TypeStr;
5161 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbar80a840b2008-08-23 00:19:03 +00005162 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
5163}
5164
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005165void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian0b1ccdc2009-01-21 23:34:32 +00005166 const ObjCContainerDecl *CD,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005167 SmallVectorImpl<char> &Name) {
Daniel Dunbard2386812009-10-19 01:21:19 +00005168 llvm::raw_svector_ostream OS(Name);
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00005169 assert (CD && "Missing container decl in GetNameForMethod");
Daniel Dunbard2386812009-10-19 01:21:19 +00005170 OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
5171 << '[' << CD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005172 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbard2386812009-10-19 01:21:19 +00005173 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +00005174 OS << '(' << *CID << ')';
Daniel Dunbard2386812009-10-19 01:21:19 +00005175 OS << ' ' << D->getSelector().getAsString() << ']';
Daniel Dunbara94ecd22008-08-16 03:19:19 +00005176}
5177
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005178void CGObjCMac::FinishModule() {
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005179 EmitModuleInfo();
5180
Daniel Dunbarc475d422008-10-29 22:36:39 +00005181 // Emit the dummy bodies for any protocols which were referenced but
5182 // never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005183 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
Chris Lattnerf56501c2009-07-17 23:57:13 +00005184 I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
5185 if (I->second->hasInitializer())
Daniel Dunbarc475d422008-10-29 22:36:39 +00005186 continue;
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005187
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005188 llvm::Constant *Values[5];
Owen Anderson0b75f232009-07-31 20:28:54 +00005189 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005190 Values[1] = GetClassName(I->first->getName());
Owen Anderson0b75f232009-07-31 20:28:54 +00005191 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005192 Values[3] = Values[4] =
Owen Anderson0b75f232009-07-31 20:28:54 +00005193 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00005194 I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
Daniel Dunbarc475d422008-10-29 22:36:39 +00005195 Values));
Rafael Espindola060062a2014-03-06 22:15:10 +00005196 CGM.addCompilerUsedGlobal(I->second);
Daniel Dunbarc475d422008-10-29 22:36:39 +00005197 }
5198
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005199 // Add assembler directives to add lazy undefined symbol references
5200 // for classes which are referenced but not defined. This is
5201 // important for correct linker interaction.
Daniel Dunbard027a922009-09-07 00:20:42 +00005202 //
5203 // FIXME: It would be nice if we had an LLVM construct for this.
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005204 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&
5205 CGM.getTriple().isOSBinFormatMachO()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005206 SmallString<256> Asm;
Daniel Dunbard027a922009-09-07 00:20:42 +00005207 Asm += CGM.getModule().getModuleInlineAsm();
5208 if (!Asm.empty() && Asm.back() != '\n')
5209 Asm += '\n';
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005210
Daniel Dunbard027a922009-09-07 00:20:42 +00005211 llvm::raw_svector_ostream OS(Asm);
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005212 for (const auto *Sym : DefinedSymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005213 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"
5214 << "\t.globl .objc_class_name_" << Sym->getName() << "\n";
Saleem Abdulrasool39217d42016-09-16 14:24:26 +00005215 for (const auto *Sym : LazySymbols)
Saleem Abdulrasool62c07eb2016-09-12 21:15:23 +00005216 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";
5217 for (const auto &Category : DefinedCategoryNames)
5218 OS << "\t.objc_category_name_" << Category << "=0\n"
5219 << "\t.globl .objc_category_name_" << Category << "\n";
Fariborz Jahanian9adb2e62010-06-21 22:05:18 +00005220
Daniel Dunbard027a922009-09-07 00:20:42 +00005221 CGM.getModule().setModuleInlineAsm(OS.str());
Daniel Dunbarc61d0e92008-08-25 06:02:07 +00005222 }
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005223}
5224
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005225CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00005226 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),
5227 ObjCEmptyVtableVar(nullptr) {
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005228 ObjCABI = 2;
5229}
5230
Daniel Dunbar3ad53482008-08-11 21:35:06 +00005231/* *** */
5232
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005233ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
Craig Topper8a13c412014-05-21 05:09:00 +00005234 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
Douglas Gregora95f9aa2012-01-17 23:38:32 +00005235{
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005236 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5237 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005238
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005239 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005240 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005241 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00005242 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Chris Lattnerece04092012-02-07 00:39:47 +00005243 Int8PtrTy = CGM.Int8PtrTy;
5244 Int8PtrPtrTy = CGM.Int8PtrPtrTy;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005245
Tim Northover238b5082014-03-29 13:42:40 +00005246 // arm64 targets use "int" ivar offset variables. All others,
5247 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
Tim Northover40956e62014-07-23 12:32:58 +00005248 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
Tim Northover238b5082014-03-29 13:42:40 +00005249 IvarOffsetVarTy = IntTy;
5250 else
5251 IvarOffsetVarTy = LongTy;
5252
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005253 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00005254 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005255 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005256
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005257 // I'm not sure I like this. The implicit coordination is a bit
5258 // gross. We should solve this in a reasonable fashion because this
5259 // is a pretty common task (match some runtime data structure with
5260 // an LLVM data structure).
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005261
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005262 // FIXME: This is leaked.
5263 // FIXME: Merge with rewriter code?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005264
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005265 // struct _objc_super {
5266 // id self;
5267 // Class cls;
5268 // }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005269 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005270 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005271 SourceLocation(), SourceLocation(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005272 &Ctx.Idents.get("_objc_super"));
Craig Topper8a13c412014-05-21 05:09:00 +00005273 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5274 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
5275 false, ICIS_NoInit));
5276 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5277 nullptr, Ctx.getObjCClassType(), nullptr,
5278 nullptr, false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005279 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005280
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005281 SuperCTy = Ctx.getTagDeclType(RD);
5282 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005283
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005284 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005285 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
5286
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005287 // struct _prop_t {
5288 // char *name;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005289 // char *attributes;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005290 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005291 PropertyTy = llvm::StructType::create("struct._prop_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005292 Int8PtrTy, Int8PtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005293
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005294 // struct _prop_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005295 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005296 // uint32_t count_of_properties;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005297 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005298 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005299 PropertyListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005300 llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005301 llvm::ArrayType::get(PropertyTy, 0), nullptr);
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005302 // struct _prop_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005303 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005304
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005305 // struct _objc_method {
5306 // SEL _cmd;
5307 // char *method_type;
5308 // char *_imp;
5309 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005310 MethodTy = llvm::StructType::create("struct._objc_method",
5311 SelectorPtrTy, Int8PtrTy, Int8PtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005312 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005313
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005314 // struct _objc_cache *
Chris Lattner5ec04a52011-08-12 17:43:31 +00005315 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005316 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005317}
Daniel Dunbar7bd00bd2008-08-12 06:48:42 +00005318
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005319ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005320 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005321 // struct _objc_method_description {
5322 // SEL name;
5323 // char *types;
5324 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005325 MethodDescriptionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005326 llvm::StructType::create("struct._objc_method_description",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005327 SelectorPtrTy, Int8PtrTy, nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005328
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005329 // struct _objc_method_description_list {
5330 // int count;
5331 // struct _objc_method_description[1];
5332 // }
Reid Kleckneree7cf842014-12-01 22:02:27 +00005333 MethodDescriptionListTy = llvm::StructType::create(
5334 "struct._objc_method_description_list", IntTy,
5335 llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005336
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005337 // struct _objc_method_description_list *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005338 MethodDescriptionListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005339 llvm::PointerType::getUnqual(MethodDescriptionListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005340
Daniel Dunbarb036db82008-08-13 03:21:16 +00005341 // Protocol description structures
5342
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005343 // struct _objc_protocol_extension {
5344 // uint32_t size; // sizeof(struct _objc_protocol_extension)
5345 // struct _objc_method_description_list *optional_instance_methods;
5346 // struct _objc_method_description_list *optional_class_methods;
5347 // struct _objc_property_list *instance_properties;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005348 // const char ** extendedMethodTypes;
Manman Rence7bff52016-01-29 23:46:55 +00005349 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005350 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005351 ProtocolExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005352 llvm::StructType::create("struct._objc_protocol_extension",
5353 IntTy, MethodDescriptionListPtrTy,
5354 MethodDescriptionListPtrTy, PropertyListPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005355 Int8PtrPtrTy, PropertyListPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005356
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005357 // struct _objc_protocol_extension *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005358 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005359
Daniel Dunbarc475d422008-10-29 22:36:39 +00005360 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarb036db82008-08-13 03:21:16 +00005361
Chris Lattnera5f58b02011-07-09 17:41:47 +00005362 ProtocolTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005363 llvm::StructType::create(VMContext, "struct._objc_protocol");
Daniel Dunbarb036db82008-08-13 03:21:16 +00005364
Chris Lattnera5f58b02011-07-09 17:41:47 +00005365 ProtocolListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005366 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005367 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
Fariborz Jahanian279eda62009-01-21 22:04:16 +00005368 LongTy,
Chris Lattnera5f58b02011-07-09 17:41:47 +00005369 llvm::ArrayType::get(ProtocolTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005370 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005371
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005372 // struct _objc_protocol {
5373 // struct _objc_protocol_extension *isa;
5374 // char *protocol_name;
5375 // struct _objc_protocol **_objc_protocol_list;
5376 // struct _objc_method_description_list *instance_methods;
5377 // struct _objc_method_description_list *class_methods;
5378 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005379 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
5380 llvm::PointerType::getUnqual(ProtocolListTy),
5381 MethodDescriptionListPtrTy,
5382 MethodDescriptionListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005383 nullptr);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005384
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005385 // struct _objc_protocol_list *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005386 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
Daniel Dunbarb036db82008-08-13 03:21:16 +00005387
Owen Anderson9793f0e2009-07-29 22:16:19 +00005388 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005389
5390 // Class description structures
5391
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005392 // struct _objc_ivar {
5393 // char *ivar_name;
5394 // char *ivar_type;
5395 // int ivar_offset;
5396 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005397 IvarTy = llvm::StructType::create("struct._objc_ivar",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005398 Int8PtrTy, Int8PtrTy, IntTy, nullptr);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005399
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005400 // struct _objc_ivar_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005401 IvarListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005402 llvm::StructType::create(VMContext, "struct._objc_ivar_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005403 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005404
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005405 // struct _objc_method_list *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005406 MethodListTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005407 llvm::StructType::create(VMContext, "struct._objc_method_list");
Owen Anderson9793f0e2009-07-29 22:16:19 +00005408 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005409
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005410 // struct _objc_class_extension *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005411 ClassExtensionTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005412 llvm::StructType::create("struct._objc_class_extension",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005413 IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005414 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005415
Chris Lattner5ec04a52011-08-12 17:43:31 +00005416 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005417
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005418 // struct _objc_class {
5419 // Class isa;
5420 // Class super_class;
5421 // char *name;
5422 // long version;
5423 // long info;
5424 // long instance_size;
5425 // struct _objc_ivar_list *ivars;
5426 // struct _objc_method_list *methods;
5427 // struct _objc_cache *cache;
5428 // struct _objc_protocol_list *protocols;
5429 // char *ivar_layout;
5430 // struct _objc_class_ext *ext;
5431 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005432 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
5433 llvm::PointerType::getUnqual(ClassTy),
5434 Int8PtrTy,
5435 LongTy,
5436 LongTy,
5437 LongTy,
5438 IvarListPtrTy,
5439 MethodListPtrTy,
5440 CachePtrTy,
5441 ProtocolListPtrTy,
5442 Int8PtrTy,
5443 ClassExtensionPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005444 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005445
Owen Anderson9793f0e2009-07-29 22:16:19 +00005446 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005447
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005448 // struct _objc_category {
5449 // char *category_name;
5450 // char *class_name;
5451 // struct _objc_method_list *instance_method;
5452 // struct _objc_method_list *class_method;
Manman Renb3736772016-01-25 22:37:47 +00005453 // struct _objc_protocol_list *protocols;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005454 // uint32_t size; // sizeof(struct _objc_category)
5455 // struct _objc_property_list *instance_properties;// category's @property
Manman Ren96df0b32016-01-29 23:45:01 +00005456 // struct _objc_property_list *class_properties;
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005457 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005458 CategoryTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005459 llvm::StructType::create("struct._objc_category",
5460 Int8PtrTy, Int8PtrTy, MethodListPtrTy,
5461 MethodListPtrTy, ProtocolListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005462 IntTy, PropertyListPtrTy, PropertyListPtrTy,
5463 nullptr);
Daniel Dunbar938a77f2008-08-22 20:34:54 +00005464
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005465 // Global metadata structures
5466
Fariborz Jahanian4b4c8262009-01-21 00:39:53 +00005467 // struct _objc_symtab {
5468 // long sel_ref_cnt;
5469 // SEL *refs;
5470 // short cls_def_cnt;
5471 // short cat_def_cnt;
5472 // char *defs[cls_def_cnt + cat_def_cnt];
5473 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005474 SymtabTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005475 llvm::StructType::create("struct._objc_symtab",
5476 LongTy, SelectorPtrTy, ShortTy, ShortTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005477 llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005478 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
Daniel Dunbar22d82ed2008-08-21 04:36:09 +00005479
Fariborz Jahanianeee54df2009-01-22 00:37:21 +00005480 // struct _objc_module {
5481 // long version;
5482 // long size; // sizeof(struct _objc_module)
5483 // char *name;
5484 // struct _objc_symtab* symtab;
5485 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005486 ModuleTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005487 llvm::StructType::create("struct._objc_module",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005488 LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
Daniel Dunbar97ff50d2008-08-23 09:25:55 +00005489
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005490
Mike Stump18bb9282009-05-16 07:57:57 +00005491 // FIXME: This is the size of the setjmp buffer and should be target
5492 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson9ff22482008-09-09 10:10:21 +00005493 uint64_t SetJmpBufferSize = 18;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005494
Anders Carlsson9ff22482008-09-09 10:10:21 +00005495 // Exceptions
Chris Lattnerece04092012-02-07 00:39:47 +00005496 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005497
5498 ExceptionDataTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005499 llvm::StructType::create("struct._objc_exception_data",
Chris Lattnerece04092012-02-07 00:39:47 +00005500 llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005501 StackPtrTy, nullptr);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005502}
5503
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005504ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Mike Stump11289f42009-09-09 15:08:12 +00005505 : ObjCCommonTypesHelper(cgm) {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005506 // struct _method_list_t {
5507 // uint32_t entsize; // sizeof(struct _objc_method)
5508 // uint32_t method_count;
5509 // struct _objc_method method_list[method_count];
5510 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005511 MethodListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005512 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005513 llvm::ArrayType::get(MethodTy, 0), nullptr);
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005514 // struct method_list_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005515 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005516
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005517 // struct _protocol_t {
5518 // id isa; // NULL
5519 // const char * const protocol_name;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005520 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005521 // const struct method_list_t * const instance_methods;
5522 // const struct method_list_t * const class_methods;
5523 // const struct method_list_t *optionalInstanceMethods;
5524 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005525 // const struct _prop_list_t * properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005526 // const uint32_t size; // sizeof(struct _protocol_t)
5527 // const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005528 // const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00005529 // const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00005530 // const struct _prop_list_t * class_properties;
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005531 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005532
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005533 // Holder for struct _protocol_list_t *
Chris Lattnera5f58b02011-07-09 17:41:47 +00005534 ProtocolListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005535 llvm::StructType::create(VMContext, "struct._objc_protocol_list");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005536
Chris Lattnera5f58b02011-07-09 17:41:47 +00005537 ProtocolnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005538 llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
5539 llvm::PointerType::getUnqual(ProtocolListnfABITy),
5540 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
5541 MethodListnfABIPtrTy, MethodListnfABIPtrTy,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005542 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
Manman Rence7bff52016-01-29 23:46:55 +00005543 Int8PtrTy, PropertyListPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005544 nullptr);
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005545
5546 // struct _protocol_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005547 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005548
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005549 // struct _protocol_list_t {
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005550 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar8de90f02009-02-15 07:36:20 +00005551 // struct _protocol_t *[protocol_count];
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005552 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005553 ProtocolListnfABITy->setBody(LongTy,
5554 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005555 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005556
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005557 // struct _objc_protocol_list*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005558 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005559
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005560 // struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00005561 // unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005562 // char *name;
5563 // char *type;
5564 // uint32_t alignment;
5565 // uint32_t size;
5566 // }
Tim Northover238b5082014-03-29 13:42:40 +00005567 IvarnfABITy = llvm::StructType::create(
5568 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005569 Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005570
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005571 // struct _ivar_list_t {
5572 // uint32 entsize; // sizeof(struct _ivar_t)
5573 // uint32 count;
5574 // struct _iver_t list[count];
5575 // }
Chris Lattnera5f58b02011-07-09 17:41:47 +00005576 IvarListnfABITy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005577 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005578 llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005579
Owen Anderson9793f0e2009-07-29 22:16:19 +00005580 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005581
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005582 // struct _class_ro_t {
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +00005583 // uint32_t const flags;
5584 // uint32_t const instanceStart;
5585 // uint32_t const instanceSize;
5586 // uint32_t const reserved; // only when building for 64bit targets
5587 // const uint8_t * const ivarLayout;
5588 // const char *const name;
5589 // const struct _method_list_t * const baseMethods;
5590 // const struct _objc_protocol_list *const baseProtocols;
5591 // const struct _ivar_list_t *const ivars;
5592 // const uint8_t * const weakIvarLayout;
5593 // const struct _prop_list_t * const properties;
5594 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005595
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005596 // FIXME. Add 'reserved' field in 64bit abi mode!
Chris Lattner5ec04a52011-08-12 17:43:31 +00005597 ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
5598 IntTy, IntTy, IntTy, Int8PtrTy,
5599 Int8PtrTy, MethodListnfABIPtrTy,
5600 ProtocolListnfABIPtrTy,
5601 IvarListnfABIPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005602 Int8PtrTy, PropertyListPtrTy,
5603 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005604
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005605 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
Chris Lattnera5f58b02011-07-09 17:41:47 +00005606 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
John McCall9dc0db22011-05-15 01:53:33 +00005607 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
5608 ->getPointerTo();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005609
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005610 // struct _class_t {
5611 // struct _class_t *isa;
5612 // struct _class_t * const superclass;
5613 // void *cache;
5614 // IMP *vtable;
5615 // struct class_ro_t *ro;
5616 // }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005617
Chris Lattner5ec04a52011-08-12 17:43:31 +00005618 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
Chris Lattnera5f58b02011-07-09 17:41:47 +00005619 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
5620 llvm::PointerType::getUnqual(ClassnfABITy),
5621 CachePtrTy,
5622 llvm::PointerType::getUnqual(ImpnfABITy),
5623 llvm::PointerType::getUnqual(ClassRonfABITy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005624 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005625
Fariborz Jahanian71394042009-01-23 23:53:38 +00005626 // LLVM for struct _class_t *
Owen Anderson9793f0e2009-07-29 22:16:19 +00005627 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005628
Fariborz Jahanian0232c052009-01-23 01:46:23 +00005629 // struct _category_t {
5630 // const char * const name;
5631 // struct _class_t *const cls;
5632 // const struct _method_list_t * const instance_methods;
5633 // const struct _method_list_t * const class_methods;
5634 // const struct _protocol_list_t * const protocols;
5635 // const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00005636 // const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00005637 // const uint32_t size;
Fariborz Jahanian5a63e4c2009-01-23 17:41:22 +00005638 // }
Chris Lattner5ec04a52011-08-12 17:43:31 +00005639 CategorynfABITy = llvm::StructType::create("struct._category_t",
5640 Int8PtrTy, ClassnfABIPtrTy,
5641 MethodListnfABIPtrTy,
5642 MethodListnfABIPtrTy,
5643 ProtocolListnfABIPtrTy,
5644 PropertyListPtrTy,
Manman Ren96df0b32016-01-29 23:45:01 +00005645 PropertyListPtrTy,
Manman Ren42ff3902016-02-24 17:49:50 +00005646 IntTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +00005647 nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005648
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005649 // New types for nonfragile abi messaging.
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005650 CodeGen::CodeGenTypes &Types = CGM.getTypes();
5651 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005652
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005653 // MessageRefTy - LLVM for:
5654 // struct _message_ref_t {
5655 // IMP messenger;
5656 // SEL name;
5657 // };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005658
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005659 // First the clang type for struct _message_ref_t
Abramo Bagnara6150c882010-05-11 21:36:43 +00005660 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
Daniel Dunbar0c005372010-04-29 16:29:11 +00005661 Ctx.getTranslationUnitDecl(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005662 SourceLocation(), SourceLocation(),
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005663 &Ctx.Idents.get("_message_ref_t"));
Craig Topper8a13c412014-05-21 05:09:00 +00005664 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5665 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
Richard Smith2b013182012-06-10 03:12:00 +00005666 ICIS_NoInit));
Craig Topper8a13c412014-05-21 05:09:00 +00005667 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
5668 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
5669 false, ICIS_NoInit));
Douglas Gregord5058122010-02-11 01:19:42 +00005670 RD->completeDefinition();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005671
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00005672 MessageRefCTy = Ctx.getTagDeclType(RD);
5673 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
5674 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005675
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005676 // MessageRefPtrTy - LLVM for struct _message_ref_t*
Owen Anderson9793f0e2009-07-29 22:16:19 +00005677 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005678
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005679 // SuperMessageRefTy - LLVM for:
5680 // struct _super_message_ref_t {
5681 // SUPER_IMP messenger;
5682 // SEL name;
5683 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005684 SuperMessageRefTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005685 llvm::StructType::create("struct._super_message_ref_t",
Reid Kleckneree7cf842014-12-01 22:02:27 +00005686 ImpnfABITy, SelectorPtrTy, nullptr);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005687
Fariborz Jahanian82c72e12009-02-03 23:49:23 +00005688 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005689 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
Fariborz Jahanian0a3cfcc2011-06-22 20:21:51 +00005690
Daniel Dunbarb1559a42009-03-01 04:46:24 +00005691
5692 // struct objc_typeinfo {
5693 // const void** vtable; // objc_ehtype_vtable + 2
5694 // const char* name; // c++ typeinfo string
5695 // Class cls;
5696 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +00005697 EHTypeTy =
Chris Lattner5ec04a52011-08-12 17:43:31 +00005698 llvm::StructType::create("struct._objc_typeinfo",
5699 llvm::PointerType::getUnqual(Int8PtrTy),
Reid Kleckneree7cf842014-12-01 22:02:27 +00005700 Int8PtrTy, ClassnfABIPtrTy, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00005701 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00005702}
5703
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005704llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
Fariborz Jahanian71394042009-01-23 23:53:38 +00005705 FinishNonFragileABIModule();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005706
Craig Topper8a13c412014-05-21 05:09:00 +00005707 return nullptr;
Fariborz Jahanian71394042009-01-23 23:53:38 +00005708}
5709
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00005710void CGObjCNonFragileABIMac::AddModuleClassList(
5711 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,
5712 StringRef SectionName) {
Daniel Dunbar19573e72009-05-15 21:48:48 +00005713 unsigned NumClasses = Container.size();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005714
Daniel Dunbar19573e72009-05-15 21:48:48 +00005715 if (!NumClasses)
5716 return;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005717
Chris Lattner3def9ae2012-02-06 22:16:34 +00005718 SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005719 for (unsigned i=0; i<NumClasses; i++)
Owen Andersonade90fd2009-07-29 18:54:39 +00005720 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
Daniel Dunbar19573e72009-05-15 21:48:48 +00005721 ObjCTypes.Int8PtrTy);
Chris Lattner3def9ae2012-02-06 22:16:34 +00005722 llvm::Constant *Init =
Owen Anderson9793f0e2009-07-29 22:16:19 +00005723 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Chris Lattner3def9ae2012-02-06 22:16:34 +00005724 Symbols.size()),
Daniel Dunbar19573e72009-05-15 21:48:48 +00005725 Symbols);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005726
Daniel Dunbar19573e72009-05-15 21:48:48 +00005727 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00005728 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005729 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar19573e72009-05-15 21:48:48 +00005730 Init,
Owen Andersonc10c8d32009-07-08 19:05:04 +00005731 SymbolName);
Micah Villmowdd31ca12012-10-08 16:25:52 +00005732 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Daniel Dunbar19573e72009-05-15 21:48:48 +00005733 GV->setSection(SectionName);
Rafael Espindola060062a2014-03-06 22:15:10 +00005734 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar19573e72009-05-15 21:48:48 +00005735}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005736
Fariborz Jahanian71394042009-01-23 23:53:38 +00005737void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
5738 // nonfragile abi has no module definition.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005739
Daniel Dunbar19573e72009-05-15 21:48:48 +00005740 // Build list of all implemented class addresses in array
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005741 // L_OBJC_LABEL_CLASS_$.
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005742
5743 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
5744 const ObjCInterfaceDecl *ID = ImplementedClasses[i];
5745 assert(ID);
5746 if (ObjCImplementationDecl *IMP = ID->getImplementation())
5747 // We are implementing a weak imported interface. Give it external linkage
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005748 if (ID->isWeakImported() && !IMP->isWeakImported()) {
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005749 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Fariborz Jahanianbc94c942014-07-15 17:14:34 +00005750 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
5751 }
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00005752 }
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005753
5754 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005755 "__DATA, __objc_classlist, regular, no_dead_strip");
Rafael Espindola554256c2014-02-26 22:25:45 +00005756
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005757 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005758 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005759
Fariborz Jahanian279abd32009-01-30 20:55:31 +00005760 // Build list of all implemented category addresses in array
5761 // L_OBJC_LABEL_CATEGORY_$.
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005762 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
Daniel Dunbar19573e72009-05-15 21:48:48 +00005763 "__DATA, __objc_catlist, regular, no_dead_strip");
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00005764 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005765 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005766
Daniel Dunbar5e639272010-04-25 20:39:01 +00005767 EmitImageInfo();
Fariborz Jahanian71394042009-01-23 23:53:38 +00005768}
5769
John McCall9e8bb002011-05-14 03:10:52 +00005770/// isVTableDispatchedSelector - Returns true if SEL is not in the list of
5771/// VTableDispatchMethods; false otherwise. What this means is that
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005772/// except for the 19 selectors in the list, we generate 32bit-style
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005773/// message dispatch call for all the rest.
John McCall9e8bb002011-05-14 03:10:52 +00005774bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
5775 // At various points we've experimented with using vtable-based
5776 // dispatch for all methods.
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005777 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005778 case CodeGenOptions::Legacy:
Fariborz Jahaniandfb39832010-04-19 17:53:30 +00005779 return false;
John McCall9e8bb002011-05-14 03:10:52 +00005780 case CodeGenOptions::NonLegacy:
5781 return true;
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005782 case CodeGenOptions::Mixed:
5783 break;
5784 }
5785
5786 // If so, see whether this selector is in the white-list of things which must
5787 // use the new dispatch convention. We lazily build a dense set for this.
John McCall9e8bb002011-05-14 03:10:52 +00005788 if (VTableDispatchMethods.empty()) {
5789 VTableDispatchMethods.insert(GetNullarySelector("alloc"));
5790 VTableDispatchMethods.insert(GetNullarySelector("class"));
5791 VTableDispatchMethods.insert(GetNullarySelector("self"));
5792 VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
5793 VTableDispatchMethods.insert(GetNullarySelector("length"));
5794 VTableDispatchMethods.insert(GetNullarySelector("count"));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005795
John McCall9e8bb002011-05-14 03:10:52 +00005796 // These are vtable-based if GC is disabled.
5797 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005798 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
John McCall9e8bb002011-05-14 03:10:52 +00005799 VTableDispatchMethods.insert(GetNullarySelector("retain"));
5800 VTableDispatchMethods.insert(GetNullarySelector("release"));
5801 VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
5802 }
5803
5804 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
5805 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
5806 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
5807 VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
5808 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
5809 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
5810 VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
5811
5812 // These are vtable-based if GC is enabled.
5813 // Optimistically use vtable dispatch for hybrid compiles.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005814 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
John McCall9e8bb002011-05-14 03:10:52 +00005815 VTableDispatchMethods.insert(GetNullarySelector("hash"));
5816 VTableDispatchMethods.insert(GetUnarySelector("addObject"));
5817
5818 // "countByEnumeratingWithState:objects:count"
5819 IdentifierInfo *KeyIdents[] = {
5820 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
5821 &CGM.getContext().Idents.get("objects"),
5822 &CGM.getContext().Idents.get("count")
5823 };
5824 VTableDispatchMethods.insert(
5825 CGM.getContext().Selectors.getSelector(3, KeyIdents));
5826 }
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005827 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00005828
John McCall9e8bb002011-05-14 03:10:52 +00005829 return VTableDispatchMethods.count(Sel);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00005830}
5831
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005832/// BuildClassRoTInitializer - generate meta-data for:
5833/// struct _class_ro_t {
5834/// uint32_t const flags;
5835/// uint32_t const instanceStart;
5836/// uint32_t const instanceSize;
5837/// uint32_t const reserved; // only when building for 64bit targets
5838/// const uint8_t * const ivarLayout;
5839/// const char *const name;
5840/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005841/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005842/// const struct _ivar_list_t *const ivars;
5843/// const uint8_t * const weakIvarLayout;
5844/// const struct _prop_list_t * const properties;
5845/// }
5846///
5847llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005848 unsigned flags,
5849 unsigned InstanceStart,
5850 unsigned InstanceSize,
5851 const ObjCImplementationDecl *ID) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005852 std::string ClassName = ID->getObjCRuntimeNameAsString();
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005853 llvm::Constant *Values[10]; // 11 for 64bit targets!
John McCall31168b02011-06-15 23:02:42 +00005854
John McCall3fd13f062015-10-21 18:06:47 +00005855 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);
5856 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);
5857
John McCall460ce582015-10-22 18:38:17 +00005858 bool hasMRCWeak = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005859 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallef19dbb2012-10-17 04:53:23 +00005860 flags |= NonFragileABI_Class_CompiledByARC;
John McCall460ce582015-10-22 18:38:17 +00005861 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))
5862 flags |= NonFragileABI_Class_HasMRCWeakIvars;
John McCall31168b02011-06-15 23:02:42 +00005863
Owen Andersonb7a2fe62009-07-24 23:12:58 +00005864 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
5865 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
5866 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005867 // FIXME. For 64bit targets add 0 here.
John McCallef19dbb2012-10-17 04:53:23 +00005868 Values[ 3] = (flags & NonFragileABI_Class_Meta)
Craig Topper8a13c412014-05-21 05:09:00 +00005869 ? GetIvarLayoutName(nullptr, ObjCTypes)
John McCall460ce582015-10-22 18:38:17 +00005870 : BuildStrongIvarLayout(ID, beginInstance, endInstance);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005871 Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005872 // const struct _method_list_t * const baseMethods;
5873 std::vector<llvm::Constant*> Methods;
5874 std::string MethodListName("\01l_OBJC_$_");
John McCallef19dbb2012-10-17 04:53:23 +00005875 if (flags & NonFragileABI_Class_Meta) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005876 MethodListName += "CLASS_METHODS_";
5877 MethodListName += ID->getObjCRuntimeNameAsString();
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005878 for (const auto *I : ID->class_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005879 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00005880 Methods.push_back(GetMethodConstant(I));
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005881 } else {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005882 MethodListName += "INSTANCE_METHODS_";
5883 MethodListName += ID->getObjCRuntimeNameAsString();
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005884 for (const auto *I : ID->instance_methods())
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005885 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005886 Methods.push_back(GetMethodConstant(I));
5887
Aaron Ballmand85eff42014-03-14 15:02:45 +00005888 for (const auto *PID : ID->property_impls()) {
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005889 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
5890 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005891
Fariborz Jahaniand27a8202009-01-28 22:46:49 +00005892 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
5893 if (llvm::Constant *C = GetMethodConstant(MD))
5894 Methods.push_back(C);
5895 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
5896 if (llvm::Constant *C = GetMethodConstant(MD))
5897 Methods.push_back(C);
5898 }
5899 }
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00005900 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005901 Values[ 5] = EmitMethodList(MethodListName,
5902 "__DATA, __objc_const", Methods);
5903
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00005904 const ObjCInterfaceDecl *OID = ID->getClassInterface();
5905 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005906 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005907 + OID->getObjCRuntimeNameAsString(),
Ted Kremenek0ef508d2010-09-01 01:21:15 +00005908 OID->all_referenced_protocol_begin(),
5909 OID->all_referenced_protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005910
John McCallef19dbb2012-10-17 04:53:23 +00005911 if (flags & NonFragileABI_Class_Meta) {
Owen Anderson0b75f232009-07-31 20:28:54 +00005912 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +00005913 Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
Manman Renad0e7912016-01-29 19:22:54 +00005914 Values[ 9] = EmitPropertyList(
5915 "\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5916 ID, ID->getClassInterface(), ObjCTypes, true);
John McCallef19dbb2012-10-17 04:53:23 +00005917 } else {
5918 Values[ 7] = EmitIvarList(ID);
John McCall460ce582015-10-22 18:38:17 +00005919 Values[ 8] = BuildWeakIvarLayout(ID, beginInstance, endInstance,
5920 hasMRCWeak);
Manman Renad0e7912016-01-29 19:22:54 +00005921 Values[ 9] = EmitPropertyList(
5922 "\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
5923 ID, ID->getClassInterface(), ObjCTypes, false);
John McCallef19dbb2012-10-17 04:53:23 +00005924 }
Owen Anderson0e0189d2009-07-27 22:29:56 +00005925 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005926 Values);
5927 llvm::GlobalVariable *CLASS_RO_GV =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005928 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00005929 llvm::GlobalValue::PrivateLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005930 Init,
John McCallef19dbb2012-10-17 04:53:23 +00005931 (flags & NonFragileABI_Class_Meta) ?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005932 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
5933 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00005934 CLASS_RO_GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00005935 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00005936 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005937 return CLASS_RO_GV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00005938
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005939}
5940
5941/// BuildClassMetaData - This routine defines that to-level meta-data
5942/// for the given ClassName for:
5943/// struct _class_t {
5944/// struct _class_t *isa;
5945/// struct _class_t * const superclass;
5946/// void *cache;
5947/// IMP *vtable;
5948/// struct class_ro_t *ro;
5949/// }
5950///
Rafael Espindola554256c2014-02-26 22:25:45 +00005951llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005952 const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
Rafael Espindola554256c2014-02-26 22:25:45 +00005953 llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00005954 llvm::Constant *Values[] = {
5955 IsAGV,
5956 SuperClassGV,
5957 ObjCEmptyCacheVar, // &ObjCEmptyCacheVar
5958 ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
5959 ClassRoGV // &CLASS_RO_GV
5960 };
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005961 if (!Values[1])
5962 Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian42d49552013-10-24 17:40:28 +00005963 if (!Values[3])
5964 Values[3] = llvm::Constant::getNullValue(
5965 llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005966 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005967 Values);
Rafael Espindola554256c2014-02-26 22:25:45 +00005968 llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00005969 GV->setInitializer(Init);
Fariborz Jahanian04087232009-01-31 01:07:39 +00005970 GV->setSection("__DATA, __objc_data");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00005971 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00005972 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00005973 if (!CGM.getTriple().isOSBinFormatCOFF())
5974 if (HiddenVisibility)
5975 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00005976 return GV;
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00005977}
5978
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005979bool
Fariborz Jahaniana6bed832009-05-21 01:03:45 +00005980CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Craig Topper8a13c412014-05-21 05:09:00 +00005981 return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
Daniel Dunbar9a017d72009-05-15 22:33:15 +00005982}
5983
Daniel Dunbar961202372009-05-03 12:57:56 +00005984void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbar554fd792009-04-19 23:41:48 +00005985 uint32_t &InstanceStart,
5986 uint32_t &InstanceSize) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005987 const ASTRecordLayout &RL =
Daniel Dunbar9252ee12009-05-04 21:26:30 +00005988 CGM.getContext().getASTObjCImplementationLayout(OID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00005989
Daniel Dunbar9b042e02009-05-04 23:23:09 +00005990 // InstanceSize is really instance end.
Ken Dyckd5090c12011-02-11 02:20:09 +00005991 InstanceSize = RL.getDataSize().getQuantity();
Daniel Dunbar9b042e02009-05-04 23:23:09 +00005992
5993 // If there are no fields, the start is the same as the end.
5994 if (!RL.getFieldCount())
5995 InstanceStart = InstanceSize;
5996 else
Ken Dyckc5ca8762011-04-14 00:43:09 +00005997 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
Daniel Dunbar554fd792009-04-19 23:41:48 +00005998}
5999
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006000static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,
6001 StringRef Name) {
6002 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
6003 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
6004 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6005
6006 const VarDecl *VD = nullptr;
6007 for (const auto &Result : DC->lookup(&II))
6008 if ((VD = dyn_cast<VarDecl>(Result)))
6009 break;
6010
6011 if (!VD)
6012 return llvm::GlobalValue::DLLImportStorageClass;
6013 if (VD->hasAttr<DLLExportAttr>())
6014 return llvm::GlobalValue::DLLExportStorageClass;
6015 if (VD->hasAttr<DLLImportAttr>())
6016 return llvm::GlobalValue::DLLImportStorageClass;
6017 return llvm::GlobalValue::DefaultStorageClass;
6018}
6019
Fariborz Jahanian71394042009-01-23 23:53:38 +00006020void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
Fariborz Jahanian71394042009-01-23 23:53:38 +00006021 if (!ObjCEmptyCacheVar) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006022 ObjCEmptyCacheVar =
6023 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,
6024 llvm::GlobalValue::ExternalLinkage, nullptr,
6025 "_objc_empty_cache");
6026 if (CGM.getTriple().isOSBinFormatCOFF())
6027 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));
Craig Topper8a13c412014-05-21 05:09:00 +00006028
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006029 // Only OS X with deployment version <10.9 use the empty vtable symbol
Fariborz Jahanian42d49552013-10-24 17:40:28 +00006030 const llvm::Triple &Triple = CGM.getTarget().getTriple();
Saleem Abdulrasool4f515a62016-07-13 02:58:44 +00006031 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006032 ObjCEmptyVtableVar =
6033 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,
6034 llvm::GlobalValue::ExternalLinkage, nullptr,
6035 "_objc_empty_vtable");
Fariborz Jahanian71394042009-01-23 23:53:38 +00006036 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006037
Daniel Dunbare3f5cfc2009-04-20 20:18:54 +00006038 // FIXME: Is this correct (that meta class size is never computed)?
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006039 uint32_t InstanceStart =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006040 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006041 uint32_t InstanceSize = InstanceStart;
John McCallef19dbb2012-10-17 04:53:23 +00006042 uint32_t flags = NonFragileABI_Class_Meta;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006043
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006044 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006045
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006046 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006047 const auto *CI = ID->getClassInterface();
6048 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");
6049
John McCall0d54a172012-10-17 04:53:31 +00006050 // Build the flags for the metaclass.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006051 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())
6052 ? !CI->hasAttr<DLLExportAttr>()
6053 : CI->getVisibility() == HiddenVisibility;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006054 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006055 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006056
6057 // FIXME: why is this flag set on the metaclass?
6058 // ObjC metaclasses have no fields and don't really get constructed.
6059 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006060 flags |= NonFragileABI_Class_HasCXXStructors;
John McCall0d54a172012-10-17 04:53:31 +00006061 if (!ID->hasNonZeroConstructors())
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006062 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
John McCall0d54a172012-10-17 04:53:31 +00006063 }
6064
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006065 if (!CI->getSuperClass()) {
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006066 // class is root
John McCallef19dbb2012-10-17 04:53:23 +00006067 flags |= NonFragileABI_Class_Root;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006068
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006069 SuperClassGV = GetClassGlobal((getClassSymbolPrefix() + ClassName).str(),
6070 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006071 if (CGM.getTriple().isOSBinFormatCOFF())
6072 if (CI->hasAttr<DLLImportAttr>())
6073 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006074
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006075 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + ClassName).str(),
6076 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006077 if (CGM.getTriple().isOSBinFormatCOFF())
6078 if (CI->hasAttr<DLLImportAttr>())
6079 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006080 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006081 // Has a root. Current class is not a root.
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006082 const ObjCInterfaceDecl *Root = ID->getClassInterface();
6083 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
6084 Root = Super;
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006085
6086 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006087 StringRef RootClassName = Root->getObjCRuntimeNameAsString();
6088 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006089
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006090 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + RootClassName).str(),
6091 Root->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006092 if (CGM.getTriple().isOSBinFormatCOFF())
6093 if (Root->hasAttr<DLLImportAttr>())
6094 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006095
Fariborz Jahanian03b300b2009-02-26 18:23:47 +00006096 // work on super class metadata symbol.
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006097 SuperClassGV =
6098 GetClassGlobal((getMetaclassSymbolPrefix() + SuperClassName).str(),
6099 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006100 if (CGM.getTriple().isOSBinFormatCOFF())
6101 if (Super->hasAttr<DLLImportAttr>())
6102 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian9e3ad522009-01-24 20:21:50 +00006103 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006104
6105 llvm::GlobalVariable *CLASS_RO_GV =
6106 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
6107
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006108 llvm::GlobalVariable *MetaTClass =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006109 BuildClassMetaData((getMetaclassSymbolPrefix() + ClassName).str(), IsAGV,
6110 SuperClassGV, CLASS_RO_GV, classIsHidden,
6111 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006112 if (CGM.getTriple().isOSBinFormatCOFF())
6113 if (CI->hasAttr<DLLExportAttr>())
6114 MetaTClass->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian67260552009-11-17 21:37:35 +00006115 DefinedMetaClasses.push_back(MetaTClass);
Daniel Dunbar15894b72009-04-07 05:48:37 +00006116
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006117 // Metadata for the class
John McCallef19dbb2012-10-17 04:53:23 +00006118 flags = 0;
Fariborz Jahanian82208252009-01-31 00:59:10 +00006119 if (classIsHidden)
John McCallef19dbb2012-10-17 04:53:23 +00006120 flags |= NonFragileABI_Class_Hidden;
John McCall0d54a172012-10-17 04:53:31 +00006121
6122 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
John McCallef19dbb2012-10-17 04:53:23 +00006123 flags |= NonFragileABI_Class_HasCXXStructors;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006124
John McCall0d54a172012-10-17 04:53:31 +00006125 // Set a flag to enable a runtime optimization when a class has
6126 // fields that require destruction but which don't require
6127 // anything except zero-initialization during construction. This
6128 // is most notably true of __strong and __weak types, but you can
6129 // also imagine there being C++ types with non-trivial default
6130 // constructors that merely set all fields to null.
6131 if (!ID->hasNonZeroConstructors())
6132 flags |= NonFragileABI_Class_HasCXXDestructorOnly;
6133 }
6134
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006135 if (hasObjCExceptionAttribute(CGM.getContext(), CI))
John McCallef19dbb2012-10-17 04:53:23 +00006136 flags |= NonFragileABI_Class_Exception;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006137
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006138 if (!CI->getSuperClass()) {
John McCallef19dbb2012-10-17 04:53:23 +00006139 flags |= NonFragileABI_Class_Root;
Craig Topper8a13c412014-05-21 05:09:00 +00006140 SuperClassGV = nullptr;
Chris Lattnerb433b272009-04-19 06:02:28 +00006141 } else {
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006142 // Has a root. Current class is not a root.
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006143 const auto *Super = CI->getSuperClass();
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006144 StringRef SuperClassName = Super->getObjCRuntimeNameAsString();
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006145
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006146 SuperClassGV =
6147 GetClassGlobal((getClassSymbolPrefix() + SuperClassName).str(),
6148 Super->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006149 if (CGM.getTriple().isOSBinFormatCOFF())
6150 if (Super->hasAttr<DLLImportAttr>())
6151 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Fariborz Jahanian4723fb72009-01-24 21:21:53 +00006152 }
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006153
Daniel Dunbar961202372009-05-03 12:57:56 +00006154 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006155 CLASS_RO_GV =
6156 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006157
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006158 llvm::GlobalVariable *ClassMD =
Saleem Abdulrasool10fd1ff2016-07-16 22:42:06 +00006159 BuildClassMetaData((getClassSymbolPrefix() + ClassName).str(), MetaTClass,
6160 SuperClassGV, CLASS_RO_GV, classIsHidden,
6161 CI->isWeakImported());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006162 if (CGM.getTriple().isOSBinFormatCOFF())
6163 if (CI->hasAttr<DLLExportAttr>())
6164 ClassMD->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Fariborz Jahanian279abd32009-01-30 20:55:31 +00006165 DefinedClasses.push_back(ClassMD);
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006166 ImplementedClasses.push_back(CI);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006167
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006168 // Determine if this class is also "non-lazy".
6169 if (ImplementationIsNonLazy(ID))
6170 DefinedNonLazyClasses.push_back(ClassMD);
6171
Daniel Dunbar8f28d012009-04-08 04:21:03 +00006172 // Force the definition of the EHType if necessary.
John McCallef19dbb2012-10-17 04:53:23 +00006173 if (flags & NonFragileABI_Class_Exception)
Saleem Abdulrasoolbc2d9992016-07-16 22:42:04 +00006174 GetInterfaceEHType(CI, true);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006175 // Make sure method definition entries are all clear for next implementation.
6176 MethodDefinitions.clear();
Fariborz Jahanian71394042009-01-23 23:53:38 +00006177}
6178
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006179/// GenerateProtocolRef - This routine is called to generate code for
6180/// a protocol reference expression; as in:
6181/// @code
6182/// @protocol(Proto1);
6183/// @endcode
6184/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
6185/// which will hold address of the protocol meta-data.
6186///
John McCall882987f2013-02-28 19:01:20 +00006187llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006188 const ObjCProtocolDecl *PD) {
6189
Fariborz Jahanian464423d2009-04-10 18:47:34 +00006190 // This routine is called for @protocol only. So, we must build definition
6191 // of protocol's meta-data (not a reference to it!)
6192 //
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006193 llvm::Constant *Init =
6194 llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Douglas Gregor020de322012-01-17 18:36:30 +00006195 ObjCTypes.getExternalProtocolPtrTy());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006196
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006197 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006198 ProtocolName += PD->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006199
John McCall7f416cc2015-09-08 08:05:57 +00006200 CharUnits Align = CGF.getPointerAlign();
6201
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006202 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
6203 if (PTGV)
John McCall7f416cc2015-09-08 08:05:57 +00006204 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006205 PTGV = new llvm::GlobalVariable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006206 CGM.getModule(),
6207 Init->getType(), false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006208 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006209 Init,
6210 ProtocolName);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006211 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006212 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall7f416cc2015-09-08 08:05:57 +00006213 PTGV->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00006214 CGM.addCompilerUsedGlobal(PTGV);
John McCall7f416cc2015-09-08 08:05:57 +00006215 return CGF.Builder.CreateAlignedLoad(PTGV, Align);
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006216}
6217
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006218/// GenerateCategory - Build metadata for a category implementation.
6219/// struct _category_t {
6220/// const char * const name;
6221/// struct _class_t *const cls;
6222/// const struct _method_list_t * const instance_methods;
6223/// const struct _method_list_t * const class_methods;
6224/// const struct _protocol_list_t * const protocols;
6225/// const struct _prop_list_t * const properties;
Manman Ren96df0b32016-01-29 23:45:01 +00006226/// const struct _prop_list_t * const class_properties;
Manman Ren42ff3902016-02-24 17:49:50 +00006227/// const uint32_t size;
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006228/// }
6229///
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006230void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006231 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006232 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006233
6234 llvm::SmallString<64> ExtCatName(Prefix);
6235 ExtCatName += Interface->getObjCRuntimeNameAsString();
6236 ExtCatName += "_$_";
6237 ExtCatName += OCD->getNameAsString();
6238
6239 llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
6240 ExtClassName += Interface->getObjCRuntimeNameAsString();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006241
Manman Ren42ff3902016-02-24 17:49:50 +00006242 llvm::Constant *Values[8];
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006243 Values[0] = GetClassName(OCD->getIdentifier()->getName());
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006244 // meta-class entry symbol
Rafael Espindola554256c2014-02-26 22:25:45 +00006245 llvm::GlobalVariable *ClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006246 GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
Rafael Espindola554256c2014-02-26 22:25:45 +00006247
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006248 Values[1] = ClassGV;
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006249 std::vector<llvm::Constant*> Methods;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006250 llvm::SmallString<64> MethodListName(Prefix);
6251
6252 MethodListName += "INSTANCE_METHODS_";
6253 MethodListName += Interface->getObjCRuntimeNameAsString();
6254 MethodListName += "_$_";
6255 MethodListName += OCD->getName();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006256
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006257 for (const auto *I : OCD->instance_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006258 // Instance methods should always be defined.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006259 Methods.push_back(GetMethodConstant(I));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006260
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006261 Values[2] = EmitMethodList(MethodListName.str(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006262 "__DATA, __objc_const",
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006263 Methods);
6264
6265 MethodListName = Prefix;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006266 MethodListName += "CLASS_METHODS_";
6267 MethodListName += Interface->getObjCRuntimeNameAsString();
6268 MethodListName += "_$_";
6269 MethodListName += OCD->getNameAsString();
6270
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006271 Methods.clear();
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006272 for (const auto *I : OCD->class_methods())
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006273 // Class methods should always be defined.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006274 Methods.push_back(GetMethodConstant(I));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006275
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006276 Values[3] = EmitMethodList(MethodListName.str(),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006277 "__DATA, __objc_const",
Fariborz Jahanian2612e142009-01-26 22:58:07 +00006278 Methods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006279 const ObjCCategoryDecl *Category =
Fariborz Jahanian066347e2009-01-28 22:18:42 +00006280 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006281 if (Category) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006282 SmallString<256> ExtName;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006283 llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006284 << OCD->getName();
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006285 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006286 + Interface->getObjCRuntimeNameAsString() + "_$_"
6287 + Category->getName(),
6288 Category->protocol_begin(),
6289 Category->protocol_end());
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006290 Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
Manman Renad0e7912016-01-29 19:22:54 +00006291 OCD, Category, ObjCTypes, false);
Manman Ren96df0b32016-01-29 23:45:01 +00006292 Values[6] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
6293 OCD, Category, ObjCTypes, true);
Mike Stump658fe022009-07-30 22:28:39 +00006294 } else {
Owen Anderson0b75f232009-07-31 20:28:54 +00006295 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
6296 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Manman Ren96df0b32016-01-29 23:45:01 +00006297 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
Fariborz Jahaniand8fc1052009-02-13 17:52:22 +00006298 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006299
Manman Ren42ff3902016-02-24 17:49:50 +00006300 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);
6301 Values[7] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6302
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006303 llvm::Constant *Init =
6304 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006305 Values);
6306 llvm::GlobalVariable *GCATV
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006307 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006308 false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006309 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006310 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006311 ExtCatName.str());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006312 GCATV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006313 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006314 GCATV->setSection("__DATA, __objc_const");
Rafael Espindola060062a2014-03-06 22:15:10 +00006315 CGM.addCompilerUsedGlobal(GCATV);
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006316 DefinedCategories.push_back(GCATV);
Daniel Dunbar9a017d72009-05-15 22:33:15 +00006317
6318 // Determine if this category is also "non-lazy".
6319 if (ImplementationIsNonLazy(OCD))
6320 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianc0577942011-04-22 22:02:28 +00006321 // method definition entries must be clear for next implementation.
6322 MethodDefinitions.clear();
Fariborz Jahanian0c8d0602009-01-26 18:32:24 +00006323}
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006324
6325/// GetMethodConstant - Return a struct objc_method constant for the
6326/// given method if it has been defined. The result is null if the
6327/// method has not been defined. The return value has type MethodPtrTy.
6328llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006329 const ObjCMethodDecl *MD) {
Argyrios Kyrtzidis13257c52010-08-09 10:54:20 +00006330 llvm::Function *Fn = GetMethodDefinition(MD);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006331 if (!Fn)
Craig Topper8a13c412014-05-21 05:09:00 +00006332 return nullptr;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006333
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006334 llvm::Constant *Method[] = {
Owen Andersonade90fd2009-07-29 18:54:39 +00006335 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006336 ObjCTypes.SelectorPtrTy),
6337 GetMethodVarType(MD),
6338 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
6339 };
Owen Anderson0e0189d2009-07-27 22:29:56 +00006340 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006341}
6342
6343/// EmitMethodList - Build meta-data for method declarations
6344/// struct _method_list_t {
6345/// uint32_t entsize; // sizeof(struct _objc_method)
6346/// uint32_t method_count;
6347/// struct _objc_method method_list[method_count];
6348/// }
6349///
Bill Wendlingcb5b5ff2012-02-07 09:25:09 +00006350llvm::Constant *
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00006351CGObjCNonFragileABIMac::EmitMethodList(Twine Name, StringRef Section,
6352 ArrayRef<llvm::Constant *> Methods) {
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006353 // Return null for empty list.
6354 if (Methods.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006355 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006356
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006357 llvm::Constant *Values[3];
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006358 // sizeof(struct _objc_method)
Micah Villmowdd31ca12012-10-08 16:25:52 +00006359 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006360 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006361 // method_count
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006362 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006363 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006364 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006365 Values[2] = llvm::ConstantArray::get(AT, Methods);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006366 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006367
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006368 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00006369 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006370 llvm::GlobalValue::PrivateLinkage, Init, Name);
Micah Villmowdd31ca12012-10-08 16:25:52 +00006371 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006372 GV->setSection(Section);
Rafael Espindola060062a2014-03-06 22:15:10 +00006373 CGM.addCompilerUsedGlobal(GV);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006374 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
Fariborz Jahanian99113fd2009-01-26 21:38:32 +00006375}
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006376
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006377/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
6378/// the given ivar.
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006379llvm::GlobalVariable *
6380CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
6381 const ObjCIvarDecl *Ivar) {
6382 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006383 llvm::SmallString<64> Name("OBJC_IVAR_$_");
6384 Name += Container->getObjCRuntimeNameAsString();
6385 Name += ".";
6386 Name += Ivar->getName();
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006387 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
6388 if (!IvarOffsetGV) {
6389 IvarOffsetGV =
6390 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,
6391 false, llvm::GlobalValue::ExternalLinkage,
6392 nullptr, Name.str());
6393 if (CGM.getTriple().isOSBinFormatCOFF()) {
6394 bool IsPrivateOrPackage =
6395 Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6396 Ivar->getAccessControl() == ObjCIvarDecl::Package;
6397
6398 if (ID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)
6399 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6400 else if (ID->hasAttr<DLLImportAttr>())
6401 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6402 }
6403 }
Fariborz Jahanian4e7ae062009-02-10 20:21:06 +00006404 return IvarOffsetGV;
6405}
6406
Daniel Dunbar8c7f9812010-04-02 21:14:02 +00006407llvm::Constant *
6408CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
6409 const ObjCIvarDecl *Ivar,
Eli Friedman8cbca202012-11-06 22:15:52 +00006410 unsigned long int Offset) {
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006411 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
Tim Northover238b5082014-03-29 13:42:40 +00006412 IvarOffsetGV->setInitializer(
6413 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006414 IvarOffsetGV->setAlignment(
Tim Northover238b5082014-03-29 13:42:40 +00006415 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
Daniel Dunbarbf90b332009-04-19 00:44:02 +00006416
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00006417 if (!CGM.getTriple().isOSBinFormatCOFF()) {
6418 // FIXME: This matches gcc, but shouldn't the visibility be set on the use
6419 // as well (i.e., in ObjCIvarOffsetVariable).
6420 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6421 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6422 ID->getVisibility() == HiddenVisibility)
6423 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
6424 else
6425 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6426 }
6427
Bill Wendlingf7d45982011-05-04 21:37:25 +00006428 IvarOffsetGV->setSection("__DATA, __objc_ivar");
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006429 return IvarOffsetGV;
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006430}
6431
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006432/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006433/// implementation. The return value has type
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006434/// IvarListnfABIPtrTy.
6435/// struct _ivar_t {
Tim Northover238b5082014-03-29 13:42:40 +00006436/// unsigned [long] int *offset; // pointer to ivar offset location
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006437/// char *name;
6438/// char *type;
6439/// uint32_t alignment;
6440/// uint32_t size;
6441/// }
6442/// struct _ivar_list_t {
6443/// uint32 entsize; // sizeof(struct _ivar_t)
6444/// uint32 count;
6445/// struct _iver_t list[count];
6446/// }
6447///
Daniel Dunbarf5c18462009-04-20 06:54:31 +00006448
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006449llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006450 const ObjCImplementationDecl *ID) {
6451
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006452 std::vector<llvm::Constant*> Ivars;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006453
Jordy Rosea91768e2011-07-22 02:08:32 +00006454 const ObjCInterfaceDecl *OID = ID->getClassInterface();
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006455 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006456
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006457 // FIXME. Consolidate this with similar code in GenerateClass.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006458
Jordy Rosea91768e2011-07-22 02:08:32 +00006459 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00006460 IVD; IVD = IVD->getNextIvar()) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00006461 // Ignore unnamed bit-fields.
6462 if (!IVD->getDeclName())
6463 continue;
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006464 llvm::Constant *Ivar[5];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006465 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar961202372009-05-03 12:57:56 +00006466 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006467 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
6468 Ivar[2] = GetMethodVarType(IVD);
Chris Lattner2192fe52011-07-18 04:24:23 +00006469 llvm::Type *FieldTy =
Daniel Dunbar725dc2c2009-04-22 08:22:17 +00006470 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00006471 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006472 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006473 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006474 Align = llvm::Log2_32(Align);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006475 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbarae032262009-04-20 00:33:43 +00006476 // NOTE. Size of a bitfield does not match gcc's, because of the
6477 // way bitfields are treated special in each. But I am told that
6478 // 'size' for bitfield ivars is ignored by the runtime so it does
6479 // not matter. If it matters, there is enough info to get the
6480 // bitfield right!
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006481 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006482 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006483 }
6484 // Return null for empty list.
6485 if (Ivars.empty())
Owen Anderson0b75f232009-07-31 20:28:54 +00006486 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006487
6488 llvm::Constant *Values[3];
Micah Villmowdd31ca12012-10-08 16:25:52 +00006489 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006490 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
6491 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
Owen Anderson9793f0e2009-07-29 22:16:19 +00006492 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006493 Ivars.size());
Owen Anderson47034e12009-07-28 18:33:04 +00006494 Values[2] = llvm::ConstantArray::get(AT, Ivars);
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006495 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006496 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
6497 llvm::GlobalVariable *GV =
Owen Andersonc10c8d32009-07-08 19:05:04 +00006498 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006499 llvm::GlobalValue::PrivateLinkage,
Fariborz Jahanian7415caa2009-01-27 19:38:51 +00006500 Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006501 Prefix + OID->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006502 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006503 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Fariborz Jahanian40a4bcd2009-01-28 01:05:23 +00006504 GV->setSection("__DATA, __objc_const");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006505
Rafael Espindola060062a2014-03-06 22:15:10 +00006506 CGM.addCompilerUsedGlobal(GV);
Owen Andersonade90fd2009-07-29 18:54:39 +00006507 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006508}
6509
6510llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006511 const ObjCProtocolDecl *PD) {
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006512 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006513
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006514 if (!Entry)
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006515 // We use the initializer as a marker of whether this is a forward
6516 // reference or not. At module finalization we add the empty
6517 // contents for protocols which were referenced but never defined.
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006518 Entry =
Rafael Espindola5d117f32014-03-06 01:10:46 +00006519 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
Rafael Espindola24615092014-09-12 20:14:20 +00006520 false, llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00006521 nullptr,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006522 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006523
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006524 return Entry;
6525}
6526
6527/// GetOrEmitProtocol - Generate the protocol meta-data:
6528/// @code
6529/// struct _protocol_t {
6530/// id isa; // NULL
6531/// const char * const protocol_name;
6532/// const struct _protocol_list_t * protocol_list; // super protocols
6533/// const struct method_list_t * const instance_methods;
6534/// const struct method_list_t * const class_methods;
6535/// const struct method_list_t *optionalInstanceMethods;
6536/// const struct method_list_t *optionalClassMethods;
6537/// const struct _prop_list_t * properties;
6538/// const uint32_t size; // sizeof(struct _protocol_t)
6539/// const uint32_t flags; // = 0
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006540/// const char ** extendedMethodTypes;
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006541/// const char *demangledName;
Manman Rence7bff52016-01-29 23:46:55 +00006542/// const struct _prop_list_t * class_properties;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006543/// }
6544/// @endcode
6545///
6546
6547llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006548 const ObjCProtocolDecl *PD) {
John McCallf9582a72012-03-30 21:29:05 +00006549 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006550
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006551 // Early exit if a defining object has already been generated.
6552 if (Entry && Entry->hasInitializer())
6553 return Entry;
6554
Douglas Gregora715bff2012-01-01 19:51:50 +00006555 // Use the protocol definition, if there is one.
6556 if (const ObjCProtocolDecl *Def = PD->getDefinition())
6557 PD = Def;
6558
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006559 // Construct method lists.
6560 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
6561 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006562 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006563 for (const auto *MD : PD->instance_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006564 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006565 if (!C)
6566 return GetOrEmitProtocolRef(PD);
6567
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006568 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6569 OptInstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006570 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006571 } else {
6572 InstanceMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006573 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006574 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006575 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006576
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006577 for (const auto *MD : PD->class_methods()) {
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006578 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006579 if (!C)
6580 return GetOrEmitProtocolRef(PD);
6581
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006582 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6583 OptClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006584 OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006585 } else {
6586 ClassMethods.push_back(C);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006587 MethodTypesExt.push_back(GetMethodVarType(MD, true));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006588 }
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006589 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006590
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006591 MethodTypesExt.insert(MethodTypesExt.end(),
6592 OptMethodTypesExt.begin(), OptMethodTypesExt.end());
6593
Manman Rence7bff52016-01-29 23:46:55 +00006594 llvm::Constant *Values[13];
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006595 // isa is NULL
Owen Anderson0b75f232009-07-31 20:28:54 +00006596 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006597 Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
6598 Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006599 PD->protocol_begin(),
6600 PD->protocol_end());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006601
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006602 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006603 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006604 "__DATA, __objc_const",
6605 InstanceMethods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006606 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006607 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006608 "__DATA, __objc_const",
6609 ClassMethods);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006610 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006611 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006612 "__DATA, __objc_const",
6613 OptInstanceMethods);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006614 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006615 + PD->getObjCRuntimeNameAsString(),
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006616 "__DATA, __objc_const",
6617 OptClassMethods);
Manman Renad0e7912016-01-29 19:22:54 +00006618 Values[7] = EmitPropertyList(
6619 "\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6620 nullptr, PD, ObjCTypes, false);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006621 uint32_t Size =
Micah Villmowdd31ca12012-10-08 16:25:52 +00006622 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006623 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Owen Anderson0b75f232009-07-31 20:28:54 +00006624 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006625 Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006626 + PD->getObjCRuntimeNameAsString(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006627 MethodTypesExt, ObjCTypes);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006628 // const char *demangledName;
6629 Values[11] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Manman Rence7bff52016-01-29 23:46:55 +00006630
6631 Values[12] = EmitPropertyList(
6632 "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
6633 nullptr, PD, ObjCTypes, true);
Fariborz Jahanian6a9c46b2015-03-31 22:22:40 +00006634
Owen Anderson0e0189d2009-07-27 22:29:56 +00006635 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006636 Values);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006637
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006638 if (Entry) {
Rafael Espindola24615092014-09-12 20:14:20 +00006639 // Already created, fix the linkage and update the initializer.
6640 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006641 Entry->setInitializer(Init);
6642 } else {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006643 Entry =
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006644 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006645 false, llvm::GlobalValue::WeakAnyLinkage, Init,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006646 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006647 Entry->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006648 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
John McCallf9582a72012-03-30 21:29:05 +00006649
6650 Protocols[PD->getIdentifier()] = Entry;
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006651 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006652 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006653 CGM.addCompilerUsedGlobal(Entry);
Chris Lattnerf56501c2009-07-17 23:57:13 +00006654
Fariborz Jahanian61cd4b52009-01-29 20:10:59 +00006655 // Use this protocol meta-data to build protocol list table in section
6656 // __DATA, __objc_protolist
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006657 llvm::GlobalVariable *PTGV =
6658 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006659 false, llvm::GlobalValue::WeakAnyLinkage, Entry,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006660 "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006661 PTGV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006662 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbarb25452a2009-04-15 02:56:18 +00006663 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006664 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindola060062a2014-03-06 22:15:10 +00006665 CGM.addCompilerUsedGlobal(PTGV);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006666 return Entry;
6667}
6668
6669/// EmitProtocolList - Generate protocol list meta-data:
6670/// @code
6671/// struct _protocol_list_t {
6672/// long protocol_count; // Note, this is 32/64 bit
6673/// struct _protocol_t[protocol_count];
6674/// }
6675/// @endcode
6676///
6677llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006678CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006679 ObjCProtocolDecl::protocol_iterator begin,
6680 ObjCProtocolDecl::protocol_iterator end) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006681 SmallVector<llvm::Constant *, 16> ProtocolRefs;
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006682
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006683 // Just return null for empty protocol lists
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006684 if (begin == end)
Owen Anderson0b75f232009-07-31 20:28:54 +00006685 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006686
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006687 // FIXME: We shouldn't need to do this lookup here, should we?
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006688 SmallString<256> TmpName;
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006689 Name.toVector(TmpName);
6690 llvm::GlobalVariable *GV =
6691 CGM.getModule().getGlobalVariable(TmpName.str(), true);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006692 if (GV)
Daniel Dunbar349e6fb2009-10-18 20:48:59 +00006693 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006694
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006695 for (; begin != end; ++begin)
6696 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
6697
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006698 // This list is null terminated.
Owen Anderson0b75f232009-07-31 20:28:54 +00006699 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006700 ObjCTypes.ProtocolnfABIPtrTy));
6701
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006702 llvm::Constant *Values[2];
Owen Anderson170229f2009-07-14 23:10:40 +00006703 Values[0] =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00006704 llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006705 Values[1] =
Bill Wendlinga515b582012-02-09 22:16:49 +00006706 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
6707 ProtocolRefs.size()),
6708 ProtocolRefs);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006709
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006710 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
Owen Andersonc10c8d32009-07-08 19:05:04 +00006711 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00006712 llvm::GlobalValue::PrivateLinkage,
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006713 Init, Name);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006714 GV->setSection("__DATA, __objc_const");
Fariborz Jahanianc22f2362009-01-31 02:43:27 +00006715 GV->setAlignment(
Micah Villmowdd31ca12012-10-08 16:25:52 +00006716 CGM.getDataLayout().getABITypeAlignment(Init->getType()));
Rafael Espindola060062a2014-03-06 22:15:10 +00006717 CGM.addCompilerUsedGlobal(GV);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006718 return llvm::ConstantExpr::getBitCast(GV,
Daniel Dunbar8de90f02009-02-15 07:36:20 +00006719 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian56b3b772009-01-29 19:24:30 +00006720}
6721
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006722/// GetMethodDescriptionConstant - This routine build following meta-data:
6723/// struct _objc_method {
6724/// SEL _cmd;
6725/// char *method_type;
6726/// char *_imp;
6727/// }
6728
6729llvm::Constant *
6730CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00006731 llvm::Constant *Desc[3];
Owen Anderson170229f2009-07-14 23:10:40 +00006732 Desc[0] =
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006733 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
6734 ObjCTypes.SelectorPtrTy);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006735 Desc[1] = GetMethodVarType(MD);
Douglas Gregora9d84932011-05-27 01:19:52 +00006736 if (!Desc[1])
Craig Topper8a13c412014-05-21 05:09:00 +00006737 return nullptr;
6738
Fariborz Jahanian097feda2009-01-30 18:58:59 +00006739 // Protocol methods have no implementation. So, this entry is always NULL.
Owen Anderson0b75f232009-07-31 20:28:54 +00006740 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Owen Anderson0e0189d2009-07-27 22:29:56 +00006741 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
Fariborz Jahaniand9c28b82009-01-30 00:46:37 +00006742}
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006743
6744/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
6745/// This code gen. amounts to generating code for:
6746/// @code
6747/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
6748/// @encode
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006749///
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00006750LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
John McCall96fa4842010-05-17 21:00:27 +00006751 CodeGen::CodeGenFunction &CGF,
6752 QualType ObjectTy,
6753 llvm::Value *BaseValue,
6754 const ObjCIvarDecl *Ivar,
6755 unsigned CVRQualifiers) {
6756 ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006757 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00006758 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
Fariborz Jahaniancaabf1b2012-02-20 22:42:22 +00006759 Offset);
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00006760}
6761
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006762llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006763 CodeGen::CodeGenFunction &CGF,
6764 const ObjCInterfaceDecl *Interface,
6765 const ObjCIvarDecl *Ivar) {
Tim Northover238b5082014-03-29 13:42:40 +00006766 llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
John McCall7f416cc2015-09-08 08:05:57 +00006767 IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
6768 CGF.getSizeAlign(), "ivar");
Tim Northover238b5082014-03-29 13:42:40 +00006769 if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
6770 cast<llvm::LoadInst>(IvarOffsetValue)
6771 ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
Craig Topper5fc8fc22014-08-27 06:28:36 +00006772 llvm::MDNode::get(VMContext, None));
Tim Northover238b5082014-03-29 13:42:40 +00006773
6774 // This could be 32bit int or 64bit integer depending on the architecture.
6775 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
6776 // as this is what caller always expectes.
6777 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
6778 IvarOffsetValue = CGF.Builder.CreateIntCast(
6779 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
6780 return IvarOffsetValue;
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00006781}
6782
John McCall234eac82011-05-13 23:16:18 +00006783static void appendSelectorForMessageRefTable(std::string &buffer,
6784 Selector selector) {
6785 if (selector.isUnarySelector()) {
6786 buffer += selector.getNameForSlot(0);
6787 return;
6788 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006789
John McCall234eac82011-05-13 23:16:18 +00006790 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
6791 buffer += selector.getNameForSlot(i);
6792 buffer += '_';
6793 }
6794}
6795
Eric Christopherd160c502016-01-29 01:35:53 +00006796/// Emit a "vtable" message send. We emit a weak hidden-visibility
John McCall9e8bb002011-05-14 03:10:52 +00006797/// struct, initially containing the selector pointer and a pointer to
6798/// a "fixup" variant of the appropriate objc_msgSend. To call, we
6799/// load and call the function pointer, passing the address of the
6800/// struct as the second parameter. The runtime determines whether
6801/// the selector is currently emitted using vtable dispatch; if so, it
6802/// substitutes a stub function which simply tail-calls through the
6803/// appropriate vtable slot, and if not, it substitues a stub function
6804/// which tail-calls objc_msgSend. Both stubs adjust the selector
6805/// argument to correctly point to the selector.
6806RValue
6807CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
6808 ReturnValueSlot returnSlot,
6809 QualType resultType,
6810 Selector selector,
6811 llvm::Value *arg0,
6812 QualType arg0Type,
6813 bool isSuper,
6814 const CallArgList &formalArgs,
6815 const ObjCMethodDecl *method) {
John McCall234eac82011-05-13 23:16:18 +00006816 // Compute the actual arguments.
6817 CallArgList args;
6818
John McCall9e8bb002011-05-14 03:10:52 +00006819 // First argument: the receiver / super-call structure.
John McCall234eac82011-05-13 23:16:18 +00006820 if (!isSuper)
John McCall9e8bb002011-05-14 03:10:52 +00006821 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
6822 args.add(RValue::get(arg0), arg0Type);
John McCall234eac82011-05-13 23:16:18 +00006823
John McCall9e8bb002011-05-14 03:10:52 +00006824 // Second argument: a pointer to the message ref structure. Leave
6825 // the actual argument value blank for now.
Craig Topper8a13c412014-05-21 05:09:00 +00006826 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
John McCall234eac82011-05-13 23:16:18 +00006827
6828 args.insert(args.end(), formalArgs.begin(), formalArgs.end());
6829
John McCalla729c622012-02-17 03:33:10 +00006830 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
John McCall234eac82011-05-13 23:16:18 +00006831
John McCall5880fb82011-05-14 21:12:11 +00006832 NullReturnState nullReturn;
6833
John McCall9e8bb002011-05-14 03:10:52 +00006834 // Find the function to call and the mangled name for the message
6835 // ref structure. Using a different mangled name wouldn't actually
6836 // be a problem; it would just be a waste.
6837 //
6838 // The runtime currently never uses vtable dispatch for anything
6839 // except normal, non-super message-sends.
6840 // FIXME: don't use this for that.
Craig Topper8a13c412014-05-21 05:09:00 +00006841 llvm::Constant *fn = nullptr;
John McCall234eac82011-05-13 23:16:18 +00006842 std::string messageRefName("\01l_");
Tim Northovere77cc392014-03-29 13:28:05 +00006843 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
John McCall234eac82011-05-13 23:16:18 +00006844 if (isSuper) {
6845 fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
6846 messageRefName += "objc_msgSendSuper2_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006847 } else {
John McCall5880fb82011-05-14 21:12:11 +00006848 nullReturn.init(CGF, arg0);
John McCall234eac82011-05-13 23:16:18 +00006849 fn = ObjCTypes.getMessageSendStretFixupFn();
6850 messageRefName += "objc_msgSend_stret_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006851 }
John McCall234eac82011-05-13 23:16:18 +00006852 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
6853 fn = ObjCTypes.getMessageSendFpretFixupFn();
6854 messageRefName += "objc_msgSend_fpret_fixup";
Mike Stump658fe022009-07-30 22:28:39 +00006855 } else {
John McCall234eac82011-05-13 23:16:18 +00006856 if (isSuper) {
6857 fn = ObjCTypes.getMessageSendSuper2FixupFn();
6858 messageRefName += "objc_msgSendSuper2_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006859 } else {
John McCall234eac82011-05-13 23:16:18 +00006860 fn = ObjCTypes.getMessageSendFixupFn();
6861 messageRefName += "objc_msgSend_fixup";
Chris Lattner396639d2010-08-18 16:09:06 +00006862 }
Fariborz Jahaniane4dc35d2009-02-04 20:42:28 +00006863 }
John McCall234eac82011-05-13 23:16:18 +00006864 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
6865 messageRefName += '_';
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006866
John McCall234eac82011-05-13 23:16:18 +00006867 // Append the selector name, except use underscores anywhere we
6868 // would have used colons.
6869 appendSelectorForMessageRefTable(messageRefName, selector);
6870
6871 llvm::GlobalVariable *messageRef
6872 = CGM.getModule().getGlobalVariable(messageRefName);
6873 if (!messageRef) {
John McCall9e8bb002011-05-14 03:10:52 +00006874 // Build the message ref structure.
John McCall234eac82011-05-13 23:16:18 +00006875 llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00006876 llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
John McCall234eac82011-05-13 23:16:18 +00006877 messageRef = new llvm::GlobalVariable(CGM.getModule(),
6878 init->getType(),
6879 /*constant*/ false,
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006880 llvm::GlobalValue::WeakAnyLinkage,
John McCall234eac82011-05-13 23:16:18 +00006881 init,
6882 messageRefName);
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006883 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCall234eac82011-05-13 23:16:18 +00006884 messageRef->setAlignment(16);
6885 messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
6886 }
Rafael Espindola70efc5b2014-03-06 18:54:12 +00006887
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006888 bool requiresnullCheck = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006889 if (CGM.getLangOpts().ObjCAutoRefCount && method)
David Majnemer59f77922016-06-24 04:05:48 +00006890 for (const auto *ParamDecl : method->parameters()) {
Fariborz Jahanianc93fa982012-01-30 23:39:30 +00006891 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
6892 if (!nullReturn.NullBB)
6893 nullReturn.init(CGF, arg0);
6894 requiresnullCheck = true;
6895 break;
6896 }
6897 }
6898
John McCall7f416cc2015-09-08 08:05:57 +00006899 Address mref =
6900 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),
6901 CGF.getPointerAlign());
John McCall234eac82011-05-13 23:16:18 +00006902
John McCall9e8bb002011-05-14 03:10:52 +00006903 // Update the message ref argument.
John McCall7f416cc2015-09-08 08:05:57 +00006904 args[1].RV = RValue::get(mref.getPointer());
John McCall234eac82011-05-13 23:16:18 +00006905
6906 // Load the function to call from the message ref table.
John McCall7f416cc2015-09-08 08:05:57 +00006907 Address calleeAddr =
6908 CGF.Builder.CreateStructGEP(mref, 0, CharUnits::Zero());
6909 llvm::Value *callee = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");
John McCall234eac82011-05-13 23:16:18 +00006910
John McCalla729c622012-02-17 03:33:10 +00006911 callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
John McCall234eac82011-05-13 23:16:18 +00006912
John McCalla729c622012-02-17 03:33:10 +00006913 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
Craig Topper8a13c412014-05-21 05:09:00 +00006914 return nullReturn.complete(CGF, result, resultType, formalArgs,
6915 requiresnullCheck ? method : nullptr);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006916}
6917
6918/// Generate code for a message send expression in the nonfragile abi.
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006919CodeGen::RValue
6920CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00006921 ReturnValueSlot Return,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006922 QualType ResultType,
6923 Selector Sel,
6924 llvm::Value *Receiver,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006925 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00006926 const ObjCInterfaceDecl *Class,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00006927 const ObjCMethodDecl *Method) {
John McCall9e8bb002011-05-14 03:10:52 +00006928 return isVTableDispatchedSelector(Sel)
6929 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006930 Receiver, CGF.getContext().getObjCIdType(),
John McCall9e8bb002011-05-14 03:10:52 +00006931 false, CallArgs, Method)
6932 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00006933 EmitSelector(CGF, Sel),
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006934 Receiver, CGF.getContext().getObjCIdType(),
John McCall1e3157b2015-09-10 22:27:50 +00006935 false, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian3d9296e2009-02-04 00:22:57 +00006936}
6937
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006938llvm::GlobalVariable *
Benjamin Kramer0772c422016-02-13 13:42:54 +00006939CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name, bool Weak) {
Rafael Espindola554256c2014-02-26 22:25:45 +00006940 llvm::GlobalValue::LinkageTypes L =
6941 Weak ? llvm::GlobalValue::ExternalWeakLinkage
6942 : llvm::GlobalValue::ExternalLinkage;
6943
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006944 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
6945
Rafael Espindola554256c2014-02-26 22:25:45 +00006946 if (!GV)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006947 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
Craig Topper8a13c412014-05-21 05:09:00 +00006948 false, L, nullptr, Name);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006949
Rafael Espindola554256c2014-02-26 22:25:45 +00006950 assert(GV->getLinkage() == L);
Daniel Dunbarc6928bb2009-03-01 04:40:10 +00006951 return GV;
6952}
6953
John McCall882987f2013-02-28 19:01:20 +00006954llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
Rafael Espindola554256c2014-02-26 22:25:45 +00006955 IdentifierInfo *II,
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006956 bool Weak,
6957 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00006958 CharUnits Align = CGF.getPointerAlign();
John McCall31168b02011-06-15 23:02:42 +00006959 llvm::GlobalVariable *&Entry = ClassReferences[II];
6960
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00006961 if (!Entry) {
Saleem Abdulrasool1e6c4062016-05-16 05:06:49 +00006962 StringRef Name = ID ? ID->getObjCRuntimeNameAsString() : II->getName();
6963 std::string ClassName = (getClassSymbolPrefix() + Name).str();
Rafael Espindola554256c2014-02-26 22:25:45 +00006964 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00006965 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
6966 false, llvm::GlobalValue::PrivateLinkage,
6967 ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
John McCall7f416cc2015-09-08 08:05:57 +00006968 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006969 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00006970 CGM.addCompilerUsedGlobal(Entry);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006971 }
John McCall7f416cc2015-09-08 08:05:57 +00006972 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006973}
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00006974
John McCall882987f2013-02-28 19:01:20 +00006975llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00006976 const ObjCInterfaceDecl *ID) {
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006977 // If the class has the objc_runtime_visible attribute, we need to
6978 // use the Objective-C runtime to get the class.
6979 if (ID->hasAttr<ObjCRuntimeVisibleAttr>())
6980 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);
6981
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006982 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
John McCall31168b02011-06-15 23:02:42 +00006983}
6984
6985llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
John McCall882987f2013-02-28 19:01:20 +00006986 CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00006987 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
Hans Wennborgdcfba332015-10-06 23:40:43 +00006988 return EmitClassRefFromId(CGF, II, false, nullptr);
John McCall31168b02011-06-15 23:02:42 +00006989}
6990
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006991llvm::Value *
John McCall882987f2013-02-28 19:01:20 +00006992CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006993 const ObjCInterfaceDecl *ID) {
John McCall7f416cc2015-09-08 08:05:57 +00006994 CharUnits Align = CGF.getPointerAlign();
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006995 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00006996
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00006997 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006998 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
6999 ClassName += ID->getObjCRuntimeNameAsString();
7000 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
Fariborz Jahanianf322f2f2014-03-11 00:25:05 +00007001 ID->isWeakImported());
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007002 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
7003 false, llvm::GlobalValue::PrivateLinkage,
7004 ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007005 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar508a7dd2009-04-18 08:51:00 +00007006 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007007 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007008 }
John McCall7f416cc2015-09-08 08:05:57 +00007009 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007010}
7011
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007012/// EmitMetaClassRef - Return a Value * of the address of _class_t
7013/// meta-data
7014///
John McCall882987f2013-02-28 19:01:20 +00007015llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007016 const ObjCInterfaceDecl *ID,
7017 bool Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00007018 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007019 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
Rafael Espindola21039aa2014-02-27 16:26:32 +00007020 if (!Entry) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007021 llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
7022 MetaClassName += ID->getObjCRuntimeNameAsString();
Fariborz Jahanian0b3bc242014-06-10 17:08:04 +00007023 llvm::GlobalVariable *MetaClassGV =
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007024 GetClassGlobal(MetaClassName.str(), Weak);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007025
Rafael Espindola21039aa2014-02-27 16:26:32 +00007026 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
Rafael Espindola5179a4e2014-02-27 19:01:11 +00007027 false, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007028 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
John McCall7f416cc2015-09-08 08:05:57 +00007029 Entry->setAlignment(Align.getQuantity());
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007030
Rafael Espindola21039aa2014-02-27 16:26:32 +00007031 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Rafael Espindola060062a2014-03-06 22:15:10 +00007032 CGM.addCompilerUsedGlobal(Entry);
Rafael Espindola21039aa2014-02-27 16:26:32 +00007033 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007034
John McCall7f416cc2015-09-08 08:05:57 +00007035 return CGF.Builder.CreateAlignedLoad(Entry, Align);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007036}
7037
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007038/// GetClass - Return a reference to the class for the given interface
7039/// decl.
John McCall882987f2013-02-28 19:01:20 +00007040llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007041 const ObjCInterfaceDecl *ID) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007042 if (ID->isWeakImported()) {
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00007043 llvm::SmallString<64> ClassName(getClassSymbolPrefix());
7044 ClassName += ID->getObjCRuntimeNameAsString();
7045 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
Nick Lewycky9a441642014-02-27 00:36:00 +00007046 (void)ClassGV;
Rafael Espindolab3262952014-05-09 00:43:37 +00007047 assert(ClassGV->hasExternalWeakLinkage());
Fariborz Jahanian95ace552009-11-17 22:42:00 +00007048 }
7049
John McCall882987f2013-02-28 19:01:20 +00007050 return EmitClassRef(CGF, ID);
Fariborz Jahanian33f66e62009-02-05 20:41:40 +00007051}
7052
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007053/// Generates a message send where the super is the receiver. This is
7054/// a message send to self with special delivery semantics indicating
7055/// which class's method should be called.
7056CodeGen::RValue
7057CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00007058 ReturnValueSlot Return,
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007059 QualType ResultType,
7060 Selector Sel,
7061 const ObjCInterfaceDecl *Class,
7062 bool isCategoryImpl,
7063 llvm::Value *Receiver,
7064 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00007065 const CodeGen::CallArgList &CallArgs,
7066 const ObjCMethodDecl *Method) {
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007067 // ...
7068 // Create and init a super structure; this is a (receiver, class)
7069 // pair we will pass to objc_msgSendSuper.
John McCall7f416cc2015-09-08 08:05:57 +00007070 Address ObjCSuper =
7071 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
7072 "objc_super");
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007073
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007074 llvm::Value *ReceiverAsObject =
7075 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007076 CGF.Builder.CreateStore(
7077 ReceiverAsObject,
John McCall7f416cc2015-09-08 08:05:57 +00007078 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007079
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007080 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00007081 llvm::Value *Target;
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007082 if (IsClassMessage)
Fariborz Jahanian85b99da2014-08-28 17:05:17 +00007083 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
Fariborz Jahanian27678b02012-10-10 23:11:18 +00007084 else
John McCall882987f2013-02-28 19:01:20 +00007085 Target = EmitSuperClassRef(CGF, Class);
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007086
Mike Stump18bb9282009-05-16 07:57:57 +00007087 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
7088 // ObjCTypes types.
Chris Lattner2192fe52011-07-18 04:24:23 +00007089 llvm::Type *ClassTy =
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007090 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
7091 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00007092 CGF.Builder.CreateStore(
John McCall7f416cc2015-09-08 08:05:57 +00007093 Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007094
John McCall9e8bb002011-05-14 03:10:52 +00007095 return (isVTableDispatchedSelector(Sel))
7096 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
John McCall7f416cc2015-09-08 08:05:57 +00007097 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall9e8bb002011-05-14 03:10:52 +00007098 true, CallArgs, Method)
7099 : EmitMessageSend(CGF, Return, ResultType,
John McCall882987f2013-02-28 19:01:20 +00007100 EmitSelector(CGF, Sel),
John McCall7f416cc2015-09-08 08:05:57 +00007101 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,
John McCall1e3157b2015-09-10 22:27:50 +00007102 true, CallArgs, Method, Class, ObjCTypes);
Fariborz Jahanian6b7cd6e2009-02-06 20:09:23 +00007103}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007104
John McCall882987f2013-02-28 19:01:20 +00007105llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007106 Selector Sel) {
7107 Address Addr = EmitSelectorAddr(CGF, Sel);
7108
7109 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);
7110 LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
7111 llvm::MDNode::get(VMContext, None));
7112 return LI;
7113}
7114
7115Address CGObjCNonFragileABIMac::EmitSelectorAddr(CodeGenFunction &CGF,
7116 Selector Sel) {
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007117 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007118
John McCall7f416cc2015-09-08 08:05:57 +00007119 CharUnits Align = CGF.getPointerAlign();
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007120 if (!Entry) {
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007121 llvm::Constant *Casted =
7122 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
7123 ObjCTypes.SelectorPtrTy);
Rafael Espindola8b27bdb2014-11-06 13:30:38 +00007124 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
7125 false, llvm::GlobalValue::PrivateLinkage,
7126 Casted, "OBJC_SELECTOR_REFERENCES_");
Michael Gottesman5c205962013-02-05 23:08:45 +00007127 Entry->setExternallyInitialized(true);
Fariborz Jahanian5d5ed2d2009-05-11 19:25:47 +00007128 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
John McCall7f416cc2015-09-08 08:05:57 +00007129 Entry->setAlignment(Align.getQuantity());
Rafael Espindola060062a2014-03-06 22:15:10 +00007130 CGM.addCompilerUsedGlobal(Entry);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007131 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007132
John McCall7f416cc2015-09-08 08:05:57 +00007133 return Address(Entry, Align);
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007134}
John McCall7f416cc2015-09-08 08:05:57 +00007135
Fariborz Jahanian06292952009-02-16 22:52:32 +00007136/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007137/// objc_assign_ivar (id src, id *dst, ptrdiff_t)
Fariborz Jahanian06292952009-02-16 22:52:32 +00007138///
7139void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00007140 llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +00007141 Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00007142 llvm::Value *ivarOffset) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007143 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007144 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007145 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007146 assert(Size <= 8 && "does not support size > 8");
7147 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7148 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007149 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7150 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007151 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7152 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007153 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset };
John McCall882987f2013-02-28 19:01:20 +00007154 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007155}
7156
7157/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
7158/// objc_assign_strongCast (id src, id *dst)
7159///
7160void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007161 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007162 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007163 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007164 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007165 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007166 assert(Size <= 8 && "does not support size > 8");
7167 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007168 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007169 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7170 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007171 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7172 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007173 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007174 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
7175 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007176}
7177
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007178void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007179 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007180 Address DestPtr,
7181 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007182 llvm::Value *Size) {
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007183 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
7184 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007185 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size };
John McCall882987f2013-02-28 19:01:20 +00007186 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007187}
7188
Fariborz Jahanian06292952009-02-16 22:52:32 +00007189/// EmitObjCWeakRead - Code gen for loading value of a __weak
7190/// object: objc_read_weak (id *src)
7191///
7192llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007193 CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007194 Address AddrWeakObj) {
7195 llvm::Type *DestTy = AddrWeakObj.getElementType();
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007196 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007197 llvm::Value *read_weak =
7198 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
John McCall7f416cc2015-09-08 08:05:57 +00007199 AddrWeakObj.getPointer(), "weakread");
Eli Friedmana374b682009-03-07 03:57:15 +00007200 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian06292952009-02-16 22:52:32 +00007201 return read_weak;
7202}
7203
7204/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
7205/// objc_assign_weak (id src, id *dst)
7206///
7207void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007208 llvm::Value *src, Address dst) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007209 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007210 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007211 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007212 assert(Size <= 8 && "does not support size > 8");
7213 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7214 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007215 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7216 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007217 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7218 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007219 llvm::Value *args[] = { src, dst.getPointer() };
John McCall882987f2013-02-28 19:01:20 +00007220 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
7221 args, "weakassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007222}
7223
7224/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
7225/// objc_assign_global (id src, id *dst)
7226///
7227void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00007228 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00007229 bool threadlocal) {
Chris Lattner2192fe52011-07-18 04:24:23 +00007230 llvm::Type * SrcTy = src->getType();
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007231 if (!isa<llvm::PointerType>(SrcTy)) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00007232 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
Fariborz Jahanianaedcfa42009-03-23 19:10:40 +00007233 assert(Size <= 8 && "does not support size > 8");
7234 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
7235 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian1b074a32009-03-13 00:42:52 +00007236 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
7237 }
Fariborz Jahanian06292952009-02-16 22:52:32 +00007238 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
7239 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00007240 llvm::Value *args[] = { src, dst.getPointer() };
Fariborz Jahanian217af242010-07-20 20:30:03 +00007241 if (!threadlocal)
John McCall882987f2013-02-28 19:01:20 +00007242 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
7243 args, "globalassign");
Fariborz Jahanian217af242010-07-20 20:30:03 +00007244 else
John McCall882987f2013-02-28 19:01:20 +00007245 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
7246 args, "threadlocalassign");
Fariborz Jahanian06292952009-02-16 22:52:32 +00007247}
Fariborz Jahanian74b77222009-02-11 20:51:17 +00007248
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007249void
John McCallbd309292010-07-06 01:34:17 +00007250CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
7251 const ObjCAtSynchronizedStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007252 EmitAtSynchronizedStmt(CGF, S,
7253 cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
7254 cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
John McCallbd309292010-07-06 01:34:17 +00007255}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007256
John McCall2ca705e2010-07-24 00:37:23 +00007257llvm::Constant *
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00007258CGObjCNonFragileABIMac::GetEHType(QualType T) {
John McCall2ca705e2010-07-24 00:37:23 +00007259 // There's a particular fixed type info for 'id'.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007260 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
7261 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007262 if (!IDEHType) {
John McCall2ca705e2010-07-24 00:37:23 +00007263 IDEHType =
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007264 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
7265 llvm::GlobalValue::ExternalLinkage, nullptr,
7266 "OBJC_EHTYPE_id");
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007267 if (CGM.getTriple().isOSBinFormatCOFF())
7268 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));
7269 }
John McCall2ca705e2010-07-24 00:37:23 +00007270 return IDEHType;
7271 }
7272
7273 // All other types should be Objective-C interface pointer types.
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007274 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
John McCall2ca705e2010-07-24 00:37:23 +00007275 assert(PT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007276
John McCall2ca705e2010-07-24 00:37:23 +00007277 const ObjCInterfaceType *IT = PT->getInterfaceType();
7278 assert(IT && "Invalid @catch type.");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007279
John McCall2ca705e2010-07-24 00:37:23 +00007280 return GetInterfaceEHType(IT->getDecl(), false);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007281}
John McCall2ca705e2010-07-24 00:37:23 +00007282
John McCallbd309292010-07-06 01:34:17 +00007283void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
7284 const ObjCAtTryStmt &S) {
David Chisnall3e575602011-03-25 17:46:35 +00007285 EmitTryCatchStmt(CGF, S,
7286 cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
7287 cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
7288 cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
Daniel Dunbar0b0dcd92009-02-24 07:47:38 +00007289}
7290
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007291/// EmitThrowStmt - Generate code for a throw statement.
7292void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007293 const ObjCAtThrowStmt &S,
7294 bool ClearInsertionPoint) {
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007295 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00007296 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00007297 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
John McCall882987f2013-02-28 19:01:20 +00007298 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
John McCall17afe452010-10-16 08:21:07 +00007299 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007300 } else {
John McCall882987f2013-02-28 19:01:20 +00007301 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
John McCall17afe452010-10-16 08:21:07 +00007302 .setDoesNotReturn();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007303 }
7304
John McCall17afe452010-10-16 08:21:07 +00007305 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00007306 if (ClearInsertionPoint)
7307 CGF.Builder.ClearInsertionPoint();
Anders Carlsson9ab53d12009-02-16 22:59:18 +00007308}
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007309
John McCall2ca705e2010-07-24 00:37:23 +00007310llvm::Constant *
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007311CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007312 bool ForDefinition) {
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007313 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007314 StringRef ClassName = ID->getObjCRuntimeNameAsString();
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007315
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007316 // If we don't need a definition, return the entry if found or check
7317 // if we use an external reference.
7318 if (!ForDefinition) {
7319 if (Entry)
7320 return Entry;
Daniel Dunbard7beeea2009-04-07 06:43:45 +00007321
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007322 // If this type (or a super class) has the __objc_exception__
7323 // attribute, emit an external reference.
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007324 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {
7325 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();
7326 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
7327 false, llvm::GlobalValue::ExternalLinkage,
7328 nullptr, EHTypeName);
7329 if (CGM.getTriple().isOSBinFormatCOFF()) {
7330 if (ID->hasAttr<DLLExportAttr>())
7331 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7332 else if (ID->hasAttr<DLLImportAttr>())
7333 Entry->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7334 }
7335 return Entry;
7336 }
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007337 }
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007338
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007339 // Otherwise we need to either make a new entry or fill in the initializer.
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007340 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007341
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007342 std::string VTableName = "objc_ehtype_vtable";
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007343 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007344 if (!VTableGV) {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007345 VTableGV =
7346 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,
7347 llvm::GlobalValue::ExternalLinkage, nullptr,
7348 VTableName);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007349 if (CGM.getTriple().isOSBinFormatCOFF())
7350 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));
7351 }
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007352
Chris Lattnerece04092012-02-07 00:39:47 +00007353 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
Benjamin Kramer22d24c22011-10-15 12:20:02 +00007354 llvm::Constant *Values[] = {
David Blaikiee3b172a2015-04-02 18:55:21 +00007355 llvm::ConstantExpr::getGetElementPtr(VTableGV->getValueType(), VTableGV,
7356 VTableIdx),
7357 GetClassName(ID->getObjCRuntimeNameAsString()),
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007358 GetClassGlobal((getClassSymbolPrefix() + ClassName).str()),
7359 };
7360 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007361
Rafael Espindola554256c2014-02-26 22:25:45 +00007362 llvm::GlobalValue::LinkageTypes L = ForDefinition
7363 ? llvm::GlobalValue::ExternalLinkage
7364 : llvm::GlobalValue::WeakAnyLinkage;
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007365 if (Entry) {
7366 Entry->setInitializer(Init);
7367 } else {
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007368 Entry =
7369 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, L,
7370 Init, ("OBJC_EHTYPE_$_" + ClassName).str());
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007371 if (CGM.getTriple().isOSBinFormatCOFF())
7372 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
7373 if (ID->hasAttr<DLLExportAttr>())
7374 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007375 }
Rafael Espindola554256c2014-02-26 22:25:45 +00007376 assert(Entry->getLinkage() == L);
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007377
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00007378 if (!CGM.getTriple().isOSBinFormatCOFF())
7379 if (ID->getVisibility() == HiddenVisibility)
7380 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Saleem Abdulrasoole5f3eae2016-07-17 22:27:38 +00007381
7382 const auto &DL = CGM.getDataLayout();
7383 Entry->setAlignment(DL.getABITypeAlignment(ObjCTypes.EHTypeTy));
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007384
Rafael Espindola554256c2014-02-26 22:25:45 +00007385 if (ForDefinition)
Daniel Dunbar8f28d012009-04-08 04:21:03 +00007386 Entry->setSection("__DATA,__objc_const");
Daniel Dunbarb1559a42009-03-01 04:46:24 +00007387
7388 return Entry;
7389}
Daniel Dunbar59e476b2009-08-03 17:06:42 +00007390
Daniel Dunbar8b8683f2008-08-12 00:12:39 +00007391/* *** */
7392
Daniel Dunbarb036db82008-08-13 03:21:16 +00007393CodeGen::CGObjCRuntime *
7394CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00007395 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
7396 case ObjCRuntime::FragileMacOSX:
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007397 return new CGObjCMac(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00007398
7399 case ObjCRuntime::MacOSX:
7400 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00007401 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00007402 return new CGObjCNonFragileABIMac(CGM);
7403
David Chisnallb601c962012-07-03 20:49:52 +00007404 case ObjCRuntime::GNUstep:
7405 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +00007406 case ObjCRuntime::ObjFW:
John McCall5fb5df92012-06-20 06:18:46 +00007407 llvm_unreachable("these runtimes are not Mac runtimes");
7408 }
7409 llvm_unreachable("bad runtime");
Daniel Dunbar303e2c22008-08-11 02:45:11 +00007410}