blob: 2b40b9ede92ea29ad466afae17b910899efadde1 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
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 GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
John McCall5ad74072017-03-02 20:04:19 +000021#include "clang/CodeGen/ConstantInitBuilder.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000037#include "llvm/Support/ConvertUTF.h"
Chris Lattner8d3f4a42009-01-27 05:06:01 +000038
Chris Lattner87ab27d2008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000041
Chris Lattnerb7256cd2008-03-01 08:50:34 +000042namespace {
David Chisnall34d00052011-03-26 11:48:37 +000043/// Class that lazily initialises the runtime function. Avoids inserting the
44/// types and the function declaration into a module if they're not used, and
45/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000046class LazyRuntimeFunction {
47 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000048 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000049 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000050 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000051
52public:
53 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
56 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000057 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000058
David Blaikie7d9e7922015-05-18 22:51:39 +000059 /// Initialises the lazy function with the name, return type, and the types
60 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000061 template <typename... Tys>
62 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
63 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000064 CGM = Mod;
65 FunctionName = name;
66 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000067 if(sizeof...(Tys)) {
68 SmallVector<llvm::Type *, 8> ArgTys({Types...});
69 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
70 }
71 else {
72 FTy = llvm::FunctionType::get(RetTy, None, false);
73 }
David Blaikie7d9e7922015-05-18 22:51:39 +000074 }
David Blaikiebf178d32015-05-19 21:31:34 +000075
76 llvm::FunctionType *getType() { return FTy; }
77
David Blaikie7d9e7922015-05-18 22:51:39 +000078 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 /// LLVM constant.
80 operator llvm::Constant *() {
81 if (!Function) {
82 if (!FunctionName)
83 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000084 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
86 return Function;
87 }
88 operator llvm::Function *() {
89 return cast<llvm::Function>((llvm::Constant *)*this);
90 }
David Chisnalld7972f52011-03-23 16:36:54 +000091};
92
93
David Chisnall34d00052011-03-26 11:48:37 +000094/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +000095/// Objective-C support that are specific to the GNU family of runtimes (GCC,
96/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +000097class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +000098protected:
David Chisnall34d00052011-03-26 11:48:37 +000099 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000100 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000101 /// strut objc_super. Used for sending messages to super. This structure
102 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000103 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000104 /// struct objc_super*. The type of the argument to the superclass message
105 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000106 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
108 /// SEL is included in a header somewhere, in which case it will be whatever
109 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000110 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
112 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// Pointer to i8 - LLVM type of char*, for all of the places where the
115 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000116 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000117 /// Instance Method Pointer type. This is a pointer to a function that takes,
118 /// at a minimum, an object and a selector, and is the generic type for
119 /// Objective-C methods. Due to differences between variadic / non-variadic
120 /// calling conventions, it must always be cast to the correct type before
121 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
124 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
125 /// but if the runtime header declaring it is included then it may be a
126 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000127 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000128 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
129 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000130 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000131 /// The clang type of id. Used when using the clang CGCall infrastructure to
132 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000133 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000134 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000135 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000136 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
137 /// used in the code to document the difference between i8* meaning a pointer
138 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// LLVM type for C long type. The runtime uses this in a lot of places where
141 /// it should be using intptr_t, but we can't fix this without breaking
142 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000143 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000145 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000146 /// LLVM type for C intptr_t.
147 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000149 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000150 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
151 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000152 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000154 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000155 /// 32-bit integer type, to save us needing to look it up every time it's used.
156 llvm::IntegerType *Int32Ty;
157 /// 64-bit integer type, to save us needing to look it up every time it's used.
158 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000159 /// Metadata kind used to tie method lookups to message sends. The GNUstep
160 /// runtime provides some LLVM passes that can use this to do things like
161 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000162 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000163
David Chisnall34d00052011-03-26 11:48:37 +0000164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000167 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
168 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000169 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
170 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000171 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000172
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Emits a linkonce_odr string, whose name is the prefix followed by the
174 /// string value. This allows the linker to combine the strings between
175 /// different modules. Used for EH typeinfo names, selector strings, and a
176 /// few other things.
Bjorn Pettersson84466332018-05-22 08:16:45 +0000177 llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
178 std::string Name = Prefix.str() + Str;
179 auto *ConstStr = TheModule.getGlobalVariable(Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000180 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000181 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
Bjorn Pettersson84466332018-05-22 08:16:45 +0000182 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
183 llvm::GlobalValue::LinkOnceODRLinkage,
184 value, Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000185 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000186 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
187 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
Bjorn Pettersson84466332018-05-22 08:16:45 +0000190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
192 /// first argument.
193 llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
194 CharUnits Align,
195 StringRef Name="",
196 llvm::GlobalValue::LinkageTypes linkage
197 =llvm::GlobalValue::InternalLinkage) {
198 auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
199 linkage, C, Name);
200 GV->setAlignment(Align.getQuantity());
201 return GV;
202 }
203
David Chisnalla5f59412012-10-16 15:11:55 +0000204 /// Returns a property name and encoding string.
205 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
206 const Decl *Container) {
Bjorn Pettersson84466332018-05-22 08:16:45 +0000207 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
208 if ((R.getKind() == ObjCRuntime::GNUstep) &&
209 (R.getVersion() >= VersionTuple(1, 6))) {
David Chisnalla5f59412012-10-16 15:11:55 +0000210 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000211 std::string TypeStr =
212 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000213 NameAndAttributes += '\0';
214 NameAndAttributes += TypeStr.length() + 3;
215 NameAndAttributes += TypeStr;
216 NameAndAttributes += '\0';
217 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000218 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000219 }
220 return MakeConstantString(PD->getNameAsString());
221 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000222
David Chisnallbeb80132013-02-28 13:59:29 +0000223 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000224 void PushPropertyAttributes(ConstantStructBuilder &Fields,
Bjorn Pettersson84466332018-05-22 08:16:45 +0000225 ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000226 isDynamic=true) {
227 int attrs = property->getPropertyAttributes();
228 // For read-only properties, clear the copy and retain flags
229 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
230 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
231 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
232 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
233 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
234 }
235 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000236 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000237 attrs >>= 8;
238 attrs <<= 2;
239 // For protocol properties, synthesized and dynamic have no meaning, so we
240 // reuse these flags to indicate that this is a protocol property (both set
241 // has no meaning, as a property can't be both synthesized and dynamic)
242 attrs |= isSynthesized ? (1<<0) : 0;
243 attrs |= isDynamic ? (1<<1) : 0;
244 // The second field is the next four fields left shifted by two, with the
245 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000246 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000247 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000248 Fields.addInt(Int8Ty, 0);
249 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000250 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000251
David Chisnall34d00052011-03-26 11:48:37 +0000252 /// Ensures that the value has the required type, by inserting a bitcast if
253 /// required. This function lets us avoid inserting bitcasts that are
254 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000255 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000256 if (V->getType() == Ty) return V;
257 return B.CreateBitCast(V, Ty);
258 }
John McCall7f416cc2015-09-08 08:05:57 +0000259 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
260 if (V.getType() == Ty) return V;
261 return B.CreateBitCast(V, Ty);
262 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000263
David Chisnall76803412011-03-23 22:52:06 +0000264 // Some zeros used for GEPs in lots of places.
265 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000266 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000267 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000268 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000269 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000270
Bjorn Pettersson84466332018-05-22 08:16:45 +0000271private:
David Chisnall34d00052011-03-26 11:48:37 +0000272 /// Placeholder for the class. Lots of things refer to the class before we've
273 /// actually emitted it. We use this alias as a placeholder, and then replace
274 /// it with a pointer to the class structure before finally emitting the
275 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000276 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000277 /// Placeholder for the metaclass. Lots of things refer to the class before
278 /// we've / actually emitted it. We use this alias as a placeholder, and then
279 /// replace / it with a pointer to the metaclass structure before finally
280 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000281 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000282 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000283 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000284 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000285 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000286 /// All of the Objective-C constant strings that have been generated for this
287 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000288 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000289 /// Map from string values to Objective-C constant strings in the output.
290 /// Used to prevent emitting Objective-C strings more than once. This should
291 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000292 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000293 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000294 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000295 /// For each variant of a selector, we store the type encoding and a
296 /// placeholder value. For an untyped selector, the type will be the empty
297 /// string. Selector references are all done via the module's selector table,
298 /// so we create an alias as a placeholder and then replace it with the real
299 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000300 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// Type of the selector map. This is roughly equivalent to the structure
302 /// used in the GNUstep runtime, which maintains a list of all of the valid
303 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000304 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000305 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000306 /// A map from selectors to selector types. This allows us to emit all
307 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000308 SelectorMap SelectorTable;
309
David Chisnall34d00052011-03-26 11:48:37 +0000310 /// Selectors related to memory management. When compiling in GC mode, we
311 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000312 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000313 /// Runtime functions used for memory management in GC mode. Note that clang
314 /// supports code generation for calling these functions, but neither GNU
315 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000316 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
317 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000318
David Chisnall92d436b2012-01-31 18:59:20 +0000319 typedef std::pair<std::string, std::string> ClassAliasPair;
320 /// All classes that have aliases set for them.
321 std::vector<ClassAliasPair> ClassAliases;
322
David Chisnalld3858d62011-03-25 11:57:33 +0000323protected:
David Chisnall34d00052011-03-26 11:48:37 +0000324 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000325 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000326 /// Function used for rethrowing exceptions, used at the end of \@finally or
327 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000328 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000329 /// Function called when entering a catch function. This is required for
330 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000331 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000332 /// Function called when exiting from a catch block. Used to do exception
333 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000334 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000335 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000336 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000337 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000338 LazyRuntimeFunction SyncExitFn;
339
David Chisnalld3858d62011-03-25 11:57:33 +0000340private:
David Chisnall34d00052011-03-26 11:48:37 +0000341 /// Function called if fast enumeration detects that the collection is
342 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000343 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000344 /// Function for implementing synthesized property getters that return an
345 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000346 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Function for implementing synthesized property setters that return an
348 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000349 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000350 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000351 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000352 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000353 LazyRuntimeFunction SetStructPropertyFn;
354
David Chisnall34d00052011-03-26 11:48:37 +0000355 /// The version of the runtime that this class targets. Must match the
356 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000357 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000358 /// The version of the protocol class. Used to differentiate between ObjC1
359 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
360 /// components and can not contain declared properties. We always emit
361 /// Objective-C 2 property structures, but we have to pretend that they're
362 /// Objective-C 1 property structures when targeting the GCC runtime or it
363 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000364 const int ProtocolVersion;
Bjorn Pettersson84466332018-05-22 08:16:45 +0000365
David Chisnall34d00052011-03-26 11:48:37 +0000366 /// Generates an instance variable list structure. This is a structure
367 /// containing a size and an array of structures containing instance variable
368 /// metadata. This is used purely for introspection in the fragile ABI. In
369 /// the non-fragile ABI, it's used for instance variable fixup.
Bjorn Pettersson84466332018-05-22 08:16:45 +0000370 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
371 ArrayRef<llvm::Constant *> IvarTypes,
372 ArrayRef<llvm::Constant *> IvarOffsets);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000373
David Chisnall34d00052011-03-26 11:48:37 +0000374 /// Generates a method list structure. This is a structure containing a size
375 /// and an array of structures containing method metadata.
376 ///
377 /// This structure is used by both classes and categories, and contains a next
378 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000379 llvm::Constant *GenerateMethodList(StringRef ClassName,
380 StringRef CategoryName,
Bjorn Pettersson84466332018-05-22 08:16:45 +0000381 ArrayRef<Selector> MethodSels,
382 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000383 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000384
James Dennettb9199ee2012-06-13 22:07:09 +0000385 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000386 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
387 /// real protocol.
Bjorn Pettersson84466332018-05-22 08:16:45 +0000388 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000389
David Chisnall34d00052011-03-26 11:48:37 +0000390 /// Generates a list of property metadata structures. This follows the same
391 /// pattern as method and instance variable metadata lists.
Bjorn Pettersson84466332018-05-22 08:16:45 +0000392 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
393 SmallVectorImpl<Selector> &InstanceMethodSels,
394 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000395
David Chisnall34d00052011-03-26 11:48:37 +0000396 /// Generates a list of referenced protocols. Classes, categories, and
397 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000398 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000399
David Chisnall34d00052011-03-26 11:48:37 +0000400 /// To ensure that all protocols are seen by the runtime, we add a category on
401 /// a class defined in the runtime, declaring no methods, but adopting the
402 /// protocols. This is a horribly ugly hack, but it allows us to collect all
403 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000404 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000405
David Chisnall34d00052011-03-26 11:48:37 +0000406 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000407 llvm::Constant *GenerateClassStructure(
408 llvm::Constant *MetaClass,
409 llvm::Constant *SuperClass,
410 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000411 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000412 llvm::Constant *Version,
413 llvm::Constant *InstanceSize,
414 llvm::Constant *IVars,
415 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000416 llvm::Constant *Protocols,
417 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000418 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000419 llvm::Constant *StrongIvarBitmap,
420 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000421 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000422
David Chisnall34d00052011-03-26 11:48:37 +0000423 /// Generates a method list. This is used by protocols to define the required
424 /// and optional methods.
Bjorn Pettersson84466332018-05-22 08:16:45 +0000425 llvm::Constant *GenerateProtocolMethodList(
426 ArrayRef<llvm::Constant *> MethodNames,
427 ArrayRef<llvm::Constant *> MethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000428
David Chisnall34d00052011-03-26 11:48:37 +0000429 /// Returns a selector with the specified type encoding. An empty string is
430 /// used to return an untyped selector (with the types field set to NULL).
Bjorn Pettersson84466332018-05-22 08:16:45 +0000431 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000432 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000433
David Chisnall34d00052011-03-26 11:48:37 +0000434 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000435 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
436 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000437 /// Emits a reference to a class. This allows the linker to object if there
438 /// is no class of the matching name.
Bjorn Pettersson84466332018-05-22 08:16:45 +0000439
440protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000441 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000442
David Chisnall920e83b2011-06-29 13:16:41 +0000443 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000444 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000445 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000446
David Chisnall34d00052011-03-26 11:48:37 +0000447 /// Looks up the method for sending a message to the specified object. This
448 /// mechanism differs between the GCC and GNU runtimes, so this method must be
449 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000450 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
451 llvm::Value *&Receiver,
452 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000453 llvm::MDNode *node,
454 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000455
David Chisnallcdd207e2011-10-04 15:35:30 +0000456 /// Looks up the method for sending a message to a superclass. This
457 /// mechanism differs between the GCC and GNU runtimes, so this method must
458 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000459 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000460 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000461 llvm::Value *cmd,
462 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000463
David Chisnallcdd207e2011-10-04 15:35:30 +0000464 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466 /// bits set to their values, LSB first, while larger ones are stored in a
467 /// structure of this / form:
468 ///
469 /// struct { int32_t length; int32_t values[length]; };
470 ///
471 /// The values in the array are stored in host-endian format, with the least
472 /// significant bit being assumed to come first in the bitfield. Therefore,
473 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000475 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000476
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000477public:
David Chisnalld7972f52011-03-23 16:36:54 +0000478 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Bjorn Pettersson84466332018-05-22 08:16:45 +0000479 unsigned protocolClassVersion);
David Chisnalld7972f52011-03-23 16:36:54 +0000480
John McCall7f416cc2015-09-08 08:05:57 +0000481 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000482
Craig Topper4f12f102014-03-12 06:41:41 +0000483 RValue
484 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
485 QualType ResultType, Selector Sel,
486 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000487 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000488 const ObjCMethodDecl *Method) override;
489 RValue
490 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
491 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000492 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000493 bool isCategoryImpl, llvm::Value *Receiver,
494 bool IsClassMessage, const CallArgList &CallArgs,
495 const ObjCMethodDecl *Method) override;
496 llvm::Value *GetClass(CodeGenFunction &CGF,
497 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000498 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
499 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000500 llvm::Value *GetSelector(CodeGenFunction &CGF,
501 const ObjCMethodDecl *Method) override;
502 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000503
Craig Topper4f12f102014-03-12 06:41:41 +0000504 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
505 const ObjCContainerDecl *CD) override;
506 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
507 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
508 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
509 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
510 const ObjCProtocolDecl *PD) override;
511 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
512 llvm::Function *ModuleInitFunction() override;
513 llvm::Constant *GetPropertyGetFunction() override;
514 llvm::Constant *GetPropertySetFunction() override;
515 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
516 bool copy) override;
517 llvm::Constant *GetSetStructFunction() override;
518 llvm::Constant *GetGetStructFunction() override;
519 llvm::Constant *GetCppAtomicObjectGetFunction() override;
520 llvm::Constant *GetCppAtomicObjectSetFunction() override;
521 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000522
Craig Topper4f12f102014-03-12 06:41:41 +0000523 void EmitTryStmt(CodeGenFunction &CGF,
524 const ObjCAtTryStmt &S) override;
525 void EmitSynchronizedStmt(CodeGenFunction &CGF,
526 const ObjCAtSynchronizedStmt &S) override;
527 void EmitThrowStmt(CodeGenFunction &CGF,
528 const ObjCAtThrowStmt &S,
529 bool ClearInsertionPoint=true) override;
530 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000532 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000533 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000534 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000535 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000536 bool threadlocal=false) override;
537 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000538 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000539 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000540 llvm::Value *src, Address dest) override;
541 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
542 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000543 llvm::Value *Size) override;
544 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
545 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
546 unsigned CVRQualifiers) override;
547 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
548 const ObjCInterfaceDecl *Interface,
549 const ObjCIvarDecl *Ivar) override;
550 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
551 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
552 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000553 return NULLPtr;
554 }
Craig Topper4f12f102014-03-12 06:41:41 +0000555 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
556 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000557 return NULLPtr;
558 }
Craig Topper4f12f102014-03-12 06:41:41 +0000559
560 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000561 return NULLPtr;
562 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000563};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000564
David Chisnall34d00052011-03-26 11:48:37 +0000565/// Class representing the legacy GCC Objective-C ABI. This is the default when
566/// -fobjc-nonfragile-abi is not specified.
567///
568/// The GCC ABI target actually generates code that is approximately compatible
569/// with the new GNUstep runtime ABI, but refrains from using any features that
570/// would not work with the GCC runtime. For example, clang always generates
571/// the extended form of the class structure, and the extra fields are simply
572/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000573class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000574 /// The GCC ABI message lookup function. Returns an IMP pointing to the
575 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000576 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000577 /// The GCC ABI superclass message lookup function. Takes a pointer to a
578 /// structure describing the receiver and the class, and a selector as
579 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000580 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000581
David Chisnall76803412011-03-23 22:52:06 +0000582protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000583 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
584 llvm::Value *cmd, llvm::MDNode *node,
585 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000586 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000587 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000588 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000589 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000590 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000591 imp->setMetadata(msgSendMDKind, node);
592 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000593 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000594
John McCall7f416cc2015-09-08 08:05:57 +0000595 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000596 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000597 CGBuilderTy &Builder = CGF.Builder;
598 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
599 PtrToObjCSuperTy).getPointer(), cmd};
600 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
601 }
602
603public:
604 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
605 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000606 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000607 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
608 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000609 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000610 }
David Chisnalld7972f52011-03-23 16:36:54 +0000611};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000612
David Chisnall34d00052011-03-26 11:48:37 +0000613/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000614class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000615 /// The slot lookup function. Returns a pointer to a cacheable structure
616 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000617 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000618 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
619 /// a structure describing the receiver and the class, and a selector as
620 /// arguments. Returns the slot for the corresponding method. Superclass
621 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000622 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000623 /// Specialised function for setting atomic retain properties
624 LazyRuntimeFunction SetPropertyAtomic;
625 /// Specialised function for setting atomic copy properties
626 LazyRuntimeFunction SetPropertyAtomicCopy;
627 /// Specialised function for setting nonatomic retain properties
628 LazyRuntimeFunction SetPropertyNonAtomic;
629 /// Specialised function for setting nonatomic copy properties
630 LazyRuntimeFunction SetPropertyNonAtomicCopy;
631 /// Function to perform atomic copies of C++ objects with nontrivial copy
632 /// constructors from Objective-C ivars.
633 LazyRuntimeFunction CxxAtomicObjectGetFn;
634 /// Function to perform atomic copies of C++ objects with nontrivial copy
635 /// constructors to Objective-C ivars.
636 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000637 /// Type of an slot structure pointer. This is returned by the various
638 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000639 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000640
John McCallc31d8932012-11-14 09:08:34 +0000641 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000642 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000643
David Chisnall76803412011-03-23 22:52:06 +0000644 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000645 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
646 llvm::Value *cmd, llvm::MDNode *node,
647 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000648 CGBuilderTy &Builder = CGF.Builder;
649 llvm::Function *LookupFn = SlotLookupFn;
650
651 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000652 Address ReceiverPtr =
653 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000654 Builder.CreateStore(Receiver, ReceiverPtr);
655
656 llvm::Value *self;
657
658 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
659 self = CGF.LoadObjCSelf();
660 } else {
661 self = llvm::ConstantPointerNull::get(IdTy);
662 }
663
664 // The lookup function is guaranteed not to capture the receiver pointer.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000665 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000666
David Chisnall0cc83e72011-10-28 17:55:06 +0000667 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000668 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000669 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000670 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000671 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000672 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000673 slot->setMetadata(msgSendMDKind, node);
674
675 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000676 llvm::Value *imp = Builder.CreateAlignedLoad(
677 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
678 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000679
680 // The lookup function may have changed the receiver, so make sure we use
681 // the new one.
682 Receiver = Builder.CreateLoad(ReceiverPtr, true);
683 return imp;
684 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000685
John McCall7f416cc2015-09-08 08:05:57 +0000686 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000687 llvm::Value *cmd,
688 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000689 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000690 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000691
John McCall882987f2013-02-28 19:01:20 +0000692 llvm::CallInst *slot =
693 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000694 slot->setOnlyReadsMemory();
695
John McCall7f416cc2015-09-08 08:05:57 +0000696 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
697 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000698 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000699
David Chisnalld7972f52011-03-23 16:36:54 +0000700 public:
Bjorn Pettersson84466332018-05-22 08:16:45 +0000701 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000702 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000703
Serge Guelton1d993272017-05-09 19:31:30 +0000704 llvm::StructType *SlotStructTy =
705 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000706 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
707 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
708 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000709 SelectorTy, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +0000710 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000711 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000712 PtrToObjCSuperTy, SelectorTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000713 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000714 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000715 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000716 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000717 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000718 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000719 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000720 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000721 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000722 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000723 } else if (R.getVersion() >= VersionTuple(1, 7)) {
724 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
725 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000726 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000727 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000728 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000729 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000730 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000731 }
David Chisnall0d75e062012-12-17 18:54:24 +0000732 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
733 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000734 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000735 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000736 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000737 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000738 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000739 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000740 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000741 // void objc_setCppObjectAtomic(void *dest, const void *src, void
742 // *helper);
743 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000744 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000745 // void objc_getCppObjectAtomic(void *dest, const void *src, void
746 // *helper);
747 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000748 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000749 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000750
Craig Topper4f12f102014-03-12 06:41:41 +0000751 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000752 // The optimised functions were added in version 1.7 of the GNUstep
753 // runtime.
754 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
755 VersionTuple(1, 7));
756 return CxxAtomicObjectGetFn;
757 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000758
Craig Topper4f12f102014-03-12 06:41:41 +0000759 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000760 // The optimised functions were added in version 1.7 of the GNUstep
761 // runtime.
762 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
763 VersionTuple(1, 7));
764 return CxxAtomicObjectSetFn;
765 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000766
Craig Topper4f12f102014-03-12 06:41:41 +0000767 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
768 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000769 // The optimised property functions omit the GC check, and so are not
770 // safe to use in GC mode. The standard functions are fast in GC mode,
771 // so there is less advantage in using them.
772 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
773 // The optimised functions were added in version 1.7 of the GNUstep
774 // runtime.
775 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
776 VersionTuple(1, 7));
777
778 if (atomic) {
779 if (copy) return SetPropertyAtomicCopy;
780 return SetPropertyAtomic;
781 }
David Chisnall0d75e062012-12-17 18:54:24 +0000782
Ted Kremenek090a2732014-03-07 18:53:05 +0000783 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000784 }
David Chisnalld7972f52011-03-23 16:36:54 +0000785};
786
Alp Toker272e9bc2013-11-25 00:40:53 +0000787/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000788class CGObjCObjFW: public CGObjCGNU {
789protected:
790 /// The GCC ABI message lookup function. Returns an IMP pointing to the
791 /// method implementation for this message.
792 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000793 /// stret lookup function. While this does not seem to make sense at the
794 /// first look, this is required to call the correct forwarding function.
795 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000796 /// The GCC ABI superclass message lookup function. Takes a pointer to a
797 /// structure describing the receiver and the class, and a selector as
798 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000799 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000800
Craig Topper4f12f102014-03-12 06:41:41 +0000801 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
802 llvm::Value *cmd, llvm::MDNode *node,
803 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000804 CGBuilderTy &Builder = CGF.Builder;
805 llvm::Value *args[] = {
806 EnforceType(Builder, Receiver, IdTy),
807 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000808
809 llvm::CallSite imp;
810 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
811 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
812 else
813 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
814
John McCall3deb1ad2012-08-21 02:47:43 +0000815 imp->setMetadata(msgSendMDKind, node);
816 return imp.getInstruction();
817 }
818
John McCall7f416cc2015-09-08 08:05:57 +0000819 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000820 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000821 CGBuilderTy &Builder = CGF.Builder;
822 llvm::Value *lookupArgs[] = {
823 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
824 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000825
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000826 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
827 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
828 else
829 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
830 }
John McCall3deb1ad2012-08-21 02:47:43 +0000831
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000832 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
833 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000834 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000835 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000836
837 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +0000838 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +0000839 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000840 if (!ClassSymbol)
841 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
842 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000843 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000844 return ClassSymbol;
845 }
846
847public:
John McCall3deb1ad2012-08-21 02:47:43 +0000848 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
849 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000850 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000851 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000852 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +0000853 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
854 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000855 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000856 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000857 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +0000858 }
John McCall775086e2012-07-12 02:07:58 +0000859};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000860} // end anonymous namespace
861
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000862/// Emits a reference to a dummy variable which is emitted with each class.
863/// This ensures that a linker error will be generated when trying to link
864/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000865void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000866 std::string symbolRef = "__objc_class_ref_" + className;
867 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000868 if (TheModule.getGlobalVariable(symbolRef))
869 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000870 std::string symbolName = "__objc_class_name_" + className;
871 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
872 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000873 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +0000874 llvm::GlobalValue::ExternalLinkage,
875 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000876 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000877 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000878 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000879}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000880
Bjorn Pettersson84466332018-05-22 08:16:45 +0000881static std::string SymbolNameForMethod( StringRef ClassName,
882 StringRef CategoryName, const Selector MethodName,
883 bool isClassMethod) {
884 std::string MethodNameColonStripped = MethodName.getAsString();
885 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
886 ':', '_');
887 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
888 CategoryName + "_" + MethodNameColonStripped).str();
889}
890
David Chisnalld7972f52011-03-23 16:36:54 +0000891CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Bjorn Pettersson84466332018-05-22 08:16:45 +0000892 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000893 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +0000894 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
895 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
Bjorn Pettersson84466332018-05-22 08:16:45 +0000896 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000897
898 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
899
David Chisnalld7972f52011-03-23 16:36:54 +0000900 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000901 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000902 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000903 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000904 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000905 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000906 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000907 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000908 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000909 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000910
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000911 Int8Ty = llvm::Type::getInt8Ty(VMContext);
912 // C string type. Used in lots of places.
913 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
914
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000915 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000916 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000917 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000918 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000919 QualType selTy = CGM.getContext().getObjCSelType();
920 if (QualType() == selTy) {
921 SelectorTy = PtrToInt8Ty;
922 } else {
923 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
924 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000925
Owen Anderson9793f0e2009-07-29 22:16:19 +0000926 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000927 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000928
David Chisnallcdd207e2011-10-04 15:35:30 +0000929 Int32Ty = llvm::Type::getInt32Ty(VMContext);
930 Int64Ty = llvm::Type::getInt64Ty(VMContext);
931
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000932 IntPtrTy =
933 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000934
Chris Lattner4bd55962008-03-30 23:03:07 +0000935 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000936 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
937 ASTIdTy = CanQualType();
938 if (UnqualIdTy != QualType()) {
939 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000940 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000941 } else {
942 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000943 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000944 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Serge Guelton1d993272017-05-09 19:31:30 +0000946 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +0000947 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
948
Chris Lattnera5f58b02011-07-09 17:41:47 +0000949 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000950
951 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +0000952 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
953 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000954 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +0000955 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000956 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +0000957 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000958
959 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +0000960 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000961
962 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
963 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000964 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000965 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
966 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000967 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000968 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +0000969 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
970 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000971 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +0000972 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
973 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000974
Chris Lattner4bd55962008-03-30 23:03:07 +0000975 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000976 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000977 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
978 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000979
David Blaikiebbafb8a2012-03-11 07:00:24 +0000980 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +0000981 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000982 RuntimeVersion = 10;
983
David Chisnalld3858d62011-03-25 11:57:33 +0000984 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000985 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000986 // This is a bit of an hack. We should sort this out by having a proper
987 // CGObjCGNUstep subclass for GC, but we may want to really support the old
988 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000989 // Get selectors needed in GC mode
990 RetainSel = GetNullarySelector("retain", CGM.getContext());
991 ReleaseSel = GetNullarySelector("release", CGM.getContext());
992 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
993
994 // Get functions needed in GC mode
995
996 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +0000997 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000998 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000999 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001000 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001001 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00001002 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001003 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00001004 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001005 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00001006 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001007 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001008 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001009 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001010 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001011}
Mike Stumpdd93a192009-07-31 21:31:32 +00001012
John McCall882987f2013-02-28 19:01:20 +00001013llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001014 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00001015 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001016 // With the incompatible ABI, this will need to be replaced with a direct
1017 // reference to the class symbol. For the compatible nonfragile ABI we are
1018 // still performing this lookup at run time but emitting the symbol for the
1019 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001020 //
1021 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1022 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001023 if (!isWeak)
1024 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001025
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001026 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001027 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001028 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001029 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001030}
1031
David Chisnall920e83b2011-06-29 13:16:41 +00001032// This has to perform the lookup every time, since posing and related
1033// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001034llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001035 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001036 auto *Value =
1037 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00001038 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
1039 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001040 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001041}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001042
John McCall882987f2013-02-28 19:01:20 +00001043llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001044 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1045 if (CGM.getTriple().isOSBinFormatCOFF()) {
1046 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1047 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1048 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1049 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1050
1051 const VarDecl *VD = nullptr;
1052 for (const auto &Result : DC->lookup(&II))
1053 if ((VD = dyn_cast<VarDecl>(Result)))
1054 break;
1055
Rafael Espindolab7350042018-03-01 00:35:47 +00001056 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001057 }
1058 }
1059 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001060}
1061
John McCall882987f2013-02-28 19:01:20 +00001062llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00001063 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00001064 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00001065 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00001066
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001067 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001068 e = Types.end() ; i!=e ; i++) {
1069 if (i->first == TypeEncoding) {
1070 SelValue = i->second;
1071 break;
1072 }
1073 }
Craig Topper8a13c412014-05-21 05:09:00 +00001074 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001075 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001076 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001077 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001078 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00001079 }
1080
David Chisnall76803412011-03-23 22:52:06 +00001081 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001082}
1083
John McCall7f416cc2015-09-08 08:05:57 +00001084Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1085 llvm::Value *SelValue = GetSelector(CGF, Sel);
1086
1087 // Store it to a temporary. Does this satisfy the semantics of
1088 // GetAddrOfSelector? Hopefully.
1089 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1090 CGF.getPointerAlign());
1091 CGF.Builder.CreateStore(SelValue, tmp);
1092 return tmp;
1093}
1094
1095llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1096 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001097}
1098
John McCall882987f2013-02-28 19:01:20 +00001099llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1100 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00001101 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
John McCall7f416cc2015-09-08 08:05:57 +00001102 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00001103}
1104
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001105llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001106 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1107 // With the old ABI, there was only one kind of catchall, which broke
1108 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1109 // a pointer indicating object catchalls, and NULL to indicate real
1110 // catchalls
1111 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1112 return MakeConstantString("@id");
1113 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001114 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00001115 }
David Chisnalld3858d62011-03-25 11:57:33 +00001116 }
John McCallc31d8932012-11-14 09:08:34 +00001117
1118 // All other types should be Objective-C interface pointer types.
1119 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1120 assert(OPT && "Invalid @catch type.");
1121 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1122 assert(IDecl && "Invalid @catch type.");
1123 return MakeConstantString(IDecl->getIdentifier()->getName());
1124}
1125
1126llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1127 if (!CGM.getLangOpts().CPlusPlus)
1128 return CGObjCGNU::GetEHType(T);
1129
David Chisnalle1d2584d2011-03-20 21:35:39 +00001130 // For Objective-C++, we want to provide the ability to catch both C++ and
1131 // Objective-C objects in the same function.
1132
1133 // There's a particular fixed type info for 'id'.
1134 if (T->isObjCIdType() ||
1135 T->isObjCQualifiedIdType()) {
1136 llvm::Constant *IDEHType =
1137 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1138 if (!IDEHType)
1139 IDEHType =
1140 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1141 false,
1142 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001143 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00001144 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1145 }
1146
1147 const ObjCObjectPointerType *PT =
1148 T->getAs<ObjCObjectPointerType>();
1149 assert(PT && "Invalid @catch type.");
1150 const ObjCInterfaceType *IT = PT->getInterfaceType();
1151 assert(IT && "Invalid @catch type.");
1152 std::string className = IT->getDecl()->getIdentifier()->getName();
1153
1154 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1155
1156 // Return the existing typeinfo if it exists
1157 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001158 if (typeinfo)
1159 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001160
1161 // Otherwise create it.
1162
1163 // vtable for gnustep::libobjc::__objc_class_type_info
1164 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1165 // platform's name mangling.
1166 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00001167 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001168 if (!Vtable) {
1169 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00001170 llvm::GlobalValue::ExternalLinkage,
1171 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001172 }
1173 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00001174 auto *BVtable = llvm::ConstantExpr::getBitCast(
1175 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1176 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001177
1178 llvm::Constant *typeName =
1179 ExportUniqueString(className, "__objc_eh_typename_");
1180
John McCall23c9dc62016-11-28 22:18:27 +00001181 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001182 auto fields = builder.beginStruct();
1183 fields.add(BVtable);
1184 fields.add(typeName);
1185 llvm::Constant *TI =
1186 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1187 CGM.getPointerAlign(),
1188 /*constant*/ false,
1189 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001190 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001191}
1192
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001193/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00001194ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001195
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001196 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00001197 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00001198
David Chisnall358e7512010-01-27 12:49:23 +00001199 // Look for an existing one
1200 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1201 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00001202 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00001203
David Blaikiebbafb8a2012-03-11 07:00:24 +00001204 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001205
Bjorn Pettersson84466332018-05-22 08:16:45 +00001206 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00001207
1208 std::string Sym = "_OBJC_CLASS_";
1209 Sym += StringClass;
1210
1211 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1212
1213 if (!isa)
1214 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00001215 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00001216 else if (isa->getType() != PtrToIdTy)
1217 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1218
John McCall23c9dc62016-11-28 22:18:27 +00001219 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001220 auto Fields = Builder.beginStruct();
1221 Fields.add(isa);
1222 Fields.add(MakeConstantString(Str));
1223 Fields.addInt(IntTy, Str.size());
1224 llvm::Constant *ObjCStr =
1225 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00001226 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1227 ObjCStrings[Str] = ObjCStr;
1228 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00001229 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001230}
1231
1232///Generates a message send where the super is the receiver. This is a message
1233///send to self with special delivery semantics indicating which class's method
1234///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001235RValue
1236CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001237 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001238 QualType ResultType,
1239 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001240 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001241 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001242 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001243 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001244 const CallArgList &CallArgs,
1245 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001246 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001247 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001248 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001249 return RValue::get(EnforceType(Builder, Receiver,
1250 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001251 }
1252 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001253 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001254 }
1255 }
David Chisnallea529a42010-05-01 12:37:16 +00001256
John McCall882987f2013-02-28 19:01:20 +00001257 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001258 CallArgList ActualArgs;
1259
Eli Friedman43dca6a2011-05-02 17:57:46 +00001260 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1261 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001262 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001263
John McCalla729c622012-02-17 03:33:10 +00001264 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001265
Craig Topper8a13c412014-05-21 05:09:00 +00001266 llvm::Value *ReceiverClass = nullptr;
Bjorn Pettersson84466332018-05-22 08:16:45 +00001267 if (isCategoryImpl) {
1268 llvm::Constant *classLookupFunction = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001269 if (IsClassMessage) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00001270 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1271 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001272 } else {
Bjorn Pettersson84466332018-05-22 08:16:45 +00001273 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1274 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001275 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00001276 ReceiverClass = Builder.CreateCall(classLookupFunction,
1277 MakeConstantString(Class->getNameAsString()));
1278 } else {
1279 // Set up global aliases for the metaclass or class pointer if they do not
1280 // already exist. These will are forward-references which will be set to
1281 // pointers to the class and metaclass structure created for the runtime
1282 // load function. To send a message to super, we look up the value of the
1283 // super_class pointer from either the class or metaclass structure.
1284 if (IsClassMessage) {
1285 if (!MetaClassPtrAlias) {
1286 MetaClassPtrAlias = llvm::GlobalAlias::create(
1287 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1288 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1289 }
1290 ReceiverClass = MetaClassPtrAlias;
1291 } else {
1292 if (!ClassPtrAlias) {
1293 ClassPtrAlias = llvm::GlobalAlias::create(
1294 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1295 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1296 }
1297 ReceiverClass = ClassPtrAlias;
1298 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001299 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00001300 // Cast the pointer to a simplified version of the class structure
1301 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
1302 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1303 llvm::PointerType::getUnqual(CastTy));
1304 // Get the superclass pointer
1305 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1306 // Load the superclass pointer
1307 ReceiverClass =
1308 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001309 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00001310 llvm::StructType *ObjCSuperTy =
1311 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00001312
Bjorn Pettersson84466332018-05-22 08:16:45 +00001313 // FIXME: Is this really supposed to be a dynamic alloca?
1314 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
John McCall7f416cc2015-09-08 08:05:57 +00001315 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001316
David Blaikie2e804282015-04-05 22:47:07 +00001317 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00001318 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00001319 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00001320 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001321
David Chisnall76803412011-03-23 22:52:06 +00001322 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001323
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001324 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001325 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001326 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001327
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001328 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00001329 llvm::MDString::get(VMContext, Sel.getAsString()),
1330 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001331 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1332 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00001333 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001334
John McCallb92ab1a2016-10-26 23:46:34 +00001335 CGCallee callee(CGCalleeInfo(), imp);
1336
David Chisnallff5f88c2010-05-02 13:41:58 +00001337 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001338 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001339 call->setMetadata(msgSendMDKind, node);
1340 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001341}
1342
Mike Stump11289f42009-09-09 15:08:12 +00001343/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001344RValue
1345CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001346 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001347 QualType ResultType,
1348 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001349 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001350 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001351 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001352 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001353 CGBuilderTy &Builder = CGF.Builder;
1354
David Chisnall75afda62010-04-27 15:08:48 +00001355 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001356 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001357 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001358 return RValue::get(EnforceType(Builder, Receiver,
1359 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001360 }
1361 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001362 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001363 }
1364 }
David Chisnall75afda62010-04-27 15:08:48 +00001365
David Chisnall75afda62010-04-27 15:08:48 +00001366 // If the return type is something that goes in an integer register, the
1367 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1368 // ourselves.
1369 //
1370 // The language spec says the result of this kind of message send is
1371 // undefined, but lots of people seem to have forgotten to read that
1372 // paragraph and insist on sending messages to nil that have structure
1373 // returns. With GCC, this generates a random return value (whatever happens
1374 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001375 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1376 // the stack.
1377 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1378 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001379
Craig Topper8a13c412014-05-21 05:09:00 +00001380 llvm::BasicBlock *startBB = nullptr;
1381 llvm::BasicBlock *messageBB = nullptr;
1382 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00001383
1384 if (!isPointerSizedReturn) {
1385 startBB = Builder.GetInsertBlock();
1386 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001387 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001388
1389 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1390 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001391 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001392 CGF.EmitBlock(messageBB);
1393 }
1394
David Chisnall9f57c292009-08-17 16:35:33 +00001395 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001396 llvm::Value *cmd;
1397 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001398 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001399 else
John McCall882987f2013-02-28 19:01:20 +00001400 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001401 cmd = EnforceType(Builder, cmd, SelectorTy);
1402 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001403
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001404 llvm::Metadata *impMD[] = {
1405 llvm::MDString::get(VMContext, Sel.getAsString()),
1406 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1407 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1408 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00001409 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001410
David Chisnall76803412011-03-23 22:52:06 +00001411 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001412 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1413 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001414 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001415
1416 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1417
David Chisnall8c93cf22011-10-24 14:07:03 +00001418 // Get the IMP to call
1419 llvm::Value *imp;
1420
1421 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1422 // functions. These are not supported on all platforms (or all runtimes on a
1423 // given platform), so we
1424 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001425 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001426 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001427 break;
1428 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001429 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001430 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1431 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1432 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001433 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001434 // The actual types here don't matter - we're going to bitcast the
1435 // function anyway
1436 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1437 "objc_msgSend_stret");
1438 } else {
1439 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1440 "objc_msgSend");
1441 }
1442 }
1443
David Chisnall6aec31a2011-12-01 18:40:09 +00001444 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00001445 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00001446
John McCalla729c622012-02-17 03:33:10 +00001447 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001448
David Chisnallff5f88c2010-05-02 13:41:58 +00001449 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001450 CGCallee callee(CGCalleeInfo(), imp);
1451 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001452 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001453
David Chisnall29cefd12010-05-20 13:45:48 +00001454
David Chisnall75afda62010-04-27 15:08:48 +00001455 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001456 messageBB = CGF.Builder.GetInsertBlock();
1457 CGF.Builder.CreateBr(continueBB);
1458 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001459 if (msgRet.isScalar()) {
1460 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001461 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001462 phi->addIncoming(v, messageBB);
1463 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1464 msgRet = RValue::get(phi);
1465 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00001466 Address v = msgRet.getAggregateAddress();
1467 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1468 llvm::Type *RetTy = v.getElementType();
1469 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1470 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1471 phi->addIncoming(v.getPointer(), messageBB);
1472 phi->addIncoming(NullVal.getPointer(), startBB);
1473 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00001474 } else /* isComplex() */ {
1475 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001476 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001477 phi->addIncoming(v.first, messageBB);
1478 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1479 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001480 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001481 phi2->addIncoming(v.second, messageBB);
1482 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1483 startBB);
1484 msgRet = RValue::getComplex(phi, phi2);
1485 }
1486 }
1487 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001488}
1489
Mike Stump11289f42009-09-09 15:08:12 +00001490/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001491/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001492llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00001493GenerateMethodList(StringRef ClassName,
1494 StringRef CategoryName,
Bjorn Pettersson84466332018-05-22 08:16:45 +00001495 ArrayRef<Selector> MethodSels,
1496 ArrayRef<llvm::Constant *> MethodTypes,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001497 bool isClassMethodList) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00001498 if (MethodSels.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00001499 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001500
John McCall23c9dc62016-11-28 22:18:27 +00001501 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001502
1503 auto MethodList = Builder.beginStruct();
1504 MethodList.addNullPointer(CGM.Int8PtrTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00001505 MethodList.addInt(Int32Ty, MethodTypes.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00001506
Mike Stump11289f42009-09-09 15:08:12 +00001507 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00001508 llvm::StructType *ObjCMethodTy =
1509 llvm::StructType::get(CGM.getLLVMContext(), {
1510 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1511 PtrToInt8Ty, // Method types
1512 IMPTy // Method pointer
1513 });
Bjorn Pettersson84466332018-05-22 08:16:45 +00001514 auto Methods = MethodList.beginArray();
1515 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
John McCallecee86f2016-11-30 20:19:46 +00001516 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001517 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Bjorn Pettersson84466332018-05-22 08:16:45 +00001518 MethodSels[i],
David Chisnalld7972f52011-03-23 16:36:54 +00001519 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00001520 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
Bjorn Pettersson84466332018-05-22 08:16:45 +00001521 auto Method = Methods.beginStruct(ObjCMethodTy);
1522 Method.add(MakeConstantString(MethodSels[i].getAsString()));
1523 Method.add(MethodTypes[i]);
1524 Method.addBitCast(FnPtr, IMPTy);
1525 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001526 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00001527 Methods.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00001528
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001529 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001530 return MethodList.finishAndCreateGlobal(".objc_method_list",
1531 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001532}
1533
1534/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001535llvm::Constant *CGObjCGNU::
1536GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1537 ArrayRef<llvm::Constant *> IvarTypes,
Bjorn Pettersson84466332018-05-22 08:16:45 +00001538 ArrayRef<llvm::Constant *> IvarOffsets) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001539 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00001540 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001541
John McCall23c9dc62016-11-28 22:18:27 +00001542 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001543
1544 // Structure containing array count followed by array.
1545 auto IvarList = Builder.beginStruct();
1546 IvarList.addInt(IntTy, (int)IvarNames.size());
1547
1548 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00001549 llvm::StructType *ObjCIvarTy =
1550 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001551
1552 // Array of ivar structures.
1553 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001554 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001555 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1556 Ivar.add(IvarNames[i]);
1557 Ivar.add(IvarTypes[i]);
1558 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00001559 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001560 }
John McCallf1788632016-11-28 22:18:30 +00001561 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001562
1563 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001564 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1565 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001566}
1567
1568/// Generate a class structure
1569llvm::Constant *CGObjCGNU::GenerateClassStructure(
1570 llvm::Constant *MetaClass,
1571 llvm::Constant *SuperClass,
1572 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001573 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001574 llvm::Constant *Version,
1575 llvm::Constant *InstanceSize,
1576 llvm::Constant *IVars,
1577 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001578 llvm::Constant *Protocols,
1579 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001580 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001581 llvm::Constant *StrongIvarBitmap,
1582 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001583 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001584 // Set up the class structure
1585 // Note: Several of these are char*s when they should be ids. This is
1586 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001587 //
1588 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1589 // anyway; the classes will still work with the GNU runtime, they will just
1590 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001591 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001592 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001593 PtrToInt8Ty, // super_class
1594 PtrToInt8Ty, // name
1595 LongTy, // version
1596 LongTy, // info
1597 LongTy, // instance_size
1598 IVars->getType(), // ivars
1599 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001600 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00001601 PtrTy, // dtable
1602 PtrTy, // subclass_list
1603 PtrTy, // sibling_class
1604 PtrTy, // protocols
1605 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001606 // New ABI:
1607 LongTy, // abi_version
1608 IvarOffsets->getType(), // ivar_offsets
1609 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001610 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00001611 IntPtrTy // weak_pointers
1612 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00001613
John McCall23c9dc62016-11-28 22:18:27 +00001614 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001615 auto Elements = Builder.beginStruct(ClassTy);
1616
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001617 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001618
1619 // isa
John McCallecee86f2016-11-30 20:19:46 +00001620 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001621 // super_class
1622 Elements.add(SuperClass);
1623 // name
1624 Elements.add(MakeConstantString(Name, ".class_name"));
1625 // version
1626 Elements.addInt(LongTy, 0);
1627 // info
1628 Elements.addInt(LongTy, info);
1629 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00001630 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001631 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001632 Elements.addInt(LongTy,
1633 td.getTypeSizeInBits(ClassTy) /
1634 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00001635 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00001636 Elements.add(InstanceSize);
1637 // ivars
1638 Elements.add(IVars);
1639 // methods
1640 Elements.add(Methods);
1641 // These are all filled in by the runtime, so we pretend
1642 // dtable
1643 Elements.add(NULLPtr);
1644 // subclass_list
1645 Elements.add(NULLPtr);
1646 // sibling_class
1647 Elements.add(NULLPtr);
1648 // protocols
John McCallecee86f2016-11-30 20:19:46 +00001649 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001650 // gc_object_type
1651 Elements.add(NULLPtr);
1652 // abi_version
Bjorn Pettersson84466332018-05-22 08:16:45 +00001653 Elements.addInt(LongTy, 1);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001654 // ivar_offsets
1655 Elements.add(IvarOffsets);
1656 // properties
1657 Elements.add(Properties);
1658 // strong_pointers
1659 Elements.add(StrongIvarBitmap);
1660 // weak_pointers
1661 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001662 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001663 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001664 // messages in the next ABI. We may already have some weak references to
1665 // this, so check and fix them properly.
1666 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1667 std::string(Name));
1668 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00001669 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001670 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1671 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00001672 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001673 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00001674 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00001675 ClassRef->removeFromParent();
1676 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00001677 }
1678 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001679}
1680
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001681llvm::Constant *CGObjCGNU::
Bjorn Pettersson84466332018-05-22 08:16:45 +00001682GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1683 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001684 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001685 llvm::StructType *ObjCMethodDescTy =
1686 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
John McCall23c9dc62016-11-28 22:18:27 +00001687 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001688 auto MethodList = Builder.beginStruct();
Bjorn Pettersson84466332018-05-22 08:16:45 +00001689 MethodList.addInt(IntTy, MethodNames.size());
1690 auto Methods = MethodList.beginArray(ObjCMethodDescTy);
1691 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1692 auto Method = Methods.beginStruct(ObjCMethodDescTy);
1693 Method.add(MethodNames[i]);
1694 Method.add(MethodTypes[i]);
1695 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001696 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00001697 Methods.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001698 return MethodList.finishAndCreateGlobal(".objc_method_list",
1699 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001700}
Mike Stumpdd93a192009-07-31 21:31:32 +00001701
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001702// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00001703llvm::Constant *
1704CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1705
John McCall23c9dc62016-11-28 22:18:27 +00001706 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001707 auto ProtocolList = Builder.beginStruct();
1708 ProtocolList.add(NULLPtr);
1709 ProtocolList.addInt(LongTy, Protocols.size());
1710
1711 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001712 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1713 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00001714 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00001715 llvm::StringMap<llvm::Constant*>::iterator value =
1716 ExistingProtocols.find(*iter);
1717 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001718 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001719 } else {
1720 protocol = value->getValue();
1721 }
John McCallecee86f2016-11-30 20:19:46 +00001722 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001723 }
John McCallf1788632016-11-28 22:18:30 +00001724 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001725 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1726 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001727}
1728
John McCall882987f2013-02-28 19:01:20 +00001729llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001730 const ObjCProtocolDecl *PD) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00001731 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001732 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001733 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001734 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001735}
1736
John McCall6c9f1fdb2016-11-19 08:17:24 +00001737llvm::Constant *
Bjorn Pettersson84466332018-05-22 08:16:45 +00001738CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001739 llvm::Constant *ProtocolList = GenerateProtocolList({});
Bjorn Pettersson84466332018-05-22 08:16:45 +00001740 llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001741 // Protocols are objects containing lists of the methods implemented and
1742 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00001743 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001744 auto Elements = Builder.beginStruct();
1745
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001746 // The isa pointer must be set to a magic number so the runtime knows it's
1747 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001748 Elements.add(llvm::ConstantExpr::getIntToPtr(
1749 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1750
1751 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00001752 Elements.add(ProtocolList); /* .protocol_list */
1753 Elements.add(MethodList); /* .instance_methods */
1754 Elements.add(MethodList); /* .class_methods */
1755 Elements.add(MethodList); /* .optional_instance_methods */
1756 Elements.add(MethodList); /* .optional_class_methods */
1757 Elements.add(NULLPtr); /* .properties */
1758 Elements.add(NULLPtr); /* .optional_properties */
Bjorn Pettersson84466332018-05-22 08:16:45 +00001759 return Elements.finishAndCreateGlobal(".objc_protocol",
John McCall6c9f1fdb2016-11-19 08:17:24 +00001760 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001761}
1762
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001763void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00001764 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001765 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001766
1767 // Use the protocol definition, if there is one.
1768 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1769 PD = Def;
1770
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001771 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001772 for (const auto *PI : PD->protocols())
1773 Protocols.push_back(PI->getNameAsString());
Bjorn Pettersson84466332018-05-22 08:16:45 +00001774 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1775 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1776 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1777 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1778 for (const auto *I : PD->instance_methods()) {
1779 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1780 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1781 OptionalInstanceMethodNames.push_back(
1782 MakeConstantString(I->getSelector().getAsString()));
1783 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1784 } else {
1785 InstanceMethodNames.push_back(
1786 MakeConstantString(I->getSelector().getAsString()));
1787 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1788 }
1789 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001790 // Collect information about class methods:
Bjorn Pettersson84466332018-05-22 08:16:45 +00001791 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1792 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1793 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1794 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1795 for (const auto *I : PD->class_methods()) {
1796 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1797 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1798 OptionalClassMethodNames.push_back(
1799 MakeConstantString(I->getSelector().getAsString()));
1800 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1801 } else {
1802 ClassMethodNames.push_back(
1803 MakeConstantString(I->getSelector().getAsString()));
1804 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1805 }
1806 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001807
1808 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1809 llvm::Constant *InstanceMethodList =
Bjorn Pettersson84466332018-05-22 08:16:45 +00001810 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001811 llvm::Constant *ClassMethodList =
Bjorn Pettersson84466332018-05-22 08:16:45 +00001812 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001813 llvm::Constant *OptionalInstanceMethodList =
Bjorn Pettersson84466332018-05-22 08:16:45 +00001814 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1815 OptionalInstanceMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001816 llvm::Constant *OptionalClassMethodList =
Bjorn Pettersson84466332018-05-22 08:16:45 +00001817 GenerateProtocolMethodList(OptionalClassMethodNames,
1818 OptionalClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001819
1820 // Property metadata: name, attributes, isSynthesized, setter name, setter
1821 // types, getter name, getter types.
1822 // The isSynthesized value is always set to 0 in a protocol. It exists to
1823 // simplify the runtime library by allowing it to use the same data
1824 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001825
Bjorn Pettersson84466332018-05-22 08:16:45 +00001826 llvm::Constant *PropertyList;
1827 llvm::Constant *OptionalPropertyList;
1828 {
1829 llvm::StructType *propertyMetadataTy =
1830 llvm::StructType::get(CGM.getLLVMContext(),
1831 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1832 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1833
1834 unsigned numReqProperties = 0, numOptProperties = 0;
1835 for (auto property : PD->instance_properties()) {
1836 if (property->isOptional())
1837 numOptProperties++;
1838 else
1839 numReqProperties++;
1840 }
1841
1842 ConstantInitBuilder reqPropertyListBuilder(CGM);
1843 auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1844 reqPropertiesList.addInt(IntTy, numReqProperties);
1845 reqPropertiesList.add(NULLPtr);
1846 auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1847
1848 ConstantInitBuilder optPropertyListBuilder(CGM);
1849 auto optPropertiesList = optPropertyListBuilder.beginStruct();
1850 optPropertiesList.addInt(IntTy, numOptProperties);
1851 optPropertiesList.add(NULLPtr);
1852 auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1853
1854 // Add all of the property methods need adding to the method list and to the
1855 // property metadata list.
1856 for (auto *property : PD->instance_properties()) {
1857 auto &propertiesArray =
1858 (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1859 auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1860
1861 fields.add(MakePropertyEncodingString(property, nullptr));
1862 PushPropertyAttributes(fields, property);
1863
1864 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1865 std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
1866 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1867 InstanceMethodTypes.push_back(typeEncoding);
1868 fields.add(MakeConstantString(getter->getSelector().getAsString()));
1869 fields.add(typeEncoding);
1870 } else {
1871 fields.add(NULLPtr);
1872 fields.add(NULLPtr);
1873 }
1874 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1875 std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
1876 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1877 InstanceMethodTypes.push_back(typeEncoding);
1878 fields.add(MakeConstantString(setter->getSelector().getAsString()));
1879 fields.add(typeEncoding);
1880 } else {
1881 fields.add(NULLPtr);
1882 fields.add(NULLPtr);
1883 }
1884
1885 fields.finishAndAddTo(propertiesArray);
1886 }
1887
1888 reqPropertiesArray.finishAndAddTo(reqPropertiesList);
1889 PropertyList =
1890 reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1891 CGM.getPointerAlign());
1892
1893 optPropertiesArray.finishAndAddTo(optPropertiesList);
1894 OptionalPropertyList =
1895 optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1896 CGM.getPointerAlign());
1897 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001898
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001899 // Protocols are objects containing lists of the methods implemented and
1900 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001901 // The isa pointer must be set to a magic number so the runtime knows it's
1902 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00001903 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001904 auto Elements = Builder.beginStruct();
1905 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00001906 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001907 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Bjorn Pettersson84466332018-05-22 08:16:45 +00001908 Elements.add(
1909 MakeConstantString(ProtocolName, ".objc_protocol_name"));
John McCall6c9f1fdb2016-11-19 08:17:24 +00001910 Elements.add(ProtocolList);
1911 Elements.add(InstanceMethodList);
1912 Elements.add(ClassMethodList);
1913 Elements.add(OptionalInstanceMethodList);
1914 Elements.add(OptionalClassMethodList);
1915 Elements.add(PropertyList);
1916 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001917 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001918 llvm::ConstantExpr::getBitCast(
1919 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1920 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001921}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001922void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001923 // Collect information about instance methods
Bjorn Pettersson84466332018-05-22 08:16:45 +00001924 SmallVector<Selector, 1> MethodSels;
1925 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001926
John McCall23c9dc62016-11-28 22:18:27 +00001927 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001928 auto Elements = Builder.beginStruct();
1929
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001930 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1931 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00001932 Elements.add(MakeConstantString(CategoryName));
1933 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001934 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00001935 Elements.addBitCast(GenerateMethodList(
Bjorn Pettersson84466332018-05-22 08:16:45 +00001936 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001937 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00001938 Elements.addBitCast(GenerateMethodList(
Bjorn Pettersson84466332018-05-22 08:16:45 +00001939 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001940
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001941 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00001942 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001943 auto ProtocolList = ProtocolListBuilder.beginStruct();
1944 ProtocolList.add(NULLPtr);
1945 ProtocolList.addInt(LongTy, ExistingProtocols.size());
1946 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1947 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001948 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00001949 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001950 }
John McCallf1788632016-11-28 22:18:30 +00001951 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00001952 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001953 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1954 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00001955 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001956 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001957 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00001958 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001959}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001960
David Chisnallcdd207e2011-10-04 15:35:30 +00001961/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1962/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1963/// bits set to their values, LSB first, while larger ones are stored in a
1964/// structure of this / form:
1965///
1966/// struct { int32_t length; int32_t values[length]; };
1967///
1968/// The values in the array are stored in host-endian format, with the least
1969/// significant bit being assumed to come first in the bitfield. Therefore, a
1970/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1971/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001972llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001973 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001974 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00001975 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001976 uint64_t val = 1;
1977 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00001978 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00001979 }
David Chisnalle89ac062011-10-25 10:12:21 +00001980 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00001981 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001982 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00001983 int v=0;
1984 while (v < bitCount) {
1985 int32_t word = 0;
1986 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1987 if (bits[v]) word |= 1<<i;
1988 v++;
1989 }
1990 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1991 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00001992
John McCall23c9dc62016-11-28 22:18:27 +00001993 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001994 auto fields = builder.beginStruct();
1995 fields.addInt(Int32Ty, values.size());
1996 auto array = fields.beginArray();
1997 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00001998 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001999
2000 llvm::Constant *GS =
2001 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002002 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002003 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002004}
2005
Daniel Dunbar92992502008-08-15 22:20:32 +00002006void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00002007 std::string ClassName = OCD->getClassInterface()->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00002008 std::string CategoryName = OCD->getNameAsString();
Bjorn Pettersson84466332018-05-22 08:16:45 +00002009 // Collect information about instance methods
2010 SmallVector<Selector, 16> InstanceMethodSels;
2011 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2012 for (const auto *I : OCD->instance_methods()) {
2013 InstanceMethodSels.push_back(I->getSelector());
2014 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2015 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2016 }
2017
2018 // Collect information about class methods
2019 SmallVector<Selector, 16> ClassMethodSels;
2020 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2021 for (const auto *I : OCD->class_methods()) {
2022 ClassMethodSels.push_back(I->getSelector());
2023 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2024 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2025 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002026
2027 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002028 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002029 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2030 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002031 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2032 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002033 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002034
John McCall23c9dc62016-11-28 22:18:27 +00002035 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002036 auto Elements = Builder.beginStruct();
2037 Elements.add(MakeConstantString(CategoryName));
2038 Elements.add(MakeConstantString(ClassName));
2039 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00002040 Elements.addBitCast(
Bjorn Pettersson84466332018-05-22 08:16:45 +00002041 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2042 InstanceMethodTypes, false),
John McCallecee86f2016-11-30 20:19:46 +00002043 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002044 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00002045 Elements.addBitCast(
Bjorn Pettersson84466332018-05-22 08:16:45 +00002046 GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2047 ClassMethodTypes, true),
John McCallecee86f2016-11-30 20:19:46 +00002048 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002049 // Protocol list
John McCallecee86f2016-11-30 20:19:46 +00002050 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
Owen Andersonade90fd2009-07-29 18:54:39 +00002051 Categories.push_back(llvm::ConstantExpr::getBitCast(
Bjorn Pettersson84466332018-05-22 08:16:45 +00002052 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00002053 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002054}
Daniel Dunbar92992502008-08-15 22:20:32 +00002055
Bjorn Pettersson84466332018-05-22 08:16:45 +00002056llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2057 SmallVectorImpl<Selector> &InstanceMethodSels,
2058 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
David Chisnall79356ee2018-05-22 06:09:23 +00002059 ASTContext &Context = CGM.getContext();
Bjorn Pettersson84466332018-05-22 08:16:45 +00002060 // Property metadata: name, attributes, attributes2, padding1, padding2,
2061 // setter name, setter types, getter name, getter types.
2062 llvm::StructType *propertyMetadataTy =
2063 llvm::StructType::get(CGM.getLLVMContext(),
2064 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2065 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
David Chisnall79356ee2018-05-22 06:09:23 +00002066
Bjorn Pettersson84466332018-05-22 08:16:45 +00002067 unsigned numProperties = 0;
2068 for (auto *propertyImpl : OID->property_impls()) {
2069 (void) propertyImpl;
2070 numProperties++;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002071 }
2072
John McCall23c9dc62016-11-28 22:18:27 +00002073 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002074 auto propertyList = builder.beginStruct();
Bjorn Pettersson84466332018-05-22 08:16:45 +00002075 propertyList.addInt(IntTy, numProperties);
2076 propertyList.add(NULLPtr);
2077 auto properties = propertyList.beginArray(propertyMetadataTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002078
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002079 // Add all of the property methods need adding to the method list and to the
2080 // property metadata list.
Bjorn Pettersson84466332018-05-22 08:16:45 +00002081 for (auto *propertyImpl : OID->property_impls()) {
2082 auto fields = properties.beginStruct(propertyMetadataTy);
2083 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2084 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2085 ObjCPropertyImplDecl::Synthesize);
2086 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2087 ObjCPropertyImplDecl::Dynamic);
2088
2089 fields.add(MakePropertyEncodingString(property, OID));
2090 PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
2091 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2092 std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
2093 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2094 if (isSynthesized) {
2095 InstanceMethodTypes.push_back(TypeEncoding);
2096 InstanceMethodSels.push_back(getter->getSelector());
David Chisnall36c63202010-02-26 01:11:38 +00002097 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002098 fields.add(MakeConstantString(getter->getSelector().getAsString()));
2099 fields.add(TypeEncoding);
2100 } else {
2101 fields.add(NULLPtr);
2102 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002103 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002104 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2105 std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
2106 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2107 if (isSynthesized) {
2108 InstanceMethodTypes.push_back(TypeEncoding);
2109 InstanceMethodSels.push_back(setter->getSelector());
2110 }
2111 fields.add(MakeConstantString(setter->getSelector().getAsString()));
2112 fields.add(TypeEncoding);
2113 } else {
2114 fields.add(NULLPtr);
2115 fields.add(NULLPtr);
2116 }
2117 fields.finishAndAddTo(properties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002118 }
John McCallf1788632016-11-28 22:18:30 +00002119 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002120
John McCall6c9f1fdb2016-11-19 08:17:24 +00002121 return propertyList.finishAndCreateGlobal(".objc_property_list",
2122 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002123}
2124
David Chisnall92d436b2012-01-31 18:59:20 +00002125void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2126 // Get the class declaration for which the alias is specified.
2127 ObjCInterfaceDecl *ClassDecl =
2128 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00002129 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2130 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00002131}
2132
Daniel Dunbar92992502008-08-15 22:20:32 +00002133void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2134 ASTContext &Context = CGM.getContext();
2135
2136 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002137 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002138 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002139 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002140 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002141 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002142 EmitClassRef(SuperClassName);
2143 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002144
2145 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002146 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002147 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002148 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002149
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002150 // Emit the symbol that is used to generate linker errors if this class is
2151 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002152 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002153 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002154 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002155 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002156 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002157 llvm::GlobalValue::ExternalLinkage,
2158 llvm::ConstantInt::get(LongTy, 0),
2159 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002160 }
Mike Stump11289f42009-09-09 15:08:12 +00002161
Daniel Dunbar12119b92009-05-03 10:46:44 +00002162 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002163 int instanceSize =
2164 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002165
2166 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002167 SmallVector<llvm::Constant*, 16> IvarNames;
2168 SmallVector<llvm::Constant*, 16> IvarTypes;
2169 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002170
John McCall23c9dc62016-11-28 22:18:27 +00002171 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002172 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00002173 SmallVector<bool, 16> WeakIvars;
2174 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002175
Mike Stump11289f42009-09-09 15:08:12 +00002176 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002177 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002178 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2179 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002180 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002181 instanceSize = 0 - (instanceSize - superInstanceSize);
2182 }
David Chisnall18cf7372010-04-19 00:45:34 +00002183
Jordy Rosea91768e2011-07-22 02:08:32 +00002184 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2185 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002186 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002187 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002188 // Get the type encoding for this ivar
2189 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00002190 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00002191 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002192 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002193 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002194 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002195 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002196 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002197 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002198 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2199 // Create the direct offset value
2200 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2201 IVD->getNameAsString();
2202 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2203 if (OffsetVar) {
2204 OffsetVar->setInitializer(OffsetValue);
2205 // If this is the real definition, change its linkage type so that
2206 // different modules will use this one, rather than their private
2207 // copy.
2208 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2209 } else
Bjorn Pettersson84466332018-05-22 08:16:45 +00002210 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002211 false, llvm::GlobalValue::ExternalLinkage,
Bjorn Pettersson84466332018-05-22 08:16:45 +00002212 OffsetValue,
2213 "__objc_ivar_offset_value_" + ClassName +"." +
2214 IVD->getNameAsString());
David Chisnall1bfe6d32011-07-07 12:34:51 +00002215 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002216 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002217 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2218 switch (lt) {
2219 case Qualifiers::OCL_Strong:
2220 StrongIvars.push_back(true);
2221 WeakIvars.push_back(false);
2222 break;
2223 case Qualifiers::OCL_Weak:
2224 StrongIvars.push_back(false);
2225 WeakIvars.push_back(true);
2226 break;
2227 default:
2228 StrongIvars.push_back(false);
2229 WeakIvars.push_back(false);
2230 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002231 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002232 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2233 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002234 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002235 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2236 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00002237
Daniel Dunbar92992502008-08-15 22:20:32 +00002238 // Collect information about instance methods
Bjorn Pettersson84466332018-05-22 08:16:45 +00002239 SmallVector<Selector, 16> InstanceMethodSels;
2240 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2241 for (const auto *I : OID->instance_methods()) {
2242 InstanceMethodSels.push_back(I->getSelector());
2243 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2244 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2245 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002246
Bjorn Pettersson84466332018-05-22 08:16:45 +00002247 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2248 InstanceMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002249
Bjorn Pettersson84466332018-05-22 08:16:45 +00002250 // Collect information about class methods
2251 SmallVector<Selector, 16> ClassMethodSels;
2252 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2253 for (const auto *I : OID->class_methods()) {
2254 ClassMethodSels.push_back(I->getSelector());
2255 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2256 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2257 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002258 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002259 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00002260 for (const auto *I : ClassDecl->protocols())
2261 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002262
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002263 // Get the superclass pointer.
2264 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002265 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002266 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2267 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002268 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002269 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002270 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002271 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002272 // Generate the method and instance variable lists
2273 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Bjorn Pettersson84466332018-05-22 08:16:45 +00002274 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002275 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Bjorn Pettersson84466332018-05-22 08:16:45 +00002276 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002277 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
Bjorn Pettersson84466332018-05-22 08:16:45 +00002278 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002279 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002280 // we emit a symbol containing the offset for each ivar in the class. This
2281 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2282 // for the legacy ABI, without causing problems. The converse is also
2283 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002284
David Chisnall5778fce2009-08-31 16:41:57 +00002285 // Offset pointer for getting at the correct field in the ivar list when
2286 // setting up the alias. These are: The base address for the global, the
2287 // ivar array (second field), the ivar in this list (set for each ivar), and
2288 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002289 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002290 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Bjorn Pettersson84466332018-05-22 08:16:45 +00002291 llvm::ConstantInt::get(IndexTy, 1), nullptr,
2292 llvm::ConstantInt::get(IndexTy, 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00002293
Jordy Rosea91768e2011-07-22 02:08:32 +00002294 unsigned ivarIndex = 0;
2295 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2296 IVD = IVD->getNextIvar()) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00002297 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2298 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002299 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002300 // Get the correct ivar field
2301 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00002302 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2303 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002304 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002305 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2306 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002307 offset->setInitializer(offsetValue);
2308 // If this is the real definition, change its linkage type so that
2309 // different modules will use this one, rather than their private
2310 // copy.
2311 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002312 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002313 // Add a new alias if there isn't one already.
Bjorn Pettersson84466332018-05-22 08:16:45 +00002314 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00002315 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002316 (void) offset; // Silence dead store warning.
2317 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002318 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002319 }
David Chisnalle89ac062011-10-25 10:12:21 +00002320 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002321
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002322 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002323 llvm::Constant *MetaClassStruct = GenerateClassStructure(
2324 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
Bjorn Pettersson84466332018-05-22 08:16:45 +00002325 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2326 NULLPtr, ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00002327 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
2328 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002329
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002330 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002331 llvm::Constant *ClassStruct = GenerateClassStructure(
2332 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2333 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2334 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2335 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00002336 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
2337 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002338
2339 // Resolve the class aliases, if they exist.
2340 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002341 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002342 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002343 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002344 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002345 }
2346 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002347 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002348 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002349 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002350 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002351 }
2352
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002353 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002354 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002355 Classes.push_back(ClassStruct);
2356}
2357
Mike Stump11289f42009-09-09 15:08:12 +00002358llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002359 // Only emit an ObjC load function if no Objective-C stuff has been called
2360 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002361 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00002362 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00002363
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002364 // Add all referenced protocols to a category.
2365 GenerateProtocolHolderCategory();
2366
John McCallecee86f2016-11-30 20:19:46 +00002367 llvm::StructType *selStructTy =
2368 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2369 llvm::Type *selStructPtrTy = SelectorTy;
2370 if (!selStructTy) {
2371 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2372 { PtrToInt8Ty, PtrToInt8Ty });
2373 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002374 }
2375
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002376 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00002377 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00002378 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00002379 llvm::GlobalVariable *fileStatics = [&] {
2380 ConstantInitBuilder builder(CGM);
2381 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00002382
John McCallecee86f2016-11-30 20:19:46 +00002383 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2384 if (stringClass.empty()) stringClass = "NXConstantString";
2385 staticsStruct.add(MakeConstantString(stringClass,
2386 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00002387
John McCallecee86f2016-11-30 20:19:46 +00002388 auto array = staticsStruct.beginArray();
2389 array.addAll(ConstantStrings);
2390 array.add(NULLPtr);
2391 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00002392
John McCallecee86f2016-11-30 20:19:46 +00002393 return staticsStruct.finishAndCreateGlobal(".objc_statics",
2394 CGM.getPointerAlign());
2395 }();
2396
2397 ConstantInitBuilder builder(CGM);
2398 auto allStaticsArray = builder.beginArray(fileStatics->getType());
2399 allStaticsArray.add(fileStatics);
2400 allStaticsArray.addNullPointer(fileStatics->getType());
2401
2402 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2403 CGM.getPointerAlign());
2404 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002405 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002406
John McCallecee86f2016-11-30 20:19:46 +00002407 // Array of classes, categories, and constant objects.
2408
2409 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2410 unsigned selectorCount;
2411
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002412 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00002413 llvm::GlobalVariable *selectorList = [&] {
2414 ConstantInitBuilder builder(CGM);
2415 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00002416 auto &table = SelectorTable; // MSVC workaround
2417 for (auto &entry : table) {
David Chisnalld7972f52011-03-23 16:36:54 +00002418
John McCallecee86f2016-11-30 20:19:46 +00002419 std::string selNameStr = entry.first.getAsString();
2420 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00002421
John McCallecee86f2016-11-30 20:19:46 +00002422 for (TypedSelector &sel : entry.second) {
2423 llvm::Constant *selectorTypeEncoding = NULLPtr;
2424 if (!sel.first.empty())
2425 selectorTypeEncoding =
2426 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00002427
John McCallecee86f2016-11-30 20:19:46 +00002428 auto selStruct = selectors.beginStruct(selStructTy);
2429 selStruct.add(selName);
2430 selStruct.add(selectorTypeEncoding);
2431 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00002432
John McCallecee86f2016-11-30 20:19:46 +00002433 // Store the selector alias for later replacement
2434 selectorAliases.push_back(sel.second);
2435 }
David Chisnalld7972f52011-03-23 16:36:54 +00002436 }
David Chisnalld7972f52011-03-23 16:36:54 +00002437
John McCallecee86f2016-11-30 20:19:46 +00002438 // Remember the number of entries in the selector table.
2439 selectorCount = selectors.size();
2440
2441 // NULL-terminate the selector list. This should not actually be required,
2442 // because the selector list has a length field. Unfortunately, the GCC
2443 // runtime decides to ignore the length field and expects a NULL terminator,
2444 // and GCC cooperates with this by always setting the length to 0.
2445 auto selStruct = selectors.beginStruct(selStructTy);
2446 selStruct.add(NULLPtr);
2447 selStruct.add(NULLPtr);
2448 selStruct.finishAndAddTo(selectors);
2449
2450 return selectors.finishAndCreateGlobal(".objc_selector_list",
2451 CGM.getPointerAlign());
2452 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002453
2454 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00002455 for (unsigned i = 0; i < selectorCount; ++i) {
2456 llvm::Constant *idxs[] = {
2457 Zeros[0],
2458 llvm::ConstantInt::get(Int32Ty, i)
2459 };
David Chisnalld7972f52011-03-23 16:36:54 +00002460 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00002461 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2462 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002463 // If selectors are defined as an opaque type, cast the pointer to this
2464 // type.
John McCallecee86f2016-11-30 20:19:46 +00002465 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2466 selectorAliases[i]->replaceAllUsesWith(selPtr);
2467 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002468 }
David Chisnalld7972f52011-03-23 16:36:54 +00002469
John McCallecee86f2016-11-30 20:19:46 +00002470 llvm::GlobalVariable *symtab = [&] {
2471 ConstantInitBuilder builder(CGM);
2472 auto symtab = builder.beginStruct();
2473
2474 // Number of static selectors
2475 symtab.addInt(LongTy, selectorCount);
2476
2477 symtab.addBitCast(selectorList, selStructPtrTy);
2478
2479 // Number of classes defined.
2480 symtab.addInt(CGM.Int16Ty, Classes.size());
2481 // Number of categories defined
2482 symtab.addInt(CGM.Int16Ty, Categories.size());
2483
2484 // Create an array of classes, then categories, then static object instances
2485 auto classList = symtab.beginArray(PtrToInt8Ty);
2486 classList.addAll(Classes);
2487 classList.addAll(Categories);
2488 // NULL-terminated list of static object instances (mainly constant strings)
2489 classList.add(statics);
2490 classList.add(NULLPtr);
2491 classList.finishAndAddTo(symtab);
2492
2493 // Construct the symbol table.
2494 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2495 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002496
2497 // The symbol table is contained in a module which has some version-checking
2498 // constants
John McCallecee86f2016-11-30 20:19:46 +00002499 llvm::Constant *module = [&] {
2500 llvm::Type *moduleEltTys[] = {
2501 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2502 };
2503 llvm::StructType *moduleTy =
2504 llvm::StructType::get(CGM.getLLVMContext(),
2505 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00002506
John McCallecee86f2016-11-30 20:19:46 +00002507 ConstantInitBuilder builder(CGM);
2508 auto module = builder.beginStruct(moduleTy);
2509 // Runtime version, used for ABI compatibility checking.
2510 module.addInt(LongTy, RuntimeVersion);
2511 // sizeof(ModuleTy)
2512 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2513
2514 // The path to the source file where this module was declared
2515 SourceManager &SM = CGM.getContext().getSourceManager();
2516 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2517 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00002518 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00002519 module.add(MakeConstantString(path, ".objc_source_file_name"));
2520 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00002521
John McCallecee86f2016-11-30 20:19:46 +00002522 if (RuntimeVersion >= 10) {
2523 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002524 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00002525 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00002526 break;
David Chisnalla918b882011-07-07 11:22:31 +00002527 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002528 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00002529 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00002530 else
John McCallecee86f2016-11-30 20:19:46 +00002531 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00002532 break;
2533 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00002534 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00002535 break;
John McCallecee86f2016-11-30 20:19:46 +00002536 }
David Chisnalla918b882011-07-07 11:22:31 +00002537 }
David Chisnall5c511772011-05-22 22:37:08 +00002538
John McCallecee86f2016-11-30 20:19:46 +00002539 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2540 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002541
2542 // Create the load function calling the runtime entry point with the module
2543 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002544 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002545 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002546 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2547 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002548 llvm::BasicBlock *EntryBB =
2549 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00002550 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002551 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002552
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002553 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00002554 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002555 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00002556 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00002557
David Chisnallaf066bbb2012-02-01 19:16:56 +00002558 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002559 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2560 llvm::FunctionType *RegisterAliasTy =
2561 llvm::FunctionType::get(Builder.getVoidTy(),
2562 ArgTypes, false);
2563 llvm::Function *RegisterAlias = llvm::Function::Create(
2564 RegisterAliasTy,
2565 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2566 &TheModule);
2567 llvm::BasicBlock *AliasBB =
2568 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2569 llvm::BasicBlock *NoAliasBB =
2570 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2571
2572 // Branch based on whether the runtime provided class_registerAlias_np()
2573 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2574 llvm::Constant::getNullValue(RegisterAlias->getType()));
2575 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2576
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002577 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002578 Builder.SetInsertPoint(AliasBB);
2579 // Emit alias registration calls:
2580 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2581 iter != ClassAliases.end(); ++iter) {
2582 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002583 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00002584 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00002585 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002586 Builder.CreateCall(RegisterAlias,
2587 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00002588 }
2589 }
2590 // Jump to end:
2591 Builder.CreateBr(NoAliasBB);
2592
2593 // Missing alias registration function, just return from the function:
2594 Builder.SetInsertPoint(NoAliasBB);
2595 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002596 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002597
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002598 return LoadFunction;
2599}
Daniel Dunbar92992502008-08-15 22:20:32 +00002600
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002601llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002602 const ObjCContainerDecl *CD) {
2603 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002604 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002605 StringRef CategoryName = OCD ? OCD->getName() : "";
2606 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002607 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002608 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002609
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002610 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002611 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002612 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002613 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2614 MethodName, isClassMethod);
2615
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002616 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002617 = llvm::Function::Create(MethodTy,
2618 llvm::GlobalValue::InternalLinkage,
2619 FunctionName,
2620 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002621 return Method;
2622}
2623
David Chisnall3fe89562011-05-23 22:33:28 +00002624llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002625 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002626}
2627
David Chisnall3fe89562011-05-23 22:33:28 +00002628llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002629 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002630}
2631
Ted Kremeneke65b0862012-03-06 20:05:56 +00002632llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2633 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00002634 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002635}
2636
David Chisnall3fe89562011-05-23 22:33:28 +00002637llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002638 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002639}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002640
David Chisnall3fe89562011-05-23 22:33:28 +00002641llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002642 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002643}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002644
David Chisnall0d75e062012-12-17 18:54:24 +00002645llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002646 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00002647}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002648
David Chisnall0d75e062012-12-17 18:54:24 +00002649llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002650 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002651}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002652
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002653llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002654 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002655}
2656
David Chisnalld7972f52011-03-23 16:36:54 +00002657void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002658 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002659 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002660}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002661
David Chisnall3a509cd2009-12-24 02:26:34 +00002662
David Chisnalld7972f52011-03-23 16:36:54 +00002663void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002664 const ObjCAtTryStmt &S) {
2665 // Unlike the Apple non-fragile runtimes, which also uses
2666 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2667 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002668 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002669 // the personality function; this avoids the need for bracketing
2670 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2671 // (or even _Unwind_DeleteException), but probably doesn't
2672 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002673 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002674 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002675 // exception handler.
2676 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002677}
2678
David Chisnalld7972f52011-03-23 16:36:54 +00002679void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002680 const ObjCAtThrowStmt &S,
2681 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002682 llvm::Value *ExceptionAsObject;
2683
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002684 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002685 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002686 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002687 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002688 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002689 "Unexpected rethrow outside @catch block.");
2690 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2691 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002692 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002693 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002694 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002695 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002696 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002697 if (ClearInsertionPoint)
2698 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002699}
2700
David Chisnalld7972f52011-03-23 16:36:54 +00002701llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002702 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002703 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002704 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002705 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2706 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002707}
2708
David Chisnalld7972f52011-03-23 16:36:54 +00002709void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002710 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002711 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002712 src = EnforceType(B, src, IdTy);
2713 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002714 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2715 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002716}
2717
David Chisnalld7972f52011-03-23 16:36:54 +00002718void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002719 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002720 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002721 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002722 src = EnforceType(B, src, IdTy);
2723 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002724 // FIXME. Add threadloca assign API
2725 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00002726 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2727 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002728}
2729
David Chisnalld7972f52011-03-23 16:36:54 +00002730void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002731 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002732 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002733 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002734 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002735 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002736 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2737 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002738}
2739
David Chisnalld7972f52011-03-23 16:36:54 +00002740void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002741 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002742 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002743 src = EnforceType(B, src, IdTy);
2744 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002745 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2746 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002747}
2748
David Chisnalld7972f52011-03-23 16:36:54 +00002749void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002750 Address DestPtr,
2751 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002752 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002753 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002754 DestPtr = EnforceType(B, DestPtr, PtrTy);
2755 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002756
John McCall7f416cc2015-09-08 08:05:57 +00002757 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2758 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002759}
2760
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002761llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2762 const ObjCInterfaceDecl *ID,
2763 const ObjCIvarDecl *Ivar) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00002764 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2765 + '.' + Ivar->getNameAsString();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002766 // Emit the variable and initialize it with what we think the correct value
2767 // is. This allows code compiled with non-fragile ivars to work correctly
2768 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002769 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2770 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002771 // This will cause a run-time crash if we accidentally use it. A value of
2772 // 0 would seem more sensible, but will silently overwrite the isa pointer
2773 // causing a great deal of confusion.
2774 uint64_t Offset = -1;
2775 // We can't call ComputeIvarBaseOffset() here if we have the
2776 // implementation, because it will create an invalid ASTRecordLayout object
2777 // that we are then stuck with forever, so we only initialize the ivar
2778 // offset variable with a guess if we only have the interface. The
2779 // initializer will be reset later anyway, when we are generating the class
2780 // description.
2781 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002782 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002783 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002784
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002785 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002786 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002787 // Don't emit the guess in non-PIC code because the linker will not be able
2788 // to replace it with the real version for a library. In non-PIC code you
2789 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002790 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002791 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002792 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002793 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002794 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2795 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2796 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2797 IvarOffsetGV, Name);
2798 } else {
2799 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002800 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002801 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002802 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002803 }
David Chisnall5778fce2009-08-31 16:41:57 +00002804 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002805}
2806
David Chisnalld7972f52011-03-23 16:36:54 +00002807LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002808 QualType ObjectTy,
2809 llvm::Value *BaseValue,
2810 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002811 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002812 const ObjCInterfaceDecl *ID =
2813 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002814 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2815 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002816}
Mike Stumpdd93a192009-07-31 21:31:32 +00002817
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002818static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2819 const ObjCInterfaceDecl *OID,
2820 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002821 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2822 next = next->getNextIvar()) {
2823 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002824 return OID;
2825 }
Mike Stump11289f42009-09-09 15:08:12 +00002826
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002827 // Otherwise check in the super class.
2828 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2829 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002830
Craig Topper8a13c412014-05-21 05:09:00 +00002831 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002832}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002833
David Chisnalld7972f52011-03-23 16:36:54 +00002834llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002835 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002836 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002837 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002838 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002839
2840 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2841 // and ExternalLinkage, so create a reference to the ivar global and rely on
2842 // the definition being created as part of GenerateClass.
2843 if (RuntimeVersion < 10 ||
2844 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00002845 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00002846 CGF.Builder.CreateAlignedLoad(
2847 Int32Ty, CGF.Builder.CreateAlignedLoad(
2848 ObjCIvarOffsetVariable(Interface, Ivar),
2849 CGF.getPointerAlign(), "ivar"),
2850 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00002851 PtrDiffTy);
2852 std::string name = "__objc_ivar_offset_value_" +
2853 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00002854 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00002855 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00002856 if (!Offset) {
2857 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002858 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2859 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00002860 GV->setAlignment(Align.getQuantity());
2861 Offset = GV;
2862 }
2863 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00002864 if (Offset->getType() != PtrDiffTy)
2865 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2866 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002867 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002868 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2869 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002870}
2871
David Chisnalld7972f52011-03-23 16:36:54 +00002872CGObjCRuntime *
2873clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
Bjorn Pettersson84466332018-05-22 08:16:45 +00002874 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002875 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002876 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002877
David Chisnallb601c962012-07-03 20:49:52 +00002878 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002879 return new CGObjCGCC(CGM);
2880
John McCall775086e2012-07-12 02:07:58 +00002881 case ObjCRuntime::ObjFW:
2882 return new CGObjCObjFW(CGM);
2883
John McCall5fb5df92012-06-20 06:18:46 +00002884 case ObjCRuntime::FragileMacOSX:
2885 case ObjCRuntime::MacOSX:
2886 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00002887 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00002888 llvm_unreachable("these runtimes are not GNU runtimes");
2889 }
2890 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002891}