blob: d2c089d0360e1affed8a038bcda4ec3542c8ed41 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerb7256cd2008-03-01 08:50:34 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner57540c52011-04-15 05:22:18 +00009// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// class in this file generates structures used by the GNU Objective-C runtime
11// library. These structures are defined in objc/objc.h and objc/objc-api.h in
12// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000017#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
David Chisnall93ce0182018-08-10 12:53:13 +000020#include "CGCXXABI.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 Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000036#include "llvm/Support/ConvertUTF.h"
David Chisnall404bbcb2018-05-22 10:13:06 +000037#include <cctype>
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 Chisnall404bbcb2018-05-22 10:13:06 +000043
44std::string SymbolNameForMethod( StringRef ClassName,
45 StringRef CategoryName, const Selector MethodName,
46 bool isClassMethod) {
47 std::string MethodNameColonStripped = MethodName.getAsString();
48 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
49 ':', '_');
50 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
51 CategoryName + "_" + MethodNameColonStripped).str();
52}
53
David Chisnall34d00052011-03-26 11:48:37 +000054/// Class that lazily initialises the runtime function. Avoids inserting the
55/// types and the function declaration into a module if they're not used, and
56/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000057class LazyRuntimeFunction {
58 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000059 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000060 const char *FunctionName;
James Y Knight9871db02019-02-05 16:42:33 +000061 llvm::FunctionCallee Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000062
63public:
64 /// Constructor leaves this class uninitialized, because it is intended to
65 /// be used as a field in another class and not all of the types that are
66 /// used as arguments will necessarily be available at construction time.
67 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000068 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000069
David Blaikie7d9e7922015-05-18 22:51:39 +000070 /// Initialises the lazy function with the name, return type, and the types
71 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000072 template <typename... Tys>
73 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
74 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000075 CGM = Mod;
76 FunctionName = name;
77 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000078 if(sizeof...(Tys)) {
79 SmallVector<llvm::Type *, 8> ArgTys({Types...});
80 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
81 }
82 else {
83 FTy = llvm::FunctionType::get(RetTy, None, false);
84 }
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
David Blaikiebf178d32015-05-19 21:31:34 +000086
87 llvm::FunctionType *getType() { return FTy; }
88
David Blaikie7d9e7922015-05-18 22:51:39 +000089 /// Overloaded cast operator, allows the class to be implicitly cast to an
90 /// LLVM constant.
James Y Knight9871db02019-02-05 16:42:33 +000091 operator llvm::FunctionCallee() {
David Blaikie7d9e7922015-05-18 22:51:39 +000092 if (!Function) {
93 if (!FunctionName)
94 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000095 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000096 }
97 return Function;
98 }
David Chisnalld7972f52011-03-23 16:36:54 +000099};
100
101
David Chisnall34d00052011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000103/// Objective-C support that are specific to the GNU family of runtimes (GCC,
104/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000106protected:
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000108 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// strut objc_super. Used for sending messages to super. This structure
110 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000111 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000112 /// struct objc_super*. The type of the argument to the superclass message
Fangrui Song6907ce22018-07-30 19:24:48 +0000113 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000114 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000115 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
116 /// SEL is included in a header somewhere, in which case it will be whatever
117 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000118 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000119 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
120 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000122 /// Pointer to i8 - LLVM type of char*, for all of the places where the
123 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000124 llvm::PointerType *PtrToInt8Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000125 /// struct objc_protocol type
126 llvm::StructType *ProtocolTy;
127 /// Protocol * type.
128 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000129 /// Instance Method Pointer type. This is a pointer to a function that takes,
130 /// at a minimum, an object and a selector, and is the generic type for
131 /// Objective-C methods. Due to differences between variadic / non-variadic
132 /// calling conventions, it must always be cast to the correct type before
133 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
136 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
137 /// but if the runtime header declaring it is included then it may be a
138 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
141 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000142 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// The clang type of id. Used when using the clang CGCall infrastructure to
144 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000145 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000146 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000147 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
149 /// used in the code to document the difference between i8* meaning a pointer
150 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000151 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000152 /// LLVM type for C long type. The runtime uses this in a lot of places where
153 /// it should be using intptr_t, but we can't fix this without breaking
154 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000155 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000157 llvm::IntegerType *SizeTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000158 /// LLVM type for C intptr_t.
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000159 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000161 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000162 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
163 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000164 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000165 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000166 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000167 /// 32-bit integer type, to save us needing to look it up every time it's used.
168 llvm::IntegerType *Int32Ty;
169 /// 64-bit integer type, to save us needing to look it up every time it's used.
170 llvm::IntegerType *Int64Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000171 /// The type of struct objc_property.
172 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Metadata kind used to tie method lookups to message sends. The GNUstep
174 /// runtime provides some LLVM passes that can use this to do things like
175 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000176 unsigned msgSendMDKind;
David Chisnall93ce0182018-08-10 12:53:13 +0000177 /// Does the current target use SEH-based exceptions? False implies
178 /// Itanium-style DWARF unwinding.
179 bool usesSEHExceptions;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000180
David Chisnall404bbcb2018-05-22 10:13:06 +0000181 /// Helper to check if we are targeting a specific runtime version or later.
182 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
183 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
184 return (R.getKind() == kind) &&
185 (R.getVersion() >= VersionTuple(major, minor));
186 }
187
David Chisnall7b36a862019-03-31 11:22:33 +0000188 std::string ManglePublicSymbol(StringRef Name) {
189 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
190 }
191
192 std::string SymbolForProtocol(Twine Name) {
193 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000194 }
195
196 std::string SymbolForProtocolRef(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000197 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000198 }
199
200
David Chisnall34d00052011-03-26 11:48:37 +0000201 /// Helper function that generates a constant string and returns a pointer to
202 /// the start of the string. The result of this function can be used anywhere
Fangrui Song6907ce22018-07-30 19:24:48 +0000203 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000204 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
205 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000206 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
207 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000208 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000209
David Chisnall34d00052011-03-26 11:48:37 +0000210 /// Emits a linkonce_odr string, whose name is the prefix followed by the
211 /// string value. This allows the linker to combine the strings between
212 /// different modules. Used for EH typeinfo names, selector strings, and a
213 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000214 llvm::Constant *ExportUniqueString(const std::string &Str,
215 const std::string &prefix,
216 bool Private=false) {
217 std::string name = prefix + Str;
218 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000219 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000220 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000221 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
222 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
David Chisnall93ce0182018-08-10 12:53:13 +0000223 GV->setComdat(TheModule.getOrInsertComdat(name));
David Chisnall404bbcb2018-05-22 10:13:06 +0000224 if (Private)
225 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
226 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000227 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000228 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
229 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000230 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
David Chisnalla5f59412012-10-16 15:11:55 +0000232 /// Returns a property name and encoding string.
233 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
234 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000235 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
236 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000237 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000238 std::string TypeStr =
239 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000240 NameAndAttributes += '\0';
241 NameAndAttributes += TypeStr.length() + 3;
242 NameAndAttributes += TypeStr;
243 NameAndAttributes += '\0';
244 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000245 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000246 }
247 return MakeConstantString(PD->getNameAsString());
248 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000249
Fangrui Song6907ce22018-07-30 19:24:48 +0000250 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000251 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000252 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000253 isDynamic=true) {
254 int attrs = property->getPropertyAttributes();
255 // For read-only properties, clear the copy and retain flags
256 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
257 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
259 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
261 }
262 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000263 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000264 attrs >>= 8;
265 attrs <<= 2;
266 // For protocol properties, synthesized and dynamic have no meaning, so we
267 // reuse these flags to indicate that this is a protocol property (both set
268 // has no meaning, as a property can't be both synthesized and dynamic)
269 attrs |= isSynthesized ? (1<<0) : 0;
270 attrs |= isDynamic ? (1<<1) : 0;
271 // The second field is the next four fields left shifted by two, with the
272 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000273 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000274 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000275 Fields.addInt(Int8Ty, 0);
276 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000277 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000278
David Chisnall386477a2018-12-28 17:44:54 +0000279 virtual llvm::Constant *GenerateCategoryProtocolList(const
280 ObjCCategoryDecl *OCD);
David Chisnall404bbcb2018-05-22 10:13:06 +0000281 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
282 int count) {
283 // int count;
284 Fields.addInt(IntTy, count);
285 // int size; (only in GNUstep v2 ABI.
286 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
287 llvm::DataLayout td(&TheModule);
288 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
289 CGM.getContext().getCharWidth());
290 }
291 // struct objc_property_list *next;
292 Fields.add(NULLPtr);
293 // struct objc_property properties[]
294 return Fields.beginArray(PropertyMetadataTy);
295 }
296 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
297 const ObjCPropertyDecl *property,
298 const Decl *OCD,
299 bool isSynthesized=true, bool
300 isDynamic=true) {
301 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
302 ASTContext &Context = CGM.getContext();
303 Fields.add(MakePropertyEncodingString(property, OCD));
304 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
305 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
306 if (accessor) {
307 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
308 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
309 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
310 Fields.add(TypeEncoding);
311 } else {
312 Fields.add(NULLPtr);
313 Fields.add(NULLPtr);
314 }
315 };
316 addPropertyMethod(property->getGetterMethodDecl());
317 addPropertyMethod(property->getSetterMethodDecl());
318 Fields.finishAndAddTo(PropertiesArray);
319 }
320
David Chisnall34d00052011-03-26 11:48:37 +0000321 /// Ensures that the value has the required type, by inserting a bitcast if
322 /// required. This function lets us avoid inserting bitcasts that are
323 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000324 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000325 if (V->getType() == Ty) return V;
326 return B.CreateBitCast(V, Ty);
327 }
John McCall7f416cc2015-09-08 08:05:57 +0000328 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
329 if (V.getType() == Ty) return V;
330 return B.CreateBitCast(V, Ty);
331 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000332
David Chisnall76803412011-03-23 22:52:06 +0000333 // Some zeros used for GEPs in lots of places.
334 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000335 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000336 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000337 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000338 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000339
David Chisnall404bbcb2018-05-22 10:13:06 +0000340protected:
341
David Chisnall34d00052011-03-26 11:48:37 +0000342 /// Placeholder for the class. Lots of things refer to the class before we've
343 /// actually emitted it. We use this alias as a placeholder, and then replace
344 /// it with a pointer to the class structure before finally emitting the
345 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000346 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Placeholder for the metaclass. Lots of things refer to the class before
348 /// we've / actually emitted it. We use this alias as a placeholder, and then
349 /// replace / it with a pointer to the metaclass structure before finally
350 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000351 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000352 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000353 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000354 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000355 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000356 /// All of the Objective-C constant strings that have been generated for this
357 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000358 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000359 /// Map from string values to Objective-C constant strings in the output.
360 /// Used to prevent emitting Objective-C strings more than once. This should
361 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000362 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000363 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000364 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000365 /// For each variant of a selector, we store the type encoding and a
366 /// placeholder value. For an untyped selector, the type will be the empty
367 /// string. Selector references are all done via the module's selector table,
368 /// so we create an alias as a placeholder and then replace it with the real
369 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000370 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000371 /// Type of the selector map. This is roughly equivalent to the structure
372 /// used in the GNUstep runtime, which maintains a list of all of the valid
373 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000374 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000375 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000376 /// A map from selectors to selector types. This allows us to emit all
377 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000378 SelectorMap SelectorTable;
379
David Chisnall34d00052011-03-26 11:48:37 +0000380 /// Selectors related to memory management. When compiling in GC mode, we
381 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000382 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000383 /// Runtime functions used for memory management in GC mode. Note that clang
384 /// supports code generation for calling these functions, but neither GNU
385 /// runtime actually supports this API properly yet.
Fangrui Song6907ce22018-07-30 19:24:48 +0000386 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
David Chisnalld7972f52011-03-23 16:36:54 +0000387 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000388
David Chisnall92d436b2012-01-31 18:59:20 +0000389 typedef std::pair<std::string, std::string> ClassAliasPair;
390 /// All classes that have aliases set for them.
391 std::vector<ClassAliasPair> ClassAliases;
392
David Chisnalld3858d62011-03-25 11:57:33 +0000393protected:
David Chisnall34d00052011-03-26 11:48:37 +0000394 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000395 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000396 /// Function used for rethrowing exceptions, used at the end of \@finally or
397 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000398 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000399 /// Function called when entering a catch function. This is required for
400 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000401 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000402 /// Function called when exiting from a catch block. Used to do exception
403 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000404 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000405 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000406 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000407 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000408 LazyRuntimeFunction SyncExitFn;
409
David Chisnalld3858d62011-03-25 11:57:33 +0000410private:
David Chisnall34d00052011-03-26 11:48:37 +0000411 /// Function called if fast enumeration detects that the collection is
412 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000413 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000414 /// Function for implementing synthesized property getters that return an
415 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000416 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000417 /// Function for implementing synthesized property setters that return an
418 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000419 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000420 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000421 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000422 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000423 LazyRuntimeFunction SetStructPropertyFn;
424
David Chisnall404bbcb2018-05-22 10:13:06 +0000425protected:
David Chisnall34d00052011-03-26 11:48:37 +0000426 /// The version of the runtime that this class targets. Must match the
427 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000428 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000429 /// The version of the protocol class. Used to differentiate between ObjC1
430 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
431 /// components and can not contain declared properties. We always emit
432 /// Objective-C 2 property structures, but we have to pretend that they're
433 /// Objective-C 1 property structures when targeting the GCC runtime or it
434 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000435 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000436 /// The version of the class ABI. This value is used in the class structure
437 /// and indicates how various fields should be interpreted.
438 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000439 /// Generates an instance variable list structure. This is a structure
440 /// containing a size and an array of structures containing instance variable
441 /// metadata. This is used purely for introspection in the fragile ABI. In
442 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000443 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
444 ArrayRef<llvm::Constant *> IvarTypes,
445 ArrayRef<llvm::Constant *> IvarOffsets,
446 ArrayRef<llvm::Constant *> IvarAlign,
447 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000448
David Chisnall34d00052011-03-26 11:48:37 +0000449 /// Generates a method list structure. This is a structure containing a size
450 /// and an array of structures containing method metadata.
451 ///
452 /// This structure is used by both classes and categories, and contains a next
453 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000454 llvm::Constant *GenerateMethodList(StringRef ClassName,
455 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000456 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000457 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000458
James Dennettb9199ee2012-06-13 22:07:09 +0000459 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000460 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
461 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000462 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000463
David Chisnall34d00052011-03-26 11:48:37 +0000464 /// Generates a list of property metadata structures. This follows the same
465 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000466 llvm::Constant *GeneratePropertyList(const Decl *Container,
467 const ObjCContainerDecl *OCD,
468 bool isClassProperty=false,
469 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000470
David Chisnall34d00052011-03-26 11:48:37 +0000471 /// Generates a list of referenced protocols. Classes, categories, and
472 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000473 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000474
David Chisnall34d00052011-03-26 11:48:37 +0000475 /// To ensure that all protocols are seen by the runtime, we add a category on
476 /// a class defined in the runtime, declaring no methods, but adopting the
477 /// protocols. This is a horribly ugly hack, but it allows us to collect all
478 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000479 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000480
David Chisnall34d00052011-03-26 11:48:37 +0000481 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000482 llvm::Constant *GenerateClassStructure(
483 llvm::Constant *MetaClass,
484 llvm::Constant *SuperClass,
485 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000486 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000487 llvm::Constant *Version,
488 llvm::Constant *InstanceSize,
489 llvm::Constant *IVars,
490 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000491 llvm::Constant *Protocols,
492 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000493 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000494 llvm::Constant *StrongIvarBitmap,
495 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000496 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000497
David Chisnall34d00052011-03-26 11:48:37 +0000498 /// Generates a method list. This is used by protocols to define the required
499 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000500 virtual llvm::Constant *GenerateProtocolMethodList(
501 ArrayRef<const ObjCMethodDecl*> Methods);
502 /// Emits optional and required method lists.
503 template<class T>
504 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
505 llvm::Constant *&Optional) {
506 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
507 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
508 for (const auto *I : Methods)
509 if (I->isOptional())
510 OptionalMethods.push_back(I);
511 else
512 RequiredMethods.push_back(I);
513 Required = GenerateProtocolMethodList(RequiredMethods);
514 Optional = GenerateProtocolMethodList(OptionalMethods);
515 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000516
David Chisnall34d00052011-03-26 11:48:37 +0000517 /// Returns a selector with the specified type encoding. An empty string is
518 /// used to return an untyped selector (with the types field set to NULL).
Simon Pilgrim04c5a342018-08-08 15:53:14 +0000519 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
520 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000521
David Chisnall404bbcb2018-05-22 10:13:06 +0000522 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
523 /// contains the class and ivar names, in the v2 ABI this contains the type
524 /// encoding as well.
525 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
526 const ObjCIvarDecl *Ivar) {
527 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
528 + '.' + Ivar->getNameAsString();
529 return Name;
530 }
David Chisnall34d00052011-03-26 11:48:37 +0000531 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000532 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
533 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000534 /// Emits a reference to a class. This allows the linker to object if there
535 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000536 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000537
David Chisnall920e83b2011-06-29 13:16:41 +0000538 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000539 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000540 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000541
David Chisnall34d00052011-03-26 11:48:37 +0000542 /// Looks up the method for sending a message to the specified object. This
543 /// mechanism differs between the GCC and GNU runtimes, so this method must be
544 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000545 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
546 llvm::Value *&Receiver,
547 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000548 llvm::MDNode *node,
549 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000550
David Chisnallcdd207e2011-10-04 15:35:30 +0000551 /// Looks up the method for sending a message to a superclass. This
552 /// mechanism differs between the GCC and GNU runtimes, so this method must
553 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000554 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000555 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000556 llvm::Value *cmd,
557 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000558
David Chisnallcdd207e2011-10-04 15:35:30 +0000559 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
560 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
561 /// bits set to their values, LSB first, while larger ones are stored in a
562 /// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +0000563 ///
David Chisnallcdd207e2011-10-04 15:35:30 +0000564 /// struct { int32_t length; int32_t values[length]; };
565 ///
566 /// The values in the array are stored in host-endian format, with the least
567 /// significant bit being assumed to come first in the bitfield. Therefore,
568 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
569 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000570 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000571
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000572public:
David Chisnalld7972f52011-03-23 16:36:54 +0000573 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000574 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000575
John McCall7f416cc2015-09-08 08:05:57 +0000576 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000577
Craig Topper4f12f102014-03-12 06:41:41 +0000578 RValue
579 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
580 QualType ResultType, Selector Sel,
581 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000582 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000583 const ObjCMethodDecl *Method) override;
584 RValue
585 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
586 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000587 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000588 bool isCategoryImpl, llvm::Value *Receiver,
589 bool IsClassMessage, const CallArgList &CallArgs,
590 const ObjCMethodDecl *Method) override;
591 llvm::Value *GetClass(CodeGenFunction &CGF,
592 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000593 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
594 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000595 llvm::Value *GetSelector(CodeGenFunction &CGF,
596 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000597 virtual llvm::Constant *GetConstantSelector(Selector Sel,
598 const std::string &TypeEncoding) {
599 llvm_unreachable("Runtime unable to generate constant selector");
600 }
601 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
602 return GetConstantSelector(M->getSelector(),
603 CGM.getContext().getObjCEncodingForMethodDecl(M));
604 }
Craig Topper4f12f102014-03-12 06:41:41 +0000605 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Craig Topper4f12f102014-03-12 06:41:41 +0000607 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
608 const ObjCContainerDecl *CD) override;
609 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
610 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
611 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
612 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
613 const ObjCProtocolDecl *PD) override;
614 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
615 llvm::Function *ModuleInitFunction() override;
James Y Knight9871db02019-02-05 16:42:33 +0000616 llvm::FunctionCallee GetPropertyGetFunction() override;
617 llvm::FunctionCallee GetPropertySetFunction() override;
618 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
619 bool copy) override;
620 llvm::FunctionCallee GetSetStructFunction() override;
621 llvm::FunctionCallee GetGetStructFunction() override;
622 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
623 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
624 llvm::FunctionCallee EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000625
Craig Topper4f12f102014-03-12 06:41:41 +0000626 void EmitTryStmt(CodeGenFunction &CGF,
627 const ObjCAtTryStmt &S) override;
628 void EmitSynchronizedStmt(CodeGenFunction &CGF,
629 const ObjCAtSynchronizedStmt &S) override;
630 void EmitThrowStmt(CodeGenFunction &CGF,
631 const ObjCAtThrowStmt &S,
632 bool ClearInsertionPoint=true) override;
633 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000634 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000635 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000636 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000637 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000638 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000639 bool threadlocal=false) override;
640 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000641 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000642 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000643 llvm::Value *src, Address dest) override;
644 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
645 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000646 llvm::Value *Size) override;
647 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
648 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
649 unsigned CVRQualifiers) override;
650 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
651 const ObjCInterfaceDecl *Interface,
652 const ObjCIvarDecl *Ivar) override;
653 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
654 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
655 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000656 return NULLPtr;
657 }
Craig Topper4f12f102014-03-12 06:41:41 +0000658 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
659 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000660 return NULLPtr;
661 }
Craig Topper4f12f102014-03-12 06:41:41 +0000662
663 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000664 return NULLPtr;
665 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000666};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000667
David Chisnall34d00052011-03-26 11:48:37 +0000668/// Class representing the legacy GCC Objective-C ABI. This is the default when
669/// -fobjc-nonfragile-abi is not specified.
670///
671/// The GCC ABI target actually generates code that is approximately compatible
672/// with the new GNUstep runtime ABI, but refrains from using any features that
673/// would not work with the GCC runtime. For example, clang always generates
674/// the extended form of the class structure, and the extra fields are simply
675/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000676class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000677 /// The GCC ABI message lookup function. Returns an IMP pointing to the
678 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000679 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000680 /// The GCC ABI superclass message lookup function. Takes a pointer to a
681 /// structure describing the receiver and the class, and a selector as
682 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000683 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000684
David Chisnall76803412011-03-23 22:52:06 +0000685protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000686 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
687 llvm::Value *cmd, llvm::MDNode *node,
688 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000689 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000690 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000691 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000692 EnforceType(Builder, cmd, SelectorTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000693 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000694 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +0000695 return imp;
David Chisnall76803412011-03-23 22:52:06 +0000696 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000697
John McCall7f416cc2015-09-08 08:05:57 +0000698 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000699 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000700 CGBuilderTy &Builder = CGF.Builder;
701 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
702 PtrToObjCSuperTy).getPointer(), cmd};
703 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
704 }
705
706public:
707 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
708 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000709 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000710 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
711 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000712 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000713 }
David Chisnalld7972f52011-03-23 16:36:54 +0000714};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000715
David Chisnall34d00052011-03-26 11:48:37 +0000716/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000717class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000718 /// The slot lookup function. Returns a pointer to a cacheable structure
719 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000720 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000721 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
722 /// a structure describing the receiver and the class, and a selector as
723 /// arguments. Returns the slot for the corresponding method. Superclass
724 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000725 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000726 /// Specialised function for setting atomic retain properties
727 LazyRuntimeFunction SetPropertyAtomic;
728 /// Specialised function for setting atomic copy properties
729 LazyRuntimeFunction SetPropertyAtomicCopy;
730 /// Specialised function for setting nonatomic retain properties
731 LazyRuntimeFunction SetPropertyNonAtomic;
732 /// Specialised function for setting nonatomic copy properties
733 LazyRuntimeFunction SetPropertyNonAtomicCopy;
734 /// Function to perform atomic copies of C++ objects with nontrivial copy
735 /// constructors from Objective-C ivars.
736 LazyRuntimeFunction CxxAtomicObjectGetFn;
737 /// Function to perform atomic copies of C++ objects with nontrivial copy
738 /// constructors to Objective-C ivars.
739 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000740 /// Type of an slot structure pointer. This is returned by the various
741 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000742 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000743
John McCallc31d8932012-11-14 09:08:34 +0000744 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000745 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000746
David Chisnall76803412011-03-23 22:52:06 +0000747 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000748 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
749 llvm::Value *cmd, llvm::MDNode *node,
750 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000751 CGBuilderTy &Builder = CGF.Builder;
James Y Knight9871db02019-02-05 16:42:33 +0000752 llvm::FunctionCallee LookupFn = SlotLookupFn;
David Chisnall76803412011-03-23 22:52:06 +0000753
754 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000755 Address ReceiverPtr =
756 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000757 Builder.CreateStore(Receiver, ReceiverPtr);
758
759 llvm::Value *self;
760
761 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
762 self = CGF.LoadObjCSelf();
763 } else {
764 self = llvm::ConstantPointerNull::get(IdTy);
765 }
766
767 // The lookup function is guaranteed not to capture the receiver pointer.
James Y Knight9871db02019-02-05 16:42:33 +0000768 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
769 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000770
David Chisnall0cc83e72011-10-28 17:55:06 +0000771 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000772 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000773 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000774 EnforceType(Builder, self, IdTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000775 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
776 slot->setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000777 slot->setMetadata(msgSendMDKind, node);
778
779 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000780 llvm::Value *imp = Builder.CreateAlignedLoad(
James Y Knight3933add2019-01-30 02:54:28 +0000781 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000782
783 // The lookup function may have changed the receiver, so make sure we use
784 // the new one.
785 Receiver = Builder.CreateLoad(ReceiverPtr, true);
786 return imp;
787 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000788
John McCall7f416cc2015-09-08 08:05:57 +0000789 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000790 llvm::Value *cmd,
791 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000792 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000793 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000794
John McCall882987f2013-02-28 19:01:20 +0000795 llvm::CallInst *slot =
796 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000797 slot->setOnlyReadsMemory();
798
John McCall7f416cc2015-09-08 08:05:57 +0000799 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
800 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000801 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000802
David Chisnalld7972f52011-03-23 16:36:54 +0000803 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000804 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
805 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
806 unsigned ClassABI) :
807 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000808 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000809
Serge Guelton1d993272017-05-09 19:31:30 +0000810 llvm::StructType *SlotStructTy =
811 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000812 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
813 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
814 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000815 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000816 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000817 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000818 PtrToObjCSuperTy, SelectorTy);
David Chisnall93ce0182018-08-10 12:53:13 +0000819 // If we're in ObjC++ mode, then we want to make
820 if (usesSEHExceptions) {
821 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
822 // void objc_exception_rethrow(void)
823 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
824 } else if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000825 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000826 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000827 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000828 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000829 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000830 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000831 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000832 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000833 } else if (R.getVersion() >= VersionTuple(1, 7)) {
834 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
835 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000836 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000837 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000838 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000839 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000840 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000841 }
David Chisnall0d75e062012-12-17 18:54:24 +0000842 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
843 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000844 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000845 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000846 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000847 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000848 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000849 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000850 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000851 // void objc_setCppObjectAtomic(void *dest, const void *src, void
852 // *helper);
853 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000854 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000855 // void objc_getCppObjectAtomic(void *dest, const void *src, void
856 // *helper);
857 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000858 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000859 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000860
James Y Knight9871db02019-02-05 16:42:33 +0000861 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000862 // The optimised functions were added in version 1.7 of the GNUstep
863 // runtime.
864 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
865 VersionTuple(1, 7));
866 return CxxAtomicObjectGetFn;
867 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000868
James Y Knight9871db02019-02-05 16:42:33 +0000869 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000870 // The optimised functions were added in version 1.7 of the GNUstep
871 // runtime.
872 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
873 VersionTuple(1, 7));
874 return CxxAtomicObjectSetFn;
875 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000876
James Y Knight9871db02019-02-05 16:42:33 +0000877 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
878 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000879 // The optimised property functions omit the GC check, and so are not
880 // safe to use in GC mode. The standard functions are fast in GC mode,
881 // so there is less advantage in using them.
882 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
883 // The optimised functions were added in version 1.7 of the GNUstep
884 // runtime.
885 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
886 VersionTuple(1, 7));
887
888 if (atomic) {
889 if (copy) return SetPropertyAtomicCopy;
890 return SetPropertyAtomic;
891 }
David Chisnall0d75e062012-12-17 18:54:24 +0000892
Ted Kremenek090a2732014-03-07 18:53:05 +0000893 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000894 }
David Chisnalld7972f52011-03-23 16:36:54 +0000895};
896
David Chisnall404bbcb2018-05-22 10:13:06 +0000897/// GNUstep Objective-C ABI version 2 implementation.
898/// This is the ABI that provides a clean break with the legacy GCC ABI and
899/// cleans up a number of things that were added to work around 1980s linkers.
900class CGObjCGNUstep2 : public CGObjCGNUstep {
David Chisnall93ce0182018-08-10 12:53:13 +0000901 enum SectionKind
902 {
903 SelectorSection = 0,
904 ClassSection,
905 ClassReferenceSection,
906 CategorySection,
907 ProtocolSection,
908 ProtocolReferenceSection,
909 ClassAliasSection,
910 ConstantStringSection
911 };
912 static const char *const SectionsBaseNames[8];
David Chisnall7b36a862019-03-31 11:22:33 +0000913 static const char *const PECOFFSectionsBaseNames[8];
David Chisnall93ce0182018-08-10 12:53:13 +0000914 template<SectionKind K>
915 std::string sectionName() {
David Chisnall7b36a862019-03-31 11:22:33 +0000916 if (CGM.getTriple().isOSBinFormatCOFF()) {
917 std::string name(PECOFFSectionsBaseNames[K]);
David Chisnall93ce0182018-08-10 12:53:13 +0000918 name += "$m";
David Chisnall7b36a862019-03-31 11:22:33 +0000919 return name;
920 }
921 return SectionsBaseNames[K];
David Chisnall93ce0182018-08-10 12:53:13 +0000922 }
David Chisnall404bbcb2018-05-22 10:13:06 +0000923 /// The GCC ABI superclass message lookup function. Takes a pointer to a
924 /// structure describing the receiver and the class, and a selector as
925 /// arguments. Returns the IMP for the corresponding method.
926 LazyRuntimeFunction MsgLookupSuperFn;
927 /// A flag indicating if we've emitted at least one protocol.
928 /// If we haven't, then we need to emit an empty protocol, to ensure that the
929 /// __start__objc_protocols and __stop__objc_protocols sections exist.
930 bool EmittedProtocol = false;
931 /// A flag indicating if we've emitted at least one protocol reference.
932 /// If we haven't, then we need to emit an empty protocol, to ensure that the
933 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
934 /// exist.
935 bool EmittedProtocolRef = false;
936 /// A flag indicating if we've emitted at least one class.
937 /// If we haven't, then we need to emit an empty protocol, to ensure that the
938 /// __start__objc_classes and __stop__objc_classes sections / exist.
939 bool EmittedClass = false;
940 /// Generate the name of a symbol for a reference to a class. Accesses to
941 /// classes should be indirected via this.
David Chisnall7b36a862019-03-31 11:22:33 +0000942
943 typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
944 std::vector<EarlyInitPair> EarlyInitList;
945
David Chisnall404bbcb2018-05-22 10:13:06 +0000946 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
947 if (isWeak)
David Chisnall7b36a862019-03-31 11:22:33 +0000948 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000949 else
David Chisnall7b36a862019-03-31 11:22:33 +0000950 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000951 }
952 /// Generate the name of a class symbol.
953 std::string SymbolForClass(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000954 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000955 }
956 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
957 ArrayRef<llvm::Value*> Args) {
958 SmallVector<llvm::Type *,8> Types;
959 for (auto *Arg : Args)
960 Types.push_back(Arg->getType());
961 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
962 false);
James Y Knight9871db02019-02-05 16:42:33 +0000963 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
David Chisnall404bbcb2018-05-22 10:13:06 +0000964 B.CreateCall(Fn, Args);
965 }
966
967 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
968
969 auto Str = SL->getString();
970 CharUnits Align = CGM.getPointerAlign();
971
972 // Look for an existing one
973 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
974 if (old != ObjCStrings.end())
975 return ConstantAddress(old->getValue(), Align);
976
977 bool isNonASCII = SL->containsNonAscii();
978
Fangrui Song6907ce22018-07-30 19:24:48 +0000979 auto LiteralLength = SL->getLength();
980
David Chisnall404bbcb2018-05-22 10:13:06 +0000981 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
982 (LiteralLength < 9) && !isNonASCII) {
983 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
984 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
985 // 3-bit tag (which is always 4).
986 uint64_t str = 0;
987 // Fill in the characters
988 for (unsigned i=0 ; i<LiteralLength ; i++)
989 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
990 // Fill in the length
991 str |= LiteralLength << 3;
992 // Set the tag
993 str |= 4;
994 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
995 llvm::ConstantInt::get(Int64Ty, str), IdTy);
996 ObjCStrings[Str] = ObjCStr;
997 return ConstantAddress(ObjCStr, Align);
998 }
999
1000 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1001
1002 if (StringClass.empty()) StringClass = "NSConstantString";
1003
1004 std::string Sym = SymbolForClass(StringClass);
1005
1006 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1007
David Chisnall7b36a862019-03-31 11:22:33 +00001008 if (!isa) {
David Chisnall404bbcb2018-05-22 10:13:06 +00001009 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1010 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
David Chisnall7b36a862019-03-31 11:22:33 +00001011 if (CGM.getTriple().isOSBinFormatCOFF()) {
1012 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1013 }
1014 } else if (isa->getType() != PtrToIdTy)
David Chisnall404bbcb2018-05-22 10:13:06 +00001015 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1016
1017 // struct
1018 // {
1019 // Class isa;
1020 // uint32_t flags;
1021 // uint32_t length; // Number of codepoints
1022 // uint32_t size; // Number of bytes
1023 // uint32_t hash;
1024 // const char *data;
1025 // };
1026
1027 ConstantInitBuilder Builder(CGM);
1028 auto Fields = Builder.beginStruct();
David Chisnall7b36a862019-03-31 11:22:33 +00001029 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1030 Fields.add(isa);
1031 } else {
1032 Fields.addNullPointer(PtrTy);
1033 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001034 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1035 // number of bytes is simply double the number of UTF-16 codepoints. In
1036 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1037 // codepoints.
1038 if (isNonASCII) {
1039 unsigned NumU8CodeUnits = Str.size();
1040 // A UTF-16 representation of a unicode string contains at most the same
1041 // number of code units as a UTF-8 representation. Allocate that much
1042 // space, plus one for the final null character.
1043 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1044 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1045 llvm::UTF16 *ToPtr = &ToBuf[0];
1046 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1047 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1048 uint32_t StringLength = ToPtr - &ToBuf[0];
1049 // Add null terminator
1050 *ToPtr = 0;
1051 // Flags: 2 indicates UTF-16 encoding
1052 Fields.addInt(Int32Ty, 2);
1053 // Number of UTF-16 codepoints
1054 Fields.addInt(Int32Ty, StringLength);
1055 // Number of bytes
1056 Fields.addInt(Int32Ty, StringLength * 2);
1057 // Hash. Not currently initialised by the compiler.
1058 Fields.addInt(Int32Ty, 0);
1059 // pointer to the data string.
1060 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1061 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1062 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1063 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1064 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1065 Fields.add(Buffer);
1066 } else {
1067 // Flags: 0 indicates ASCII encoding
1068 Fields.addInt(Int32Ty, 0);
1069 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1070 Fields.addInt(Int32Ty, Str.size());
1071 // Number of bytes
1072 Fields.addInt(Int32Ty, Str.size());
1073 // Hash. Not currently initialised by the compiler.
1074 Fields.addInt(Int32Ty, 0);
1075 // Data pointer
1076 Fields.add(MakeConstantString(Str));
1077 }
1078 std::string StringName;
1079 bool isNamed = !isNonASCII;
1080 if (isNamed) {
1081 StringName = ".objc_str_";
1082 for (int i=0,e=Str.size() ; i<e ; ++i) {
David Chisnall48a7afa2018-05-22 10:13:17 +00001083 unsigned char c = Str[i];
David Chisnall88e754f2018-05-22 10:13:11 +00001084 if (isalnum(c))
David Chisnall404bbcb2018-05-22 10:13:06 +00001085 StringName += c;
1086 else if (c == ' ')
1087 StringName += '_';
1088 else {
1089 isNamed = false;
1090 break;
1091 }
1092 }
1093 }
1094 auto *ObjCStrGV =
1095 Fields.finishAndCreateGlobal(
1096 isNamed ? StringRef(StringName) : ".objc_string",
1097 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1098 : llvm::GlobalValue::PrivateLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001099 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001100 if (isNamed) {
1101 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1102 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1103 }
David Chisnall7b36a862019-03-31 11:22:33 +00001104 if (CGM.getTriple().isOSBinFormatCOFF()) {
1105 std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1106 EarlyInitList.emplace_back(Sym, v);
1107 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001108 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1109 ObjCStrings[Str] = ObjCStr;
1110 ConstantStrings.push_back(ObjCStr);
1111 return ConstantAddress(ObjCStr, Align);
1112 }
1113
1114 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1115 const ObjCPropertyDecl *property,
1116 const Decl *OCD,
1117 bool isSynthesized=true, bool
1118 isDynamic=true) override {
1119 // struct objc_property
1120 // {
1121 // const char *name;
1122 // const char *attributes;
1123 // const char *type;
1124 // SEL getter;
1125 // SEL setter;
1126 // };
1127 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1128 ASTContext &Context = CGM.getContext();
1129 Fields.add(MakeConstantString(property->getNameAsString()));
1130 std::string TypeStr =
1131 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1132 Fields.add(MakeConstantString(TypeStr));
1133 std::string typeStr;
1134 Context.getObjCEncodingForType(property->getType(), typeStr);
1135 Fields.add(MakeConstantString(typeStr));
1136 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1137 if (accessor) {
1138 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1139 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1140 } else {
1141 Fields.add(NULLPtr);
1142 }
1143 };
1144 addPropertyMethod(property->getGetterMethodDecl());
1145 addPropertyMethod(property->getSetterMethodDecl());
1146 Fields.finishAndAddTo(PropertiesArray);
1147 }
1148
1149 llvm::Constant *
1150 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1151 // struct objc_protocol_method_description
1152 // {
1153 // SEL selector;
1154 // const char *types;
1155 // };
1156 llvm::StructType *ObjCMethodDescTy =
1157 llvm::StructType::get(CGM.getLLVMContext(),
1158 { PtrToInt8Ty, PtrToInt8Ty });
1159 ASTContext &Context = CGM.getContext();
1160 ConstantInitBuilder Builder(CGM);
1161 // struct objc_protocol_method_description_list
1162 // {
1163 // int count;
1164 // int size;
1165 // struct objc_protocol_method_description methods[];
1166 // };
1167 auto MethodList = Builder.beginStruct();
1168 // int count;
1169 MethodList.addInt(IntTy, Methods.size());
1170 // int size; // sizeof(struct objc_method_description)
1171 llvm::DataLayout td(&TheModule);
1172 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1173 CGM.getContext().getCharWidth());
1174 // struct objc_method_description[]
1175 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1176 for (auto *M : Methods) {
1177 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1178 Method.add(CGObjCGNU::GetConstantSelector(M));
1179 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1180 Method.finishAndAddTo(MethodArray);
1181 }
1182 MethodArray.finishAndAddTo(MethodList);
1183 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1184 CGM.getPointerAlign());
1185 }
David Chisnall386477a2018-12-28 17:44:54 +00001186 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1187 override {
1188 SmallVector<llvm::Constant*, 16> Protocols;
1189 for (const auto *PI : OCD->getReferencedProtocols())
1190 Protocols.push_back(
1191 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1192 ProtocolPtrTy));
1193 return GenerateProtocolList(Protocols);
1194 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001195
1196 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1197 llvm::Value *cmd, MessageSendInfo &MSI) override {
1198 // Don't access the slot unless we're trying to cache the result.
1199 CGBuilderTy &Builder = CGF.Builder;
1200 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1201 PtrToObjCSuperTy).getPointer(), cmd};
1202 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1203 }
1204
1205 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1206 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1207 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1208 if (ClassSymbol)
1209 return ClassSymbol;
1210 ClassSymbol = new llvm::GlobalVariable(TheModule,
1211 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1212 nullptr, SymbolName);
1213 // If this is a weak symbol, then we are creating a valid definition for
1214 // the symbol, pointing to a weak definition of the real class pointer. If
1215 // this is not a weak reference, then we are expecting another compilation
1216 // unit to provide the real indirection symbol.
1217 if (isWeak)
1218 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1219 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1220 nullptr, SymbolForClass(Name)));
David Chisnall7b36a862019-03-31 11:22:33 +00001221 else {
1222 if (CGM.getTriple().isOSBinFormatCOFF()) {
1223 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1224 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1225 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1226
1227 const ObjCInterfaceDecl *OID = nullptr;
1228 for (const auto &Result : DC->lookup(&II))
1229 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1230 break;
1231
1232 // The first Interface we find may be a @class,
1233 // which should only be treated as the source of
1234 // truth in the absence of a true declaration.
1235 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1236 if (OIDDef != nullptr)
1237 OID = OIDDef;
1238
1239 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1240 if (OID->hasAttr<DLLImportAttr>())
1241 Storage = llvm::GlobalValue::DLLImportStorageClass;
1242 else if (OID->hasAttr<DLLExportAttr>())
1243 Storage = llvm::GlobalValue::DLLExportStorageClass;
1244
1245 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1246 }
1247 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001248 assert(ClassSymbol->getName() == SymbolName);
1249 return ClassSymbol;
1250 }
1251 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1252 const std::string &Name,
1253 bool isWeak) override {
1254 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1255 CGM.getPointerAlign()));
1256 }
1257 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1258 // typedef enum {
1259 // ownership_invalid = 0,
1260 // ownership_strong = 1,
1261 // ownership_weak = 2,
1262 // ownership_unsafe = 3
1263 // } ivar_ownership;
1264 int Flag;
1265 switch (Ownership) {
1266 case Qualifiers::OCL_Strong:
1267 Flag = 1;
1268 break;
1269 case Qualifiers::OCL_Weak:
1270 Flag = 2;
1271 break;
1272 case Qualifiers::OCL_ExplicitNone:
1273 Flag = 3;
1274 break;
1275 case Qualifiers::OCL_None:
1276 case Qualifiers::OCL_Autoreleasing:
1277 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1278 Flag = 0;
1279 }
1280 return Flag;
1281 }
1282 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1283 ArrayRef<llvm::Constant *> IvarTypes,
1284 ArrayRef<llvm::Constant *> IvarOffsets,
1285 ArrayRef<llvm::Constant *> IvarAlign,
1286 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1287 llvm_unreachable("Method should not be called!");
1288 }
1289
1290 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1291 std::string Name = SymbolForProtocol(ProtocolName);
1292 auto *GV = TheModule.getGlobalVariable(Name);
1293 if (!GV) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001294 // Emit a placeholder symbol.
David Chisnall404bbcb2018-05-22 10:13:06 +00001295 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1296 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001297 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001298 }
1299 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1300 }
1301
1302 /// Existing protocol references.
1303 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1304
1305 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1306 const ObjCProtocolDecl *PD) override {
1307 auto Name = PD->getNameAsString();
1308 auto *&Ref = ExistingProtocolRefs[Name];
1309 if (!Ref) {
1310 auto *&Protocol = ExistingProtocols[Name];
1311 if (!Protocol)
1312 Protocol = GenerateProtocolRef(PD);
1313 std::string RefName = SymbolForProtocolRef(Name);
1314 assert(!TheModule.getGlobalVariable(RefName));
1315 // Emit a reference symbol.
1316 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
David Chisnall93ce0182018-08-10 12:53:13 +00001317 false, llvm::GlobalValue::LinkOnceODRLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001318 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
David Chisnall93ce0182018-08-10 12:53:13 +00001319 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1320 GV->setSection(sectionName<ProtocolReferenceSection>());
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001321 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001322 Ref = GV;
1323 }
1324 EmittedProtocolRef = true;
1325 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1326 }
1327
1328 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1329 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1330 Protocols.size());
1331 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1332 Protocols);
1333 ConstantInitBuilder builder(CGM);
1334 auto ProtocolBuilder = builder.beginStruct();
1335 ProtocolBuilder.addNullPointer(PtrTy);
1336 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1337 ProtocolBuilder.add(ProtocolArray);
1338 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1339 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1340 }
1341
1342 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1343 // Do nothing - we only emit referenced protocols.
1344 }
1345 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1346 std::string ProtocolName = PD->getNameAsString();
1347 auto *&Protocol = ExistingProtocols[ProtocolName];
1348 if (Protocol)
1349 return Protocol;
1350
1351 EmittedProtocol = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001352
David Chisnall93ce0182018-08-10 12:53:13 +00001353 auto SymName = SymbolForProtocol(ProtocolName);
1354 auto *OldGV = TheModule.getGlobalVariable(SymName);
1355
David Chisnall404bbcb2018-05-22 10:13:06 +00001356 // Use the protocol definition, if there is one.
1357 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1358 PD = Def;
David Chisnall93ce0182018-08-10 12:53:13 +00001359 else {
1360 // If there is no definition, then create an external linkage symbol and
1361 // hope that someone else fills it in for us (and fail to link if they
1362 // don't).
1363 assert(!OldGV);
1364 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1365 /*isConstant*/false,
1366 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1367 return Protocol;
1368 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001369
1370 SmallVector<llvm::Constant*, 16> Protocols;
1371 for (const auto *PI : PD->protocols())
1372 Protocols.push_back(
1373 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1374 ProtocolPtrTy));
1375 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1376
1377 // Collect information about methods
1378 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1379 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1380 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1381 OptionalInstanceMethodList);
1382 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1383 OptionalClassMethodList);
1384
David Chisnall404bbcb2018-05-22 10:13:06 +00001385 // The isa pointer must be set to a magic number so the runtime knows it's
1386 // the correct layout.
1387 ConstantInitBuilder builder(CGM);
1388 auto ProtocolBuilder = builder.beginStruct();
1389 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1390 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1391 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1392 ProtocolBuilder.add(ProtocolList);
1393 ProtocolBuilder.add(InstanceMethodList);
1394 ProtocolBuilder.add(ClassMethodList);
1395 ProtocolBuilder.add(OptionalInstanceMethodList);
1396 ProtocolBuilder.add(OptionalClassMethodList);
1397 // Required instance properties
1398 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1399 // Optional instance properties
1400 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1401 // Required class properties
1402 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1403 // Optional class properties
1404 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1405
1406 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1407 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001408 GV->setSection(sectionName<ProtocolSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001409 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1410 if (OldGV) {
1411 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1412 OldGV->getType()));
1413 OldGV->removeFromParent();
1414 GV->setName(SymName);
1415 }
1416 Protocol = GV;
1417 return GV;
1418 }
1419 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1420 if (Val->getType() == Ty)
1421 return Val;
1422 return llvm::ConstantExpr::getBitCast(Val, Ty);
1423 }
Simon Pilgrim04c5a342018-08-08 15:53:14 +00001424 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1425 const std::string &TypeEncoding) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001426 return GetConstantSelector(Sel, TypeEncoding);
1427 }
1428 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1429 if (TypeEncoding.empty())
1430 return NULLPtr;
1431 std::string MangledTypes = TypeEncoding;
1432 std::replace(MangledTypes.begin(), MangledTypes.end(),
1433 '@', '\1');
1434 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1435 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1436 if (!TypesGlobal) {
1437 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1438 TypeEncoding);
1439 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1440 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
David Chisnall93ce0182018-08-10 12:53:13 +00001441 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
David Chisnall404bbcb2018-05-22 10:13:06 +00001442 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1443 TypesGlobal = GV;
1444 }
1445 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1446 TypesGlobal, Zeros);
1447 }
1448 llvm::Constant *GetConstantSelector(Selector Sel,
1449 const std::string &TypeEncoding) override {
1450 // @ is used as a special character in symbol names (used for symbol
1451 // versioning), so mangle the name to not include it. Replace it with a
1452 // character that is not a valid type encoding character (and, being
1453 // non-printable, never will be!)
1454 std::string MangledTypes = TypeEncoding;
1455 std::replace(MangledTypes.begin(), MangledTypes.end(),
1456 '@', '\1');
1457 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1458 MangledTypes).str();
1459 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1460 return EnforceType(GV, SelectorTy);
1461 ConstantInitBuilder builder(CGM);
1462 auto SelBuilder = builder.beginStruct();
1463 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1464 true));
1465 SelBuilder.add(GetTypeString(TypeEncoding));
1466 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1467 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1468 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1469 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
David Chisnall93ce0182018-08-10 12:53:13 +00001470 GV->setSection(sectionName<SelectorSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001471 auto *SelVal = EnforceType(GV, SelectorTy);
1472 return SelVal;
1473 }
David Chisnall93ce0182018-08-10 12:53:13 +00001474 llvm::StructType *emptyStruct = nullptr;
1475
1476 /// Return pointers to the start and end of a section. On ELF platforms, we
1477 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1478 /// to the start and end of section names, as long as those section names are
1479 /// valid identifiers and the symbols are referenced but not defined. On
1480 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1481 /// by subsections and place everything that we want to reference in a middle
1482 /// subsection and then insert zero-sized symbols in subsections a and z.
David Chisnall404bbcb2018-05-22 10:13:06 +00001483 std::pair<llvm::Constant*,llvm::Constant*>
1484 GetSectionBounds(StringRef Section) {
David Chisnall93ce0182018-08-10 12:53:13 +00001485 if (CGM.getTriple().isOSBinFormatCOFF()) {
1486 if (emptyStruct == nullptr) {
1487 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1488 emptyStruct->setBody({}, /*isPacked*/true);
1489 }
1490 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1491 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1492 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1493 /*isConstant*/false,
1494 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1495 Section);
1496 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1497 Sym->setSection((Section + SecSuffix).str());
1498 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1499 Section).str()));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001500 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall93ce0182018-08-10 12:53:13 +00001501 return Sym;
1502 };
1503 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1504 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001505 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1506 /*isConstant*/false,
1507 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1508 Section);
1509 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1510 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1511 /*isConstant*/false,
1512 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1513 Section);
1514 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1515 return { Start, Stop };
1516 }
David Chisnall93ce0182018-08-10 12:53:13 +00001517 CatchTypeInfo getCatchAllTypeInfo() override {
1518 return CGM.getCXXABI().getCatchAllTypeInfo();
1519 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001520 llvm::Function *ModuleInitFunction() override {
1521 llvm::Function *LoadFunction = llvm::Function::Create(
1522 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1523 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1524 &TheModule);
1525 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1526 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1527
1528 llvm::BasicBlock *EntryBB =
1529 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1530 CGBuilderTy B(CGM, VMContext);
1531 B.SetInsertPoint(EntryBB);
1532 ConstantInitBuilder builder(CGM);
1533 auto InitStructBuilder = builder.beginStruct();
1534 InitStructBuilder.addInt(Int64Ty, 0);
David Chisnall7b36a862019-03-31 11:22:33 +00001535 auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1536 for (auto *s : sectionVec) {
David Chisnall93ce0182018-08-10 12:53:13 +00001537 auto bounds = GetSectionBounds(s);
David Chisnall404bbcb2018-05-22 10:13:06 +00001538 InitStructBuilder.add(bounds.first);
1539 InitStructBuilder.add(bounds.second);
David Chisnall7b36a862019-03-31 11:22:33 +00001540 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001541 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1542 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1543 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1544 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1545
1546 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1547 B.CreateRetVoid();
1548 // Make sure that the optimisers don't delete this function.
1549 CGM.addCompilerUsedGlobal(LoadFunction);
1550 // FIXME: Currently ELF only!
1551 // We have to do this by hand, rather than with @llvm.ctors, so that the
1552 // linker can remove the duplicate invocations.
1553 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1554 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1555 LoadFunction, ".objc_ctor");
1556 // Check that this hasn't been renamed. This shouldn't happen, because
1557 // this function should be called precisely once.
1558 assert(InitVar->getName() == ".objc_ctor");
David Chisnall93ce0182018-08-10 12:53:13 +00001559 // In Windows, initialisers are sorted by the suffix. XCL is for library
1560 // initialisers, which run before user initialisers. We are running
1561 // Objective-C loads at the end of library load. This means +load methods
1562 // will run before any other static constructors, but that static
1563 // constructors can see a fully initialised Objective-C state.
1564 if (CGM.getTriple().isOSBinFormatCOFF())
1565 InitVar->setSection(".CRT$XCLz");
1566 else
David Chisnall0e9e02c2019-03-31 11:22:19 +00001567 {
1568 if (CGM.getCodeGenOpts().UseInitArray)
1569 InitVar->setSection(".init_array");
1570 else
1571 InitVar->setSection(".ctors");
1572 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001573 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1574 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
David Chisnall93ce0182018-08-10 12:53:13 +00001575 CGM.addUsedGlobal(InitVar);
David Chisnall404bbcb2018-05-22 10:13:06 +00001576 for (auto *C : Categories) {
1577 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
David Chisnall93ce0182018-08-10 12:53:13 +00001578 Cat->setSection(sectionName<CategorySection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001579 CGM.addUsedGlobal(Cat);
1580 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001581 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1582 StringRef Section) {
1583 auto nullBuilder = builder.beginStruct();
1584 for (auto *F : Init)
1585 nullBuilder.add(F);
1586 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1587 false, llvm::GlobalValue::LinkOnceODRLinkage);
1588 GV->setSection(Section);
1589 GV->setComdat(TheModule.getOrInsertComdat(Name));
1590 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1591 CGM.addUsedGlobal(GV);
1592 return GV;
1593 };
David Chisnall93ce0182018-08-10 12:53:13 +00001594 for (auto clsAlias : ClassAliases)
1595 createNullGlobal(std::string(".objc_class_alias") +
1596 clsAlias.second, { MakeConstantString(clsAlias.second),
1597 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1598 // On ELF platforms, add a null value for each special section so that we
1599 // can always guarantee that the _start and _stop symbols will exist and be
1600 // meaningful. This is not required on COFF platforms, where our start and
1601 // stop symbols will create the section.
1602 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1603 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1604 sectionName<SelectorSection>());
1605 if (Categories.empty())
1606 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1607 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1608 sectionName<CategorySection>());
1609 if (!EmittedClass) {
1610 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
David Chisnallddd06822018-12-27 14:44:36 +00001611 sectionName<ClassSection>());
David Chisnall93ce0182018-08-10 12:53:13 +00001612 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1613 sectionName<ClassReferenceSection>());
1614 }
1615 if (!EmittedProtocol)
1616 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1617 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1618 NULLPtr}, sectionName<ProtocolSection>());
1619 if (!EmittedProtocolRef)
1620 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1621 sectionName<ProtocolReferenceSection>());
1622 if (ClassAliases.empty())
1623 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1624 sectionName<ClassAliasSection>());
1625 if (ConstantStrings.empty()) {
1626 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1627 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1628 i32Zero, i32Zero, i32Zero, NULLPtr },
1629 sectionName<ConstantStringSection>());
1630 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001631 }
1632 ConstantStrings.clear();
1633 Categories.clear();
1634 Classes.clear();
David Chisnall7b36a862019-03-31 11:22:33 +00001635
1636 if (EarlyInitList.size() > 0) {
1637 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1638 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1639 &CGM.getModule());
1640 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1641 Init));
1642 for (const auto &lateInit : EarlyInitList) {
1643 auto *global = TheModule.getGlobalVariable(lateInit.first);
1644 if (global) {
1645 b.CreateAlignedStore(global,
1646 b.CreateStructGEP(lateInit.second.first, lateInit.second.second), CGM.getPointerAlign().getQuantity());
1647 }
1648 }
1649 b.CreateRetVoid();
1650 // We can't use the normal LLVM global initialisation array, because we
1651 // need to specify that this runs early in library initialisation.
1652 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1653 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1654 Init, ".objc_early_init_ptr");
1655 InitVar->setSection(".CRT$XCLb");
1656 CGM.addUsedGlobal(InitVar);
1657 }
David Chisnall93ce0182018-08-10 12:53:13 +00001658 return nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001659 }
1660 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1661 /// to trigger linker failures if the types don't match.
1662 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1663 const ObjCIvarDecl *Ivar) override {
1664 std::string TypeEncoding;
1665 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1666 // Prevent the @ from being interpreted as a symbol version.
1667 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1668 '@', '\1');
1669 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1670 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1671 return Name;
1672 }
1673 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1674 const ObjCInterfaceDecl *Interface,
1675 const ObjCIvarDecl *Ivar) override {
1676 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1677 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1678 if (!IvarOffsetPointer)
1679 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1680 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1681 CharUnits Align = CGM.getIntAlign();
1682 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1683 if (Offset->getType() != PtrDiffTy)
1684 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1685 return Offset;
1686 }
1687 void GenerateClass(const ObjCImplementationDecl *OID) override {
1688 ASTContext &Context = CGM.getContext();
David Chisnall7b36a862019-03-31 11:22:33 +00001689 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
David Chisnall404bbcb2018-05-22 10:13:06 +00001690
1691 // Get the class name
1692 ObjCInterfaceDecl *classDecl =
1693 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1694 std::string className = classDecl->getNameAsString();
1695 auto *classNameConstant = MakeConstantString(className);
1696
1697 ConstantInitBuilder builder(CGM);
1698 auto metaclassFields = builder.beginStruct();
1699 // struct objc_class *isa;
1700 metaclassFields.addNullPointer(PtrTy);
1701 // struct objc_class *super_class;
1702 metaclassFields.addNullPointer(PtrTy);
1703 // const char *name;
1704 metaclassFields.add(classNameConstant);
1705 // long version;
1706 metaclassFields.addInt(LongTy, 0);
1707 // unsigned long info;
1708 // objc_class_flag_meta
1709 metaclassFields.addInt(LongTy, 1);
1710 // long instance_size;
1711 // Setting this to zero is consistent with the older ABI, but it might be
1712 // more sensible to set this to sizeof(struct objc_class)
1713 metaclassFields.addInt(LongTy, 0);
1714 // struct objc_ivar_list *ivars;
1715 metaclassFields.addNullPointer(PtrTy);
1716 // struct objc_method_list *methods
1717 // FIXME: Almost identical code is copied and pasted below for the
1718 // class, but refactoring it cleanly requires C++14 generic lambdas.
1719 if (OID->classmeth_begin() == OID->classmeth_end())
1720 metaclassFields.addNullPointer(PtrTy);
1721 else {
1722 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1723 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1724 OID->classmeth_end());
1725 metaclassFields.addBitCast(
1726 GenerateMethodList(className, "", ClassMethods, true),
1727 PtrTy);
1728 }
1729 // void *dtable;
1730 metaclassFields.addNullPointer(PtrTy);
1731 // IMP cxx_construct;
1732 metaclassFields.addNullPointer(PtrTy);
1733 // IMP cxx_destruct;
1734 metaclassFields.addNullPointer(PtrTy);
1735 // struct objc_class *subclass_list
1736 metaclassFields.addNullPointer(PtrTy);
1737 // struct objc_class *sibling_class
1738 metaclassFields.addNullPointer(PtrTy);
1739 // struct objc_protocol_list *protocols;
1740 metaclassFields.addNullPointer(PtrTy);
1741 // struct reference_list *extra_data;
1742 metaclassFields.addNullPointer(PtrTy);
1743 // long abi_version;
1744 metaclassFields.addInt(LongTy, 0);
1745 // struct objc_property_list *properties
1746 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1747
David Chisnall7b36a862019-03-31 11:22:33 +00001748 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1749 ManglePublicSymbol("OBJC_METACLASS_") + className,
1750 CGM.getPointerAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001751
1752 auto classFields = builder.beginStruct();
1753 // struct objc_class *isa;
1754 classFields.add(metaclass);
1755 // struct objc_class *super_class;
1756 // Get the superclass name.
1757 const ObjCInterfaceDecl * SuperClassDecl =
1758 OID->getClassInterface()->getSuperClass();
David Chisnall7b36a862019-03-31 11:22:33 +00001759 llvm::Constant *SuperClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001760 if (SuperClassDecl) {
1761 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
David Chisnall7b36a862019-03-31 11:22:33 +00001762 SuperClass = TheModule.getNamedGlobal(SuperClassName);
David Chisnall404bbcb2018-05-22 10:13:06 +00001763 if (!SuperClass)
1764 {
1765 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1766 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
David Chisnall7b36a862019-03-31 11:22:33 +00001767 if (IsCOFF) {
1768 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1769 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1770 Storage = llvm::GlobalValue::DLLImportStorageClass;
1771 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1772 Storage = llvm::GlobalValue::DLLExportStorageClass;
1773
1774 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1775 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001776 }
David Chisnall7b36a862019-03-31 11:22:33 +00001777 if (!IsCOFF)
1778 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1779 else
1780 classFields.addNullPointer(PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00001781 } else
1782 classFields.addNullPointer(PtrTy);
1783 // const char *name;
1784 classFields.add(classNameConstant);
1785 // long version;
1786 classFields.addInt(LongTy, 0);
1787 // unsigned long info;
1788 // !objc_class_flag_meta
1789 classFields.addInt(LongTy, 0);
1790 // long instance_size;
1791 int superInstanceSize = !SuperClassDecl ? 0 :
1792 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1793 // Instance size is negative for classes that have not yet had their ivar
1794 // layout calculated.
1795 classFields.addInt(LongTy,
1796 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1797 superInstanceSize));
1798
1799 if (classDecl->all_declared_ivar_begin() == nullptr)
1800 classFields.addNullPointer(PtrTy);
1801 else {
1802 int ivar_count = 0;
1803 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1804 IVD = IVD->getNextIvar()) ivar_count++;
1805 llvm::DataLayout td(&TheModule);
1806 // struct objc_ivar_list *ivars;
1807 ConstantInitBuilder b(CGM);
1808 auto ivarListBuilder = b.beginStruct();
1809 // int count;
1810 ivarListBuilder.addInt(IntTy, ivar_count);
1811 // size_t size;
1812 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1813 PtrToInt8Ty,
1814 PtrToInt8Ty,
1815 PtrToInt8Ty,
1816 Int32Ty,
1817 Int32Ty);
1818 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1819 CGM.getContext().getCharWidth());
1820 // struct objc_ivar ivars[]
1821 auto ivarArrayBuilder = ivarListBuilder.beginArray();
David Chisnall404bbcb2018-05-22 10:13:06 +00001822 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1823 IVD = IVD->getNextIvar()) {
1824 auto ivarTy = IVD->getType();
1825 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1826 // const char *name;
1827 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1828 // const char *type;
1829 std::string TypeStr;
1830 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1831 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1832 ivarBuilder.add(MakeConstantString(TypeStr));
1833 // int *offset;
1834 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1835 uint64_t Offset = BaseOffset - superInstanceSize;
1836 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1837 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1838 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1839 if (OffsetVar)
1840 OffsetVar->setInitializer(OffsetValue);
1841 else
1842 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1843 false, llvm::GlobalValue::ExternalLinkage,
1844 OffsetValue, OffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00001845 auto ivarVisibility =
David Chisnall404bbcb2018-05-22 10:13:06 +00001846 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1847 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1848 classDecl->getVisibility() == HiddenVisibility) ?
1849 llvm::GlobalValue::HiddenVisibility :
1850 llvm::GlobalValue::DefaultVisibility;
1851 OffsetVar->setVisibility(ivarVisibility);
1852 ivarBuilder.add(OffsetVar);
1853 // Ivar size
1854 ivarBuilder.addInt(Int32Ty,
David Chisnallccc42862019-02-03 15:05:52 +00001855 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001856 // Alignment will be stored as a base-2 log of the alignment.
Simon Pilgrimd06ee792019-10-02 11:49:32 +00001857 unsigned align =
1858 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001859 // Objects that require more than 2^64-byte alignment should be impossible!
1860 assert(align < 64);
1861 // uint32_t flags;
1862 // Bits 0-1 are ownership.
1863 // Bit 2 indicates an extended type encoding
1864 // Bits 3-8 contain log2(aligment)
Fangrui Song6907ce22018-07-30 19:24:48 +00001865 ivarBuilder.addInt(Int32Ty,
David Chisnall404bbcb2018-05-22 10:13:06 +00001866 (align << 3) | (1<<2) |
1867 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1868 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1869 }
1870 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1871 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
Fangrui Song6907ce22018-07-30 19:24:48 +00001872 CGM.getPointerAlign(), /*constant*/ false,
David Chisnall404bbcb2018-05-22 10:13:06 +00001873 llvm::GlobalValue::PrivateLinkage);
1874 classFields.add(ivarList);
1875 }
1876 // struct objc_method_list *methods
1877 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1878 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1879 OID->instmeth_end());
1880 for (auto *propImpl : OID->property_impls())
1881 if (propImpl->getPropertyImplementation() ==
1882 ObjCPropertyImplDecl::Synthesize) {
1883 ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1884 auto addIfExists = [&](const ObjCMethodDecl* OMD) {
1885 if (OMD)
1886 InstanceMethods.push_back(OMD);
1887 };
1888 addIfExists(prop->getGetterMethodDecl());
1889 addIfExists(prop->getSetterMethodDecl());
1890 }
1891
1892 if (InstanceMethods.size() == 0)
1893 classFields.addNullPointer(PtrTy);
1894 else
1895 classFields.addBitCast(
1896 GenerateMethodList(className, "", InstanceMethods, false),
1897 PtrTy);
1898 // void *dtable;
1899 classFields.addNullPointer(PtrTy);
1900 // IMP cxx_construct;
1901 classFields.addNullPointer(PtrTy);
1902 // IMP cxx_destruct;
1903 classFields.addNullPointer(PtrTy);
1904 // struct objc_class *subclass_list
1905 classFields.addNullPointer(PtrTy);
1906 // struct objc_class *sibling_class
1907 classFields.addNullPointer(PtrTy);
1908 // struct objc_protocol_list *protocols;
1909 SmallVector<llvm::Constant*, 16> Protocols;
1910 for (const auto *I : classDecl->protocols())
1911 Protocols.push_back(
1912 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1913 ProtocolPtrTy));
1914 if (Protocols.empty())
1915 classFields.addNullPointer(PtrTy);
1916 else
1917 classFields.add(GenerateProtocolList(Protocols));
1918 // struct reference_list *extra_data;
1919 classFields.addNullPointer(PtrTy);
1920 // long abi_version;
1921 classFields.addInt(LongTy, 0);
1922 // struct objc_property_list *properties
1923 classFields.add(GeneratePropertyList(OID, classDecl));
1924
1925 auto *classStruct =
1926 classFields.finishAndCreateGlobal(SymbolForClass(className),
1927 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1928
David Chisnall404bbcb2018-05-22 10:13:06 +00001929 auto *classRefSymbol = GetClassVar(className);
David Chisnall93ce0182018-08-10 12:53:13 +00001930 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001931 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1932
David Chisnall7b36a862019-03-31 11:22:33 +00001933 if (IsCOFF) {
1934 // we can't import a class struct.
1935 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1936 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1937 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1938 }
1939
1940 if (SuperClass) {
1941 std::pair<llvm::Constant*, int> v{classStruct, 1};
1942 EarlyInitList.emplace_back(SuperClass->getName(), std::move(v));
1943 }
1944
1945 }
1946
David Chisnall404bbcb2018-05-22 10:13:06 +00001947
1948 // Resolve the class aliases, if they exist.
1949 // FIXME: Class pointer aliases shouldn't exist!
1950 if (ClassPtrAlias) {
1951 ClassPtrAlias->replaceAllUsesWith(
1952 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1953 ClassPtrAlias->eraseFromParent();
1954 ClassPtrAlias = nullptr;
1955 }
1956 if (auto Placeholder =
1957 TheModule.getNamedGlobal(SymbolForClass(className)))
1958 if (Placeholder != classStruct) {
1959 Placeholder->replaceAllUsesWith(
1960 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1961 Placeholder->eraseFromParent();
1962 classStruct->setName(SymbolForClass(className));
1963 }
1964 if (MetaClassPtrAlias) {
1965 MetaClassPtrAlias->replaceAllUsesWith(
1966 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1967 MetaClassPtrAlias->eraseFromParent();
1968 MetaClassPtrAlias = nullptr;
1969 }
1970 assert(classStruct->getName() == SymbolForClass(className));
1971
1972 auto classInitRef = new llvm::GlobalVariable(TheModule,
1973 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
David Chisnall7b36a862019-03-31 11:22:33 +00001974 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
David Chisnall93ce0182018-08-10 12:53:13 +00001975 classInitRef->setSection(sectionName<ClassSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001976 CGM.addUsedGlobal(classInitRef);
1977
1978 EmittedClass = true;
1979 }
1980 public:
1981 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1982 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1983 PtrToObjCSuperTy, SelectorTy);
1984 // struct objc_property
1985 // {
1986 // const char *name;
1987 // const char *attributes;
1988 // const char *type;
1989 // SEL getter;
1990 // SEL setter;
1991 // }
1992 PropertyMetadataTy =
1993 llvm::StructType::get(CGM.getLLVMContext(),
1994 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1995 }
1996
1997};
1998
David Chisnall93ce0182018-08-10 12:53:13 +00001999const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2000{
2001"__objc_selectors",
2002"__objc_classes",
2003"__objc_class_refs",
2004"__objc_cats",
2005"__objc_protocols",
2006"__objc_protocol_refs",
2007"__objc_class_aliases",
2008"__objc_constant_string"
2009};
2010
David Chisnall7b36a862019-03-31 11:22:33 +00002011const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2012{
2013".objcrt$SEL",
2014".objcrt$CLS",
2015".objcrt$CLR",
2016".objcrt$CAT",
2017".objcrt$PCL",
2018".objcrt$PCR",
2019".objcrt$CAL",
2020".objcrt$STR"
2021};
2022
Alp Toker272e9bc2013-11-25 00:40:53 +00002023/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00002024class CGObjCObjFW: public CGObjCGNU {
2025protected:
2026 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2027 /// method implementation for this message.
2028 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002029 /// stret lookup function. While this does not seem to make sense at the
2030 /// first look, this is required to call the correct forwarding function.
2031 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002032 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2033 /// structure describing the receiver and the class, and a selector as
2034 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002035 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002036
Craig Topper4f12f102014-03-12 06:41:41 +00002037 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2038 llvm::Value *cmd, llvm::MDNode *node,
2039 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00002040 CGBuilderTy &Builder = CGF.Builder;
2041 llvm::Value *args[] = {
2042 EnforceType(Builder, Receiver, IdTy),
2043 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002044
James Y Knight3933add2019-01-30 02:54:28 +00002045 llvm::CallBase *imp;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002046 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2047 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2048 else
2049 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2050
John McCall3deb1ad2012-08-21 02:47:43 +00002051 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +00002052 return imp;
John McCall3deb1ad2012-08-21 02:47:43 +00002053 }
2054
John McCall7f416cc2015-09-08 08:05:57 +00002055 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00002056 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002057 CGBuilderTy &Builder = CGF.Builder;
2058 llvm::Value *lookupArgs[] = {
2059 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2060 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002061
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002062 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2063 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2064 else
2065 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2066 }
John McCall3deb1ad2012-08-21 02:47:43 +00002067
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002068 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2069 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00002070 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00002071 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00002072
2073 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00002074 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00002075 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002076 if (!ClassSymbol)
2077 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2078 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002079 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002080 return ClassSymbol;
2081 }
2082
2083public:
John McCall3deb1ad2012-08-21 02:47:43 +00002084 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2085 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00002086 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002087 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002088 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002089 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2090 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002091 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002092 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002093 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002094 }
John McCall775086e2012-07-12 02:07:58 +00002095};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002096} // end anonymous namespace
2097
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002098/// Emits a reference to a dummy variable which is emitted with each class.
2099/// This ensures that a linker error will be generated when trying to link
2100/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00002101void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002102 std::string symbolRef = "__objc_class_ref_" + className;
2103 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00002104 if (TheModule.getGlobalVariable(symbolRef))
2105 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002106 std::string symbolName = "__objc_class_name_" + className;
2107 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2108 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002109 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00002110 llvm::GlobalValue::ExternalLinkage,
2111 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002112 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00002113 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00002114 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002115}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002116
David Chisnalld7972f52011-03-23 16:36:54 +00002117CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00002118 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00002119 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00002120 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2121 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00002122 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00002123
2124 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
David Chisnall93ce0182018-08-10 12:53:13 +00002125 usesSEHExceptions =
2126 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
David Chisnall01aa4672010-04-28 19:33:36 +00002127
David Chisnalld7972f52011-03-23 16:36:54 +00002128 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002129 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002130 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002131 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002132 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00002133 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002134 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002135 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002136 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002137 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00002138
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002139 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2140 // C string type. Used in lots of places.
2141 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00002142 ProtocolPtrTy = llvm::PointerType::getUnqual(
2143 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002144
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002145 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002146 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002147 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00002148 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00002149 QualType selTy = CGM.getContext().getObjCSelType();
2150 if (QualType() == selTy) {
2151 SelectorTy = PtrToInt8Ty;
2152 } else {
2153 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2154 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002155
Owen Anderson9793f0e2009-07-29 22:16:19 +00002156 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00002157 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00002158
David Chisnallcdd207e2011-10-04 15:35:30 +00002159 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2160 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2161
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002162 IntPtrTy =
2163 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002164
Chris Lattner4bd55962008-03-30 23:03:07 +00002165 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00002166 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2167 ASTIdTy = CanQualType();
2168 if (UnqualIdTy != QualType()) {
2169 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00002170 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00002171 } else {
2172 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00002173 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00002174 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002175 ProtocolTy = llvm::StructType::get(IdTy,
2176 PtrToInt8Ty, // name
2177 PtrToInt8Ty, // protocols
2178 PtrToInt8Ty, // instance methods
2179 PtrToInt8Ty, // class methods
2180 PtrToInt8Ty, // optional instance methods
2181 PtrToInt8Ty, // optional class methods
2182 PtrToInt8Ty, // properties
2183 PtrToInt8Ty);// optional properties
2184
2185 // struct objc_property_gsv1
2186 // {
2187 // const char *name;
2188 // char attributes;
2189 // char attributes2;
2190 // char unused1;
2191 // char unused2;
2192 // const char *getter_name;
2193 // const char *getter_types;
2194 // const char *setter_name;
2195 // const char *setter_types;
2196 // }
2197 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2198 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2199 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002200
Serge Guelton1d993272017-05-09 19:31:30 +00002201 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002202 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2203
Chris Lattnera5f58b02011-07-09 17:41:47 +00002204 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002205
2206 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002207 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2208 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002209 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002210 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002211 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002212 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002213
2214 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002215 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002216
2217 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2218 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002219 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002220 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2221 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002222 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002223 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002224 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2225 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002226 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002227 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2228 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002229
Chris Lattner4bd55962008-03-30 23:03:07 +00002230 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002231 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002232 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2233 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002234
David Blaikiebbafb8a2012-03-11 07:00:24 +00002235 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002236 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002237 RuntimeVersion = 10;
2238
David Chisnalld3858d62011-03-25 11:57:33 +00002239 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002240 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002241 // This is a bit of an hack. We should sort this out by having a proper
2242 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2243 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002244 // Get selectors needed in GC mode
2245 RetainSel = GetNullarySelector("retain", CGM.getContext());
2246 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2247 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2248
2249 // Get functions needed in GC mode
2250
2251 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002252 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002253 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002254 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002255 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002256 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002257 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002258 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002259 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002260 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002261 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002262 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002263 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002264 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002265 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002266}
Mike Stumpdd93a192009-07-31 21:31:32 +00002267
John McCall882987f2013-02-28 19:01:20 +00002268llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002269 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002270 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002271 // With the incompatible ABI, this will need to be replaced with a direct
2272 // reference to the class symbol. For the compatible nonfragile ABI we are
2273 // still performing this lookup at run time but emitting the symbol for the
2274 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002275 //
2276 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2277 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002278 if (!isWeak)
2279 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002280
James Y Knight9871db02019-02-05 16:42:33 +00002281 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2282 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002283 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002284}
2285
David Chisnall920e83b2011-06-29 13:16:41 +00002286// This has to perform the lookup every time, since posing and related
2287// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002288llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002289 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002290 auto *Value =
2291 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002292 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2293 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002294 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002295}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002296
John McCall882987f2013-02-28 19:01:20 +00002297llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002298 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2299 if (CGM.getTriple().isOSBinFormatCOFF()) {
2300 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2301 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2302 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2303 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2304
2305 const VarDecl *VD = nullptr;
2306 for (const auto &Result : DC->lookup(&II))
2307 if ((VD = dyn_cast<VarDecl>(Result)))
2308 break;
2309
Rafael Espindolab7350042018-03-01 00:35:47 +00002310 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002311 }
2312 }
2313 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002314}
2315
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002316llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2317 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002318 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002319 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002320
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002321 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002322 e = Types.end() ; i!=e ; i++) {
2323 if (i->first == TypeEncoding) {
2324 SelValue = i->second;
2325 break;
2326 }
2327 }
Craig Topper8a13c412014-05-21 05:09:00 +00002328 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002329 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002330 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002331 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002332 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002333 }
2334
David Chisnall76803412011-03-23 22:52:06 +00002335 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002336}
2337
John McCall7f416cc2015-09-08 08:05:57 +00002338Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2339 llvm::Value *SelValue = GetSelector(CGF, Sel);
2340
2341 // Store it to a temporary. Does this satisfy the semantics of
2342 // GetAddrOfSelector? Hopefully.
2343 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2344 CGF.getPointerAlign());
2345 CGF.Builder.CreateStore(SelValue, tmp);
2346 return tmp;
2347}
2348
2349llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002350 return GetTypedSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002351}
2352
John McCall882987f2013-02-28 19:01:20 +00002353llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2354 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002355 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002356 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002357}
2358
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002359llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002360 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2361 // With the old ABI, there was only one kind of catchall, which broke
2362 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2363 // a pointer indicating object catchalls, and NULL to indicate real
2364 // catchalls
2365 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2366 return MakeConstantString("@id");
2367 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002368 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002369 }
David Chisnalld3858d62011-03-25 11:57:33 +00002370 }
John McCallc31d8932012-11-14 09:08:34 +00002371
2372 // All other types should be Objective-C interface pointer types.
2373 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2374 assert(OPT && "Invalid @catch type.");
2375 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2376 assert(IDecl && "Invalid @catch type.");
2377 return MakeConstantString(IDecl->getIdentifier()->getName());
2378}
2379
2380llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
David Chisnall93ce0182018-08-10 12:53:13 +00002381 if (usesSEHExceptions)
2382 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2383
John McCallc31d8932012-11-14 09:08:34 +00002384 if (!CGM.getLangOpts().CPlusPlus)
2385 return CGObjCGNU::GetEHType(T);
2386
David Chisnalle1d2584d2011-03-20 21:35:39 +00002387 // For Objective-C++, we want to provide the ability to catch both C++ and
2388 // Objective-C objects in the same function.
2389
2390 // There's a particular fixed type info for 'id'.
2391 if (T->isObjCIdType() ||
2392 T->isObjCQualifiedIdType()) {
2393 llvm::Constant *IDEHType =
2394 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2395 if (!IDEHType)
2396 IDEHType =
2397 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2398 false,
2399 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002400 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002401 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2402 }
2403
2404 const ObjCObjectPointerType *PT =
2405 T->getAs<ObjCObjectPointerType>();
2406 assert(PT && "Invalid @catch type.");
2407 const ObjCInterfaceType *IT = PT->getInterfaceType();
2408 assert(IT && "Invalid @catch type.");
2409 std::string className = IT->getDecl()->getIdentifier()->getName();
2410
2411 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2412
2413 // Return the existing typeinfo if it exists
2414 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002415 if (typeinfo)
2416 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002417
2418 // Otherwise create it.
2419
2420 // vtable for gnustep::libobjc::__objc_class_type_info
2421 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2422 // platform's name mangling.
2423 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002424 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002425 if (!Vtable) {
2426 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002427 llvm::GlobalValue::ExternalLinkage,
2428 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002429 }
2430 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002431 auto *BVtable = llvm::ConstantExpr::getBitCast(
2432 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2433 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002434
2435 llvm::Constant *typeName =
2436 ExportUniqueString(className, "__objc_eh_typename_");
2437
John McCall23c9dc62016-11-28 22:18:27 +00002438 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002439 auto fields = builder.beginStruct();
2440 fields.add(BVtable);
2441 fields.add(typeName);
2442 llvm::Constant *TI =
2443 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2444 CGM.getPointerAlign(),
2445 /*constant*/ false,
2446 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002447 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002448}
2449
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002450/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002451ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002452
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002453 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002454 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002455
David Chisnall358e7512010-01-27 12:49:23 +00002456 // Look for an existing one
2457 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2458 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002459 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002460
David Blaikiebbafb8a2012-03-11 07:00:24 +00002461 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002462
David Chisnall404bbcb2018-05-22 10:13:06 +00002463 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002464
2465 std::string Sym = "_OBJC_CLASS_";
2466 Sym += StringClass;
2467
2468 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2469
2470 if (!isa)
2471 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002472 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002473 else if (isa->getType() != PtrToIdTy)
2474 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2475
John McCall23c9dc62016-11-28 22:18:27 +00002476 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002477 auto Fields = Builder.beginStruct();
2478 Fields.add(isa);
2479 Fields.add(MakeConstantString(Str));
2480 Fields.addInt(IntTy, Str.size());
2481 llvm::Constant *ObjCStr =
2482 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002483 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2484 ObjCStrings[Str] = ObjCStr;
2485 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002486 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002487}
2488
2489///Generates a message send where the super is the receiver. This is a message
2490///send to self with special delivery semantics indicating which class's method
2491///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002492RValue
2493CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002494 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002495 QualType ResultType,
2496 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002497 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002498 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002499 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002500 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002501 const CallArgList &CallArgs,
2502 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002503 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002504 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002505 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002506 return RValue::get(EnforceType(Builder, Receiver,
2507 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002508 }
2509 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002510 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002511 }
2512 }
David Chisnallea529a42010-05-01 12:37:16 +00002513
John McCall882987f2013-02-28 19:01:20 +00002514 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002515 CallArgList ActualArgs;
2516
Eli Friedman43dca6a2011-05-02 17:57:46 +00002517 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2518 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002519 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002520
John McCalla729c622012-02-17 03:33:10 +00002521 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002522
Craig Topper8a13c412014-05-21 05:09:00 +00002523 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002524 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2525 if (isV2ABI) {
2526 ReceiverClass = GetClassNamed(CGF,
2527 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002528 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002529 // Load the isa pointer of the superclass is this is a class method.
2530 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2531 llvm::PointerType::getUnqual(IdTy));
2532 ReceiverClass =
2533 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002534 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002535 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002536 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002537 if (isCategoryImpl) {
James Y Knight9871db02019-02-05 16:42:33 +00002538 llvm::FunctionCallee classLookupFunction = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002539 if (IsClassMessage) {
2540 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2541 IdTy, PtrTy, true), "objc_get_meta_class");
2542 } else {
2543 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2544 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002545 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002546 ReceiverClass = Builder.CreateCall(classLookupFunction,
2547 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002548 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002549 // Set up global aliases for the metaclass or class pointer if they do not
2550 // already exist. These will are forward-references which will be set to
2551 // pointers to the class and metaclass structure created for the runtime
2552 // load function. To send a message to super, we look up the value of the
2553 // super_class pointer from either the class or metaclass structure.
2554 if (IsClassMessage) {
2555 if (!MetaClassPtrAlias) {
2556 MetaClassPtrAlias = llvm::GlobalAlias::create(
2557 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2558 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2559 }
2560 ReceiverClass = MetaClassPtrAlias;
2561 } else {
2562 if (!ClassPtrAlias) {
2563 ClassPtrAlias = llvm::GlobalAlias::create(
2564 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2565 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2566 }
2567 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002568 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002569 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002570 // Cast the pointer to a simplified version of the class structure
2571 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2572 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2573 llvm::PointerType::getUnqual(CastTy));
2574 // Get the superclass pointer
2575 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2576 // Load the superclass pointer
2577 ReceiverClass =
2578 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002579 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002580 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002581 llvm::StructType *ObjCSuperTy =
2582 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002583
David Chisnall404bbcb2018-05-22 10:13:06 +00002584 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002585 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002586
James Y Knight751fe282019-02-09 22:22:28 +00002587 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2588 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002589
David Chisnall76803412011-03-23 22:52:06 +00002590 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002591
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002592 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002593 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002594 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002595
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002596 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002597 llvm::MDString::get(VMContext, Sel.getAsString()),
2598 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002599 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2600 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002601 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002602
John McCallb92ab1a2016-10-26 23:46:34 +00002603 CGCallee callee(CGCalleeInfo(), imp);
2604
James Y Knight3933add2019-01-30 02:54:28 +00002605 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002606 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002607 call->setMetadata(msgSendMDKind, node);
2608 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002609}
2610
Mike Stump11289f42009-09-09 15:08:12 +00002611/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002612RValue
2613CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002614 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002615 QualType ResultType,
2616 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002617 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002618 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002619 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002620 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002621 CGBuilderTy &Builder = CGF.Builder;
2622
David Chisnall75afda62010-04-27 15:08:48 +00002623 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002624 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002625 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002626 return RValue::get(EnforceType(Builder, Receiver,
2627 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002628 }
2629 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002630 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002631 }
2632 }
David Chisnall75afda62010-04-27 15:08:48 +00002633
David Chisnall75afda62010-04-27 15:08:48 +00002634 // If the return type is something that goes in an integer register, the
2635 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2636 // ourselves.
2637 //
2638 // The language spec says the result of this kind of message send is
2639 // undefined, but lots of people seem to have forgotten to read that
2640 // paragraph and insist on sending messages to nil that have structure
2641 // returns. With GCC, this generates a random return value (whatever happens
2642 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002643 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
Fangrui Song6907ce22018-07-30 19:24:48 +00002644 // the stack.
David Chisnall76803412011-03-23 22:52:06 +00002645 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2646 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002647
Craig Topper8a13c412014-05-21 05:09:00 +00002648 llvm::BasicBlock *startBB = nullptr;
2649 llvm::BasicBlock *messageBB = nullptr;
2650 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002651
2652 if (!isPointerSizedReturn) {
2653 startBB = Builder.GetInsertBlock();
2654 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002655 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002656
Fangrui Song6907ce22018-07-30 19:24:48 +00002657 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
David Chisnall75afda62010-04-27 15:08:48 +00002658 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002659 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002660 CGF.EmitBlock(messageBB);
2661 }
2662
David Chisnall9f57c292009-08-17 16:35:33 +00002663 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002664 llvm::Value *cmd;
2665 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002666 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002667 else
John McCall882987f2013-02-28 19:01:20 +00002668 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002669 cmd = EnforceType(Builder, cmd, SelectorTy);
2670 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002671
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002672 llvm::Metadata *impMD[] = {
2673 llvm::MDString::get(VMContext, Sel.getAsString()),
2674 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2675 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2676 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002677 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002678
David Chisnall76803412011-03-23 22:52:06 +00002679 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002680 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2681 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002682 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002683
2684 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2685
David Chisnall8c93cf22011-10-24 14:07:03 +00002686 // Get the IMP to call
2687 llvm::Value *imp;
2688
2689 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2690 // functions. These are not supported on all platforms (or all runtimes on a
Fangrui Song6907ce22018-07-30 19:24:48 +00002691 // given platform), so we
David Chisnall8c93cf22011-10-24 14:07:03 +00002692 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002693 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002694 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002695 break;
2696 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002697 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002698 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
James Y Knight9871db02019-02-05 16:42:33 +00002699 imp =
2700 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2701 "objc_msgSend_fpret")
2702 .getCallee();
John McCalla729c622012-02-17 03:33:10 +00002703 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002704 // The actual types here don't matter - we're going to bitcast the
2705 // function anyway
James Y Knight9871db02019-02-05 16:42:33 +00002706 imp =
2707 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2708 "objc_msgSend_stret")
2709 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002710 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002711 imp = CGM.CreateRuntimeFunction(
2712 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2713 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002714 }
2715 }
2716
David Chisnall6aec31a2011-12-01 18:40:09 +00002717 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002718 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002719
John McCalla729c622012-02-17 03:33:10 +00002720 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002721
James Y Knight3933add2019-01-30 02:54:28 +00002722 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002723 CGCallee callee(CGCalleeInfo(), imp);
2724 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002725 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002726
David Chisnall29cefd12010-05-20 13:45:48 +00002727
David Chisnall75afda62010-04-27 15:08:48 +00002728 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002729 messageBB = CGF.Builder.GetInsertBlock();
2730 CGF.Builder.CreateBr(continueBB);
2731 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002732 if (msgRet.isScalar()) {
2733 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002734 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002735 phi->addIncoming(v, messageBB);
2736 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2737 msgRet = RValue::get(phi);
2738 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002739 Address v = msgRet.getAggregateAddress();
2740 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2741 llvm::Type *RetTy = v.getElementType();
2742 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2743 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2744 phi->addIncoming(v.getPointer(), messageBB);
2745 phi->addIncoming(NullVal.getPointer(), startBB);
2746 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002747 } else /* isComplex() */ {
2748 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002749 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002750 phi->addIncoming(v.first, messageBB);
2751 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2752 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002753 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002754 phi2->addIncoming(v.second, messageBB);
2755 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2756 startBB);
2757 msgRet = RValue::getComplex(phi, phi2);
2758 }
2759 }
2760 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002761}
2762
Mike Stump11289f42009-09-09 15:08:12 +00002763/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002764/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002765llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002766GenerateMethodList(StringRef ClassName,
2767 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002768 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002769 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002770 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002771 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002772
John McCall23c9dc62016-11-28 22:18:27 +00002773 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002774
2775 auto MethodList = Builder.beginStruct();
2776 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002777 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002778
Mike Stump11289f42009-09-09 15:08:12 +00002779 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002780 llvm::StructType *ObjCMethodTy =
2781 llvm::StructType::get(CGM.getLLVMContext(), {
2782 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2783 PtrToInt8Ty, // Method types
2784 IMPTy // Method pointer
2785 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002786 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2787 if (isV2ABI) {
2788 // size_t size;
2789 llvm::DataLayout td(&TheModule);
2790 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2791 CGM.getContext().getCharWidth());
2792 ObjCMethodTy =
2793 llvm::StructType::get(CGM.getLLVMContext(), {
2794 IMPTy, // Method pointer
2795 PtrToInt8Ty, // Selector
2796 PtrToInt8Ty // Extended type encoding
2797 });
2798 } else {
2799 ObjCMethodTy =
2800 llvm::StructType::get(CGM.getLLVMContext(), {
2801 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2802 PtrToInt8Ty, // Method types
2803 IMPTy // Method pointer
2804 });
2805 }
2806 auto MethodArray = MethodList.beginArray();
2807 ASTContext &Context = CGM.getContext();
2808 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002809 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002810 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002811 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002812 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002813 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002814 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2815 if (isV2ABI) {
2816 Method.addBitCast(FnPtr, IMPTy);
2817 Method.add(GetConstantSelector(OMD->getSelector(),
2818 Context.getObjCEncodingForMethodDecl(OMD)));
2819 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2820 } else {
2821 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2822 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2823 Method.addBitCast(FnPtr, IMPTy);
2824 }
2825 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002826 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002827 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002828
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002829 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002830 return MethodList.finishAndCreateGlobal(".objc_method_list",
2831 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002832}
2833
2834/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002835llvm::Constant *CGObjCGNU::
2836GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2837 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002838 ArrayRef<llvm::Constant *> IvarOffsets,
2839 ArrayRef<llvm::Constant *> IvarAlign,
2840 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002841 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002842 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002843
John McCall23c9dc62016-11-28 22:18:27 +00002844 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002845
2846 // Structure containing array count followed by array.
2847 auto IvarList = Builder.beginStruct();
2848 IvarList.addInt(IntTy, (int)IvarNames.size());
2849
2850 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002851 llvm::StructType *ObjCIvarTy =
2852 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002853
2854 // Array of ivar structures.
2855 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002856 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002857 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2858 Ivar.add(IvarNames[i]);
2859 Ivar.add(IvarTypes[i]);
2860 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002861 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002862 }
John McCallf1788632016-11-28 22:18:30 +00002863 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002864
2865 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002866 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2867 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002868}
2869
2870/// Generate a class structure
2871llvm::Constant *CGObjCGNU::GenerateClassStructure(
2872 llvm::Constant *MetaClass,
2873 llvm::Constant *SuperClass,
2874 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002875 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002876 llvm::Constant *Version,
2877 llvm::Constant *InstanceSize,
2878 llvm::Constant *IVars,
2879 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002880 llvm::Constant *Protocols,
2881 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002882 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002883 llvm::Constant *StrongIvarBitmap,
2884 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002885 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002886 // Set up the class structure
2887 // Note: Several of these are char*s when they should be ids. This is
2888 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002889 //
2890 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2891 // anyway; the classes will still work with the GNU runtime, they will just
2892 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002893 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002894 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002895 PtrToInt8Ty, // super_class
2896 PtrToInt8Ty, // name
2897 LongTy, // version
2898 LongTy, // info
2899 LongTy, // instance_size
2900 IVars->getType(), // ivars
2901 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002902 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002903 PtrTy, // dtable
2904 PtrTy, // subclass_list
2905 PtrTy, // sibling_class
2906 PtrTy, // protocols
2907 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002908 // New ABI:
2909 LongTy, // abi_version
2910 IvarOffsets->getType(), // ivar_offsets
2911 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002912 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002913 IntPtrTy // weak_pointers
2914 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002915
John McCall23c9dc62016-11-28 22:18:27 +00002916 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002917 auto Elements = Builder.beginStruct(ClassTy);
2918
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002919 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002920
Fangrui Song6907ce22018-07-30 19:24:48 +00002921 // isa
John McCallecee86f2016-11-30 20:19:46 +00002922 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002923 // super_class
2924 Elements.add(SuperClass);
2925 // name
2926 Elements.add(MakeConstantString(Name, ".class_name"));
2927 // version
2928 Elements.addInt(LongTy, 0);
2929 // info
2930 Elements.addInt(LongTy, info);
2931 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002932 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002933 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002934 Elements.addInt(LongTy,
2935 td.getTypeSizeInBits(ClassTy) /
2936 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002937 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002938 Elements.add(InstanceSize);
2939 // ivars
2940 Elements.add(IVars);
2941 // methods
2942 Elements.add(Methods);
2943 // These are all filled in by the runtime, so we pretend
2944 // dtable
2945 Elements.add(NULLPtr);
2946 // subclass_list
2947 Elements.add(NULLPtr);
2948 // sibling_class
2949 Elements.add(NULLPtr);
2950 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002951 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002952 // gc_object_type
2953 Elements.add(NULLPtr);
2954 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002955 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002956 // ivar_offsets
2957 Elements.add(IvarOffsets);
2958 // properties
2959 Elements.add(Properties);
2960 // strong_pointers
2961 Elements.add(StrongIvarBitmap);
2962 // weak_pointers
2963 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002964 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002965 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002966 // messages in the next ABI. We may already have some weak references to
2967 // this, so check and fix them properly.
2968 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2969 std::string(Name));
2970 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002971 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002972 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2973 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002974 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002975 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002976 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002977 ClassRef->removeFromParent();
2978 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002979 }
2980 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002981}
2982
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002983llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00002984GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002985 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002986 llvm::StructType *ObjCMethodDescTy =
2987 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00002988 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002989 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002990 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00002991 MethodList.addInt(IntTy, Methods.size());
2992 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2993 for (auto *M : Methods) {
2994 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2995 Method.add(MakeConstantString(M->getSelector().getAsString()));
2996 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2997 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002998 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002999 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003000 return MethodList.finishAndCreateGlobal(".objc_method_list",
3001 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003002}
Mike Stumpdd93a192009-07-31 21:31:32 +00003003
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003004// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00003005llvm::Constant *
3006CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3007
John McCall23c9dc62016-11-28 22:18:27 +00003008 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003009 auto ProtocolList = Builder.beginStruct();
3010 ProtocolList.add(NULLPtr);
3011 ProtocolList.addInt(LongTy, Protocols.size());
3012
3013 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003014 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3015 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00003016 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00003017 llvm::StringMap<llvm::Constant*>::iterator value =
3018 ExistingProtocols.find(*iter);
3019 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003020 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00003021 } else {
3022 protocol = value->getValue();
3023 }
John McCallecee86f2016-11-30 20:19:46 +00003024 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003025 }
John McCallf1788632016-11-28 22:18:30 +00003026 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003027 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3028 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003029}
3030
John McCall882987f2013-02-28 19:01:20 +00003031llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003032 const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003033 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3034 if (!protocol)
3035 GenerateProtocol(PD);
Chris Lattner2192fe52011-07-18 04:24:23 +00003036 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003037 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00003038 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003039}
3040
John McCall6c9f1fdb2016-11-19 08:17:24 +00003041llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00003042CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00003043 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00003044 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3045 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003046 // Protocols are objects containing lists of the methods implemented and
3047 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00003048 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003049 auto Elements = Builder.beginStruct();
3050
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003051 // The isa pointer must be set to a magic number so the runtime knows it's
3052 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003053 Elements.add(llvm::ConstantExpr::getIntToPtr(
3054 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3055
3056 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00003057 Elements.add(ProtocolList); /* .protocol_list */
3058 Elements.add(MethodList); /* .instance_methods */
3059 Elements.add(MethodList); /* .class_methods */
3060 Elements.add(MethodList); /* .optional_instance_methods */
3061 Elements.add(MethodList); /* .optional_class_methods */
3062 Elements.add(NULLPtr); /* .properties */
3063 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00003064 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00003065 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003066}
3067
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003068void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003069 std::string ProtocolName = PD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003070
Douglas Gregora715bff2012-01-01 19:51:50 +00003071 // Use the protocol definition, if there is one.
3072 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3073 PD = Def;
3074
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003075 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003076 for (const auto *PI : PD->protocols())
3077 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00003078 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3079 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3080 for (const auto *I : PD->instance_methods())
3081 if (I->isOptional())
3082 OptionalInstanceMethods.push_back(I);
3083 else
3084 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003085 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00003086 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3087 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3088 for (const auto *I : PD->class_methods())
3089 if (I->isOptional())
3090 OptionalClassMethods.push_back(I);
3091 else
3092 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003093
3094 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3095 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003096 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003097 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003098 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003099 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003100 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003101 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003102 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003103
3104 // Property metadata: name, attributes, isSynthesized, setter name, setter
3105 // types, getter name, getter types.
3106 // The isSynthesized value is always set to 0 in a protocol. It exists to
3107 // simplify the runtime library by allowing it to use the same data
3108 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003109
David Chisnall404bbcb2018-05-22 10:13:06 +00003110 llvm::Constant *PropertyList =
3111 GeneratePropertyList(nullptr, PD, false, false);
3112 llvm::Constant *OptionalPropertyList =
3113 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003114
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003115 // Protocols are objects containing lists of the methods implemented and
3116 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003117 // The isa pointer must be set to a magic number so the runtime knows it's
3118 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00003119 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003120 auto Elements = Builder.beginStruct();
3121 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00003122 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003123 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00003124 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00003125 Elements.add(ProtocolList);
3126 Elements.add(InstanceMethodList);
3127 Elements.add(ClassMethodList);
3128 Elements.add(OptionalInstanceMethodList);
3129 Elements.add(OptionalClassMethodList);
3130 Elements.add(PropertyList);
3131 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00003132 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003133 llvm::ConstantExpr::getBitCast(
3134 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3135 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003136}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00003137void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003138 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003139
John McCall23c9dc62016-11-28 22:18:27 +00003140 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003141 auto Elements = Builder.beginStruct();
3142
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003143 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3144 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00003145 Elements.add(MakeConstantString(CategoryName));
3146 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003147 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00003148 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003149 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003150 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00003151 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003152 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003153
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003154 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00003155 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003156 auto ProtocolList = ProtocolListBuilder.beginStruct();
3157 ProtocolList.add(NULLPtr);
3158 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3159 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3160 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003161 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00003162 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003163 }
John McCallf1788632016-11-28 22:18:30 +00003164 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00003165 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003166 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3167 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00003168 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003169 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003170 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003171 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003172}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003173
David Chisnallcdd207e2011-10-04 15:35:30 +00003174/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3175/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3176/// bits set to their values, LSB first, while larger ones are stored in a
3177/// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +00003178///
David Chisnallcdd207e2011-10-04 15:35:30 +00003179/// struct { int32_t length; int32_t values[length]; };
3180///
3181/// The values in the array are stored in host-endian format, with the least
3182/// significant bit being assumed to come first in the bitfield. Therefore, a
3183/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3184/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003185llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003186 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00003187 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00003188 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003189 uint64_t val = 1;
3190 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00003191 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00003192 }
David Chisnalle89ac062011-10-25 10:12:21 +00003193 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00003194 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003195 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00003196 int v=0;
3197 while (v < bitCount) {
3198 int32_t word = 0;
3199 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3200 if (bits[v]) word |= 1<<i;
3201 v++;
3202 }
3203 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3204 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003205
John McCall23c9dc62016-11-28 22:18:27 +00003206 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003207 auto fields = builder.beginStruct();
3208 fields.addInt(Int32Ty, values.size());
3209 auto array = fields.beginArray();
3210 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003211 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003212
3213 llvm::Constant *GS =
3214 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003215 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003216 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003217}
3218
David Chisnall386477a2018-12-28 17:44:54 +00003219llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3220 ObjCCategoryDecl *OCD) {
3221 SmallVector<std::string, 16> Protocols;
3222 for (const auto *PD : OCD->getReferencedProtocols())
3223 Protocols.push_back(PD->getNameAsString());
3224 return GenerateProtocolList(Protocols);
3225}
3226
Daniel Dunbar92992502008-08-15 22:20:32 +00003227void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003228 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3229 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003230 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003231
3232 // Collect the names of referenced protocols
David Chisnall2bfc50b2010-03-13 22:20:45 +00003233 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
Daniel Dunbar92992502008-08-15 22:20:32 +00003234
John McCall23c9dc62016-11-28 22:18:27 +00003235 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003236 auto Elements = Builder.beginStruct();
3237 Elements.add(MakeConstantString(CategoryName));
3238 Elements.add(MakeConstantString(ClassName));
3239 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003240 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3241 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3242 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003243 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003244 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003245 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003246 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003247
3248 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3249 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3250 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003251 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003252 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003253 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003254 // Protocol list
David Chisnall386477a2018-12-28 17:44:54 +00003255 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003256 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3257 const ObjCCategoryDecl *Category =
3258 Class->FindCategoryDeclaration(OCD->getIdentifier());
3259 if (Category) {
3260 // Instance properties
3261 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3262 // Class properties
3263 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3264 } else {
3265 Elements.addNullPointer(PtrTy);
3266 Elements.addNullPointer(PtrTy);
3267 }
3268 }
3269
Owen Andersonade90fd2009-07-29 18:54:39 +00003270 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003271 Elements.finishAndCreateGlobal(
3272 std::string(".objc_category_")+ClassName+CategoryName,
3273 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003274 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003275}
Daniel Dunbar92992502008-08-15 22:20:32 +00003276
David Chisnall404bbcb2018-05-22 10:13:06 +00003277llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3278 const ObjCContainerDecl *OCD,
3279 bool isClassProperty,
3280 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003281
David Chisnall404bbcb2018-05-22 10:13:06 +00003282 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3283 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3284 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3285 ASTContext &Context = CGM.getContext();
3286
3287 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3288 = [&](const ObjCProtocolDecl *Proto) {
3289 for (const auto *P : Proto->protocols())
3290 collectProtocolProperties(P);
3291 for (const auto *PD : Proto->properties()) {
3292 if (isClassProperty != PD->isClassProperty())
3293 continue;
3294 // Skip any properties that are declared in protocols that this class
3295 // conforms to but are not actually implemented by this class.
3296 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3297 continue;
3298 if (!PropertySet.insert(PD->getIdentifier()).second)
3299 continue;
3300 Properties.push_back(PD);
3301 }
3302 };
3303
3304 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3305 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3306 for (auto *PD : ClassExt->properties()) {
3307 if (isClassProperty != PD->isClassProperty())
3308 continue;
3309 PropertySet.insert(PD->getIdentifier());
3310 Properties.push_back(PD);
3311 }
3312
3313 for (const auto *PD : OCD->properties()) {
3314 if (isClassProperty != PD->isClassProperty())
3315 continue;
3316 // If we're generating a list for a protocol, skip optional / required ones
3317 // when generating the other list.
3318 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3319 continue;
3320 // Don't emit duplicate metadata for properties that were already in a
3321 // class extension.
3322 if (!PropertySet.insert(PD->getIdentifier()).second)
3323 continue;
3324
3325 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003326 }
3327
David Chisnall404bbcb2018-05-22 10:13:06 +00003328 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3329 for (const auto *P : OID->all_referenced_protocols())
3330 collectProtocolProperties(P);
3331 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3332 for (const auto *P : CD->protocols())
3333 collectProtocolProperties(P);
3334
3335 auto numProperties = Properties.size();
3336
3337 if (numProperties == 0)
3338 return NULLPtr;
3339
John McCall23c9dc62016-11-28 22:18:27 +00003340 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003341 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003342 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003343
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003344 // Add all of the property methods need adding to the method list and to the
3345 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003346 for (auto *property : Properties) {
3347 bool isSynthesized = false;
3348 bool isDynamic = false;
3349 if (!isProtocol) {
3350 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3351 if (propertyImpl) {
3352 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3353 ObjCPropertyImplDecl::Synthesize);
3354 isDynamic = (propertyImpl->getPropertyImplementation() ==
3355 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003356 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003357 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003358 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003359 }
John McCallf1788632016-11-28 22:18:30 +00003360 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003361
John McCall6c9f1fdb2016-11-19 08:17:24 +00003362 return propertyList.finishAndCreateGlobal(".objc_property_list",
3363 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003364}
3365
David Chisnall92d436b2012-01-31 18:59:20 +00003366void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3367 // Get the class declaration for which the alias is specified.
3368 ObjCInterfaceDecl *ClassDecl =
3369 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003370 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3371 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003372}
3373
Daniel Dunbar92992502008-08-15 22:20:32 +00003374void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3375 ASTContext &Context = CGM.getContext();
3376
3377 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003378 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003379 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003380 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003381 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003382 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003383 EmitClassRef(SuperClassName);
3384 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003385
3386 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003387 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003388 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003389 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003390
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003391 // Emit the symbol that is used to generate linker errors if this class is
3392 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003393 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003394 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003395 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003396 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003397 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003398 llvm::GlobalValue::ExternalLinkage,
3399 llvm::ConstantInt::get(LongTy, 0),
3400 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Daniel Dunbar12119b92009-05-03 10:46:44 +00003403 // Get the size of instances.
Fangrui Song6907ce22018-07-30 19:24:48 +00003404 int instanceSize =
Ken Dyckc8ae5502011-02-09 01:59:34 +00003405 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003406
3407 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003408 SmallVector<llvm::Constant*, 16> IvarNames;
3409 SmallVector<llvm::Constant*, 16> IvarTypes;
3410 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003411 SmallVector<llvm::Constant*, 16> IvarAligns;
3412 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003413
John McCall23c9dc62016-11-28 22:18:27 +00003414 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003415 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003416 SmallVector<bool, 16> WeakIvars;
3417 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003418
Mike Stump11289f42009-09-09 15:08:12 +00003419 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003420 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003421 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3422 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003423 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003424 instanceSize = 0 - (instanceSize - superInstanceSize);
3425 }
David Chisnall18cf7372010-04-19 00:45:34 +00003426
Jordy Rosea91768e2011-07-22 02:08:32 +00003427 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3428 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003429 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003430 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003431 // Get the type encoding for this ivar
3432 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003433 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003434 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003435 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3436 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003437 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003438 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003439 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003440 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003441 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003442 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003443 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3444 // Create the direct offset value
3445 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3446 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003447
David Chisnall1bfe6d32011-07-07 12:34:51 +00003448 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3449 if (OffsetVar) {
3450 OffsetVar->setInitializer(OffsetValue);
3451 // If this is the real definition, change its linkage type so that
3452 // different modules will use this one, rather than their private
3453 // copy.
3454 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3455 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003456 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003457 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003458 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003459 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003460 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003461 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003462 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003463 switch (lt) {
3464 case Qualifiers::OCL_Strong:
3465 StrongIvars.push_back(true);
3466 WeakIvars.push_back(false);
3467 break;
3468 case Qualifiers::OCL_Weak:
3469 StrongIvars.push_back(false);
3470 WeakIvars.push_back(true);
3471 break;
3472 default:
3473 StrongIvars.push_back(false);
3474 WeakIvars.push_back(false);
3475 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003476 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003477 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3478 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003479 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003480 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3481 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003482
Daniel Dunbar92992502008-08-15 22:20:32 +00003483 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003484 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3485 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3486 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003487
David Chisnall404bbcb2018-05-22 10:13:06 +00003488 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3489 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3490 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003491
David Chisnall404bbcb2018-05-22 10:13:06 +00003492 // Collect the same information about synthesized properties, which don't
3493 // show up in the instance method lists.
3494 for (auto *propertyImpl : OID->property_impls())
Fangrui Song6907ce22018-07-30 19:24:48 +00003495 if (propertyImpl->getPropertyImplementation() ==
David Chisnall404bbcb2018-05-22 10:13:06 +00003496 ObjCPropertyImplDecl::Synthesize) {
3497 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
3498 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3499 if (accessor)
3500 InstanceMethods.push_back(accessor);
3501 };
3502 addPropertyMethod(property->getGetterMethodDecl());
3503 addPropertyMethod(property->getSetterMethodDecl());
3504 }
3505
3506 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3507
Daniel Dunbar92992502008-08-15 22:20:32 +00003508 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003509 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003510 for (const auto *I : ClassDecl->protocols())
3511 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003512
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003513 // Get the superclass pointer.
3514 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003515 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003516 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3517 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003518 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003519 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003520 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003521 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003522 // Generate the method and instance variable lists
3523 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003524 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003525 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003526 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003527 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003528 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003529 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003530 // we emit a symbol containing the offset for each ivar in the class. This
3531 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3532 // for the legacy ABI, without causing problems. The converse is also
3533 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003534
David Chisnall5778fce2009-08-31 16:41:57 +00003535 // Offset pointer for getting at the correct field in the ivar list when
3536 // setting up the alias. These are: The base address for the global, the
3537 // ivar array (second field), the ivar in this list (set for each ivar), and
3538 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003539 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003540 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003541 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3542 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003543
Jordy Rosea91768e2011-07-22 02:08:32 +00003544 unsigned ivarIndex = 0;
3545 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3546 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003547 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003548 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003549 // Get the correct ivar field
3550 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003551 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3552 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003553 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003554 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3555 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003556 offset->setInitializer(offsetValue);
3557 // If this is the real definition, change its linkage type so that
3558 // different modules will use this one, rather than their private
3559 // copy.
3560 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003561 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003562 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003563 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003564 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003565 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003566 }
David Chisnalle89ac062011-10-25 10:12:21 +00003567 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003568
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003569 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003570 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3571 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003572 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3573 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003574 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3575 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003576
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003577 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003578 llvm::Constant *ClassStruct = GenerateClassStructure(
3579 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3580 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3581 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3582 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003583 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3584 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003585
3586 // Resolve the class aliases, if they exist.
3587 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003588 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003589 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003590 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003591 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003592 }
3593 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003594 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003595 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003596 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003597 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003598 }
3599
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003600 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003601 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003602 Classes.push_back(ClassStruct);
3603}
3604
Mike Stump11289f42009-09-09 15:08:12 +00003605llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003606 // Only emit an ObjC load function if no Objective-C stuff has been called
3607 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003608 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003609 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003610
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003611 // Add all referenced protocols to a category.
3612 GenerateProtocolHolderCategory();
3613
John McCallecee86f2016-11-30 20:19:46 +00003614 llvm::StructType *selStructTy =
3615 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3616 llvm::Type *selStructPtrTy = SelectorTy;
3617 if (!selStructTy) {
3618 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3619 { PtrToInt8Ty, PtrToInt8Ty });
3620 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003621 }
3622
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003623 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003624 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003625 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003626 llvm::GlobalVariable *fileStatics = [&] {
3627 ConstantInitBuilder builder(CGM);
3628 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003629
John McCallecee86f2016-11-30 20:19:46 +00003630 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3631 if (stringClass.empty()) stringClass = "NXConstantString";
3632 staticsStruct.add(MakeConstantString(stringClass,
3633 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003634
John McCallecee86f2016-11-30 20:19:46 +00003635 auto array = staticsStruct.beginArray();
3636 array.addAll(ConstantStrings);
3637 array.add(NULLPtr);
3638 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003639
John McCallecee86f2016-11-30 20:19:46 +00003640 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3641 CGM.getPointerAlign());
3642 }();
3643
3644 ConstantInitBuilder builder(CGM);
3645 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3646 allStaticsArray.add(fileStatics);
3647 allStaticsArray.addNullPointer(fileStatics->getType());
3648
3649 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3650 CGM.getPointerAlign());
3651 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003652 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003653
John McCallecee86f2016-11-30 20:19:46 +00003654 // Array of classes, categories, and constant objects.
3655
3656 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3657 unsigned selectorCount;
3658
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003659 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003660 llvm::GlobalVariable *selectorList = [&] {
3661 ConstantInitBuilder builder(CGM);
3662 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003663 auto &table = SelectorTable; // MSVC workaround
David Chisnallc66d4802018-08-14 10:05:25 +00003664 std::vector<Selector> allSelectors;
3665 for (auto &entry : table)
3666 allSelectors.push_back(entry.first);
Fangrui Song55fab262018-09-26 22:16:28 +00003667 llvm::sort(allSelectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003668
David Chisnallc66d4802018-08-14 10:05:25 +00003669 for (auto &untypedSel : allSelectors) {
3670 std::string selNameStr = untypedSel.getAsString();
John McCallecee86f2016-11-30 20:19:46 +00003671 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003672
David Chisnallc66d4802018-08-14 10:05:25 +00003673 for (TypedSelector &sel : table[untypedSel]) {
John McCallecee86f2016-11-30 20:19:46 +00003674 llvm::Constant *selectorTypeEncoding = NULLPtr;
3675 if (!sel.first.empty())
3676 selectorTypeEncoding =
3677 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003678
John McCallecee86f2016-11-30 20:19:46 +00003679 auto selStruct = selectors.beginStruct(selStructTy);
3680 selStruct.add(selName);
3681 selStruct.add(selectorTypeEncoding);
3682 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003683
John McCallecee86f2016-11-30 20:19:46 +00003684 // Store the selector alias for later replacement
3685 selectorAliases.push_back(sel.second);
3686 }
David Chisnalld7972f52011-03-23 16:36:54 +00003687 }
David Chisnalld7972f52011-03-23 16:36:54 +00003688
John McCallecee86f2016-11-30 20:19:46 +00003689 // Remember the number of entries in the selector table.
3690 selectorCount = selectors.size();
3691
3692 // NULL-terminate the selector list. This should not actually be required,
3693 // because the selector list has a length field. Unfortunately, the GCC
3694 // runtime decides to ignore the length field and expects a NULL terminator,
3695 // and GCC cooperates with this by always setting the length to 0.
3696 auto selStruct = selectors.beginStruct(selStructTy);
3697 selStruct.add(NULLPtr);
3698 selStruct.add(NULLPtr);
3699 selStruct.finishAndAddTo(selectors);
3700
3701 return selectors.finishAndCreateGlobal(".objc_selector_list",
3702 CGM.getPointerAlign());
3703 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003704
3705 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003706 for (unsigned i = 0; i < selectorCount; ++i) {
3707 llvm::Constant *idxs[] = {
3708 Zeros[0],
3709 llvm::ConstantInt::get(Int32Ty, i)
3710 };
David Chisnalld7972f52011-03-23 16:36:54 +00003711 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003712 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3713 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003714 // If selectors are defined as an opaque type, cast the pointer to this
3715 // type.
John McCallecee86f2016-11-30 20:19:46 +00003716 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3717 selectorAliases[i]->replaceAllUsesWith(selPtr);
3718 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003719 }
David Chisnalld7972f52011-03-23 16:36:54 +00003720
John McCallecee86f2016-11-30 20:19:46 +00003721 llvm::GlobalVariable *symtab = [&] {
3722 ConstantInitBuilder builder(CGM);
3723 auto symtab = builder.beginStruct();
3724
3725 // Number of static selectors
3726 symtab.addInt(LongTy, selectorCount);
3727
3728 symtab.addBitCast(selectorList, selStructPtrTy);
3729
3730 // Number of classes defined.
3731 symtab.addInt(CGM.Int16Ty, Classes.size());
3732 // Number of categories defined
3733 symtab.addInt(CGM.Int16Ty, Categories.size());
3734
3735 // Create an array of classes, then categories, then static object instances
3736 auto classList = symtab.beginArray(PtrToInt8Ty);
3737 classList.addAll(Classes);
3738 classList.addAll(Categories);
3739 // NULL-terminated list of static object instances (mainly constant strings)
3740 classList.add(statics);
3741 classList.add(NULLPtr);
3742 classList.finishAndAddTo(symtab);
3743
3744 // Construct the symbol table.
3745 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3746 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003747
3748 // The symbol table is contained in a module which has some version-checking
3749 // constants
John McCallecee86f2016-11-30 20:19:46 +00003750 llvm::Constant *module = [&] {
3751 llvm::Type *moduleEltTys[] = {
3752 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3753 };
3754 llvm::StructType *moduleTy =
3755 llvm::StructType::get(CGM.getLLVMContext(),
3756 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003757
John McCallecee86f2016-11-30 20:19:46 +00003758 ConstantInitBuilder builder(CGM);
3759 auto module = builder.beginStruct(moduleTy);
3760 // Runtime version, used for ABI compatibility checking.
3761 module.addInt(LongTy, RuntimeVersion);
3762 // sizeof(ModuleTy)
3763 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3764
3765 // The path to the source file where this module was declared
3766 SourceManager &SM = CGM.getContext().getSourceManager();
3767 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3768 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003769 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003770 module.add(MakeConstantString(path, ".objc_source_file_name"));
3771 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003772
John McCallecee86f2016-11-30 20:19:46 +00003773 if (RuntimeVersion >= 10) {
3774 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003775 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003776 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003777 break;
David Chisnalla918b882011-07-07 11:22:31 +00003778 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003779 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003780 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003781 else
John McCallecee86f2016-11-30 20:19:46 +00003782 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003783 break;
3784 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003785 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003786 break;
John McCallecee86f2016-11-30 20:19:46 +00003787 }
David Chisnalla918b882011-07-07 11:22:31 +00003788 }
David Chisnall5c511772011-05-22 22:37:08 +00003789
John McCallecee86f2016-11-30 20:19:46 +00003790 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3791 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003792
3793 // Create the load function calling the runtime entry point with the module
3794 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003795 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003796 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003797 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3798 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003799 llvm::BasicBlock *EntryBB =
3800 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003801 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003802 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003803
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003804 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003805 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
James Y Knight9871db02019-02-05 16:42:33 +00003806 llvm::FunctionCallee Register =
3807 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003808 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003809
David Chisnallaf066bbb2012-02-01 19:16:56 +00003810 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003811 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3812 llvm::FunctionType *RegisterAliasTy =
3813 llvm::FunctionType::get(Builder.getVoidTy(),
3814 ArgTypes, false);
3815 llvm::Function *RegisterAlias = llvm::Function::Create(
3816 RegisterAliasTy,
3817 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3818 &TheModule);
3819 llvm::BasicBlock *AliasBB =
3820 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3821 llvm::BasicBlock *NoAliasBB =
3822 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3823
3824 // Branch based on whether the runtime provided class_registerAlias_np()
3825 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3826 llvm::Constant::getNullValue(RegisterAlias->getType()));
3827 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3828
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003829 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003830 Builder.SetInsertPoint(AliasBB);
3831 // Emit alias registration calls:
3832 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3833 iter != ClassAliases.end(); ++iter) {
3834 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003835 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003836 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003837 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003838 Builder.CreateCall(RegisterAlias,
3839 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003840 }
3841 }
3842 // Jump to end:
3843 Builder.CreateBr(NoAliasBB);
3844
3845 // Missing alias registration function, just return from the function:
3846 Builder.SetInsertPoint(NoAliasBB);
3847 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003848 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003849
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003850 return LoadFunction;
3851}
Daniel Dunbar92992502008-08-15 22:20:32 +00003852
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003853llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003854 const ObjCContainerDecl *CD) {
3855 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003856 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003857 StringRef CategoryName = OCD ? OCD->getName() : "";
3858 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003859 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003860 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003861
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003862 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003863 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003864 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003865 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3866 MethodName, isClassMethod);
3867
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003868 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003869 = llvm::Function::Create(MethodTy,
3870 llvm::GlobalValue::InternalLinkage,
3871 FunctionName,
3872 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003873 return Method;
3874}
3875
James Y Knight9871db02019-02-05 16:42:33 +00003876llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003877 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003878}
3879
James Y Knight9871db02019-02-05 16:42:33 +00003880llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003881 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003882}
3883
James Y Knight9871db02019-02-05 16:42:33 +00003884llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3885 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003886 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003887}
3888
James Y Knight9871db02019-02-05 16:42:33 +00003889llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003890 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003891}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003892
James Y Knight9871db02019-02-05 16:42:33 +00003893llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003894 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003895}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003896
James Y Knight9871db02019-02-05 16:42:33 +00003897llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003898 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003899}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003900
James Y Knight9871db02019-02-05 16:42:33 +00003901llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003902 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003903}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003904
James Y Knight9871db02019-02-05 16:42:33 +00003905llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003906 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003907}
3908
David Chisnalld7972f52011-03-23 16:36:54 +00003909void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003910 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003911 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003912}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003913
David Chisnall3a509cd2009-12-24 02:26:34 +00003914
David Chisnalld7972f52011-03-23 16:36:54 +00003915void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003916 const ObjCAtTryStmt &S) {
3917 // Unlike the Apple non-fragile runtimes, which also uses
3918 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3919 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003920 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003921 // the personality function; this avoids the need for bracketing
3922 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3923 // (or even _Unwind_DeleteException), but probably doesn't
3924 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003925 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003926 // In Objective-C++ mode, we actually emit something equivalent to the C++
Fangrui Song6907ce22018-07-30 19:24:48 +00003927 // exception handler.
David Chisnalld3858d62011-03-25 11:57:33 +00003928 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003929}
3930
David Chisnalld7972f52011-03-23 16:36:54 +00003931void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003932 const ObjCAtThrowStmt &S,
3933 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003934 llvm::Value *ExceptionAsObject;
David Chisnall93ce0182018-08-10 12:53:13 +00003935 bool isRethrow = false;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003936
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003937 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003938 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003939 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003940 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003941 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003942 "Unexpected rethrow outside @catch block.");
3943 ExceptionAsObject = CGF.ObjCEHValueStack.back();
David Chisnall93ce0182018-08-10 12:53:13 +00003944 isRethrow = true;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003945 }
David Chisnall93ce0182018-08-10 12:53:13 +00003946 if (isRethrow && usesSEHExceptions) {
3947 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3948 // not passed it for catchalls and so it is not visible to the catch
3949 // funclet. The real thrown object will still be live on the stack at this
3950 // point and will be rethrown. If we are explicitly rethrowing the object
3951 // that was passed into the `@catch` block, then this code path is not
3952 // reached and we will instead call `objc_exception_throw` with an explicit
3953 // argument.
James Y Knight3933add2019-01-30 02:54:28 +00003954 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3955 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003956 }
3957 else {
3958 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
James Y Knight3933add2019-01-30 02:54:28 +00003959 llvm::CallBase *Throw =
David Chisnall93ce0182018-08-10 12:53:13 +00003960 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
James Y Knight3933add2019-01-30 02:54:28 +00003961 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003962 }
Eli Friedmandc009da2012-08-10 21:26:17 +00003963 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003964 if (ClearInsertionPoint)
3965 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003966}
3967
David Chisnalld7972f52011-03-23 16:36:54 +00003968llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003969 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003970 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003971 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003972 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003973}
3974
David Chisnalld7972f52011-03-23 16:36:54 +00003975void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003976 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003977 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003978 src = EnforceType(B, src, IdTy);
3979 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003980 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003981}
3982
David Chisnalld7972f52011-03-23 16:36:54 +00003983void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003984 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003985 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003986 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003987 src = EnforceType(B, src, IdTy);
3988 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003989 // FIXME. Add threadloca assign API
3990 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
James Y Knight9871db02019-02-05 16:42:33 +00003991 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003992}
3993
David Chisnalld7972f52011-03-23 16:36:54 +00003994void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003995 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00003996 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00003997 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003998 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00003999 dst = EnforceType(B, dst, IdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004000 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004001}
4002
David Chisnalld7972f52011-03-23 16:36:54 +00004003void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004004 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00004005 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004006 src = EnforceType(B, src, IdTy);
4007 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004008 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004009}
4010
David Chisnalld7972f52011-03-23 16:36:54 +00004011void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004012 Address DestPtr,
4013 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004014 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00004015 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00004016 DestPtr = EnforceType(B, DestPtr, PtrTy);
4017 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00004018
James Y Knight9871db02019-02-05 16:42:33 +00004019 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004020}
4021
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004022llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4023 const ObjCInterfaceDecl *ID,
4024 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004025 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004026 // Emit the variable and initialize it with what we think the correct value
4027 // is. This allows code compiled with non-fragile ivars to work correctly
4028 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00004029 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
David Chisnall9e310362018-08-07 12:02:46 +00004030 if (!IvarOffsetPointer)
4031 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4032 llvm::Type::getInt32PtrTy(VMContext), false,
4033 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00004034 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004035}
4036
David Chisnalld7972f52011-03-23 16:36:54 +00004037LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004038 QualType ObjectTy,
4039 llvm::Value *BaseValue,
4040 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004041 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004042 const ObjCInterfaceDecl *ID =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004043 ObjectTy->castAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004044 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4045 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004046}
Mike Stumpdd93a192009-07-31 21:31:32 +00004047
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004048static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4049 const ObjCInterfaceDecl *OID,
4050 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004051 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4052 next = next->getNextIvar()) {
4053 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004054 return OID;
4055 }
Mike Stump11289f42009-09-09 15:08:12 +00004056
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004057 // Otherwise check in the super class.
4058 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4059 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00004060
Craig Topper8a13c412014-05-21 05:09:00 +00004061 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004062}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004063
David Chisnalld7972f52011-03-23 16:36:54 +00004064llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004065 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004066 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00004067 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004068 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00004069
4070 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4071 // and ExternalLinkage, so create a reference to the ivar global and rely on
4072 // the definition being created as part of GenerateClass.
4073 if (RuntimeVersion < 10 ||
4074 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00004075 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00004076 CGF.Builder.CreateAlignedLoad(
4077 Int32Ty, CGF.Builder.CreateAlignedLoad(
4078 ObjCIvarOffsetVariable(Interface, Ivar),
4079 CGF.getPointerAlign(), "ivar"),
4080 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00004081 PtrDiffTy);
4082 std::string name = "__objc_ivar_offset_value_" +
4083 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00004084 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00004085 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00004086 if (!Offset) {
4087 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00004088 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4089 llvm::Constant::getNullValue(IntTy), name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004090 GV->setAlignment(Align.getAsAlign());
John McCall7f416cc2015-09-08 08:05:57 +00004091 Offset = GV;
4092 }
4093 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00004094 if (Offset->getType() != PtrDiffTy)
4095 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4096 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004097 }
Eli Friedman8cbca202012-11-06 22:15:52 +00004098 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4099 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004100}
4101
David Chisnalld7972f52011-03-23 16:36:54 +00004102CGObjCRuntime *
4103clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004104 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4105 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00004106 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00004107 if (Runtime.getVersion() >= VersionTuple(2, 0))
4108 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00004109 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00004110
David Chisnallb601c962012-07-03 20:49:52 +00004111 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00004112 return new CGObjCGCC(CGM);
4113
John McCall775086e2012-07-12 02:07:58 +00004114 case ObjCRuntime::ObjFW:
4115 return new CGObjCObjFW(CGM);
4116
John McCall5fb5df92012-06-20 06:18:46 +00004117 case ObjCRuntime::FragileMacOSX:
4118 case ObjCRuntime::MacOSX:
4119 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00004120 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00004121 llvm_unreachable("these runtimes are not GNU runtimes");
4122 }
4123 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00004124}