blob: 8f984524b4180a525ad03e05bbd51ceb4d6d06fb [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
John McCall6c9f1fdb2016-11-19 08:17:24 +000021#include "ConstantBuilder.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000037#include <cstdarg>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000038
Chris Lattner87ab27d2008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000041
Chris Lattnerb7256cd2008-03-01 08:50:34 +000042namespace {
David Chisnall34d00052011-03-26 11:48:37 +000043/// Class that lazily initialises the runtime function. Avoids inserting the
44/// types and the function declaration into a module if they're not used, and
45/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000046class LazyRuntimeFunction {
47 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000048 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000049 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000050 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000051
52public:
53 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
56 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000057 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000058
David Blaikie7d9e7922015-05-18 22:51:39 +000059 /// Initialises the lazy function with the name, return type, and the types
60 /// of the arguments.
61 LLVM_END_WITH_NULL
62 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
63 CGM = Mod;
64 FunctionName = name;
65 Function = nullptr;
David Blaikiebf178d32015-05-19 21:31:34 +000066 std::vector<llvm::Type *> ArgTys;
David Blaikie7d9e7922015-05-18 22:51:39 +000067 va_list Args;
68 va_start(Args, RetTy);
69 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
70 ArgTys.push_back(ArgTy);
71 va_end(Args);
David Blaikiebf178d32015-05-19 21:31:34 +000072 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
David Blaikie7d9e7922015-05-18 22:51:39 +000073 }
David Blaikiebf178d32015-05-19 21:31:34 +000074
75 llvm::FunctionType *getType() { return FTy; }
76
David Blaikie7d9e7922015-05-18 22:51:39 +000077 /// Overloaded cast operator, allows the class to be implicitly cast to an
78 /// LLVM constant.
79 operator llvm::Constant *() {
80 if (!Function) {
81 if (!FunctionName)
82 return nullptr;
David Blaikie7d9e7922015-05-18 22:51:39 +000083 Function =
84 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
86 return Function;
87 }
88 operator llvm::Function *() {
89 return cast<llvm::Function>((llvm::Constant *)*this);
90 }
David Chisnalld7972f52011-03-23 16:36:54 +000091};
92
93
David Chisnall34d00052011-03-26 11:48:37 +000094/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +000095/// Objective-C support that are specific to the GNU family of runtimes (GCC,
96/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +000097class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +000098protected:
David Chisnall34d00052011-03-26 11:48:37 +000099 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000100 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000101 /// strut objc_super. Used for sending messages to super. This structure
102 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000103 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000104 /// struct objc_super*. The type of the argument to the superclass message
105 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000106 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
108 /// SEL is included in a header somewhere, in which case it will be whatever
109 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000110 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
112 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// Pointer to i8 - LLVM type of char*, for all of the places where the
115 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000116 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000117 /// Instance Method Pointer type. This is a pointer to a function that takes,
118 /// at a minimum, an object and a selector, and is the generic type for
119 /// Objective-C methods. Due to differences between variadic / non-variadic
120 /// calling conventions, it must always be cast to the correct type before
121 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
124 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
125 /// but if the runtime header declaring it is included then it may be a
126 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000127 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000128 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
129 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000130 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000131 /// The clang type of id. Used when using the clang CGCall infrastructure to
132 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000133 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000134 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000135 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000136 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
137 /// used in the code to document the difference between i8* meaning a pointer
138 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// LLVM type for C long type. The runtime uses this in a lot of places where
141 /// it should be using intptr_t, but we can't fix this without breaking
142 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000143 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000145 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000146 /// LLVM type for C intptr_t.
147 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000149 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000150 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
151 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000152 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000154 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000155 /// 32-bit integer type, to save us needing to look it up every time it's used.
156 llvm::IntegerType *Int32Ty;
157 /// 64-bit integer type, to save us needing to look it up every time it's used.
158 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000159 /// Metadata kind used to tie method lookups to message sends. The GNUstep
160 /// runtime provides some LLVM passes that can use this to do things like
161 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000162 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000163
David Chisnall34d00052011-03-26 11:48:37 +0000164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000167 llvm::Constant *MakeConstantString(const std::string &Str,
168 const std::string &Name="") {
John McCall7f416cc2015-09-08 08:05:57 +0000169 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name.c_str());
170 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
171 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000172 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000173
David Chisnall34d00052011-03-26 11:48:37 +0000174 /// Emits a linkonce_odr string, whose name is the prefix followed by the
175 /// string value. This allows the linker to combine the strings between
176 /// different modules. Used for EH typeinfo names, selector strings, and a
177 /// few other things.
Benjamin Kramer81cb4b72016-11-24 16:01:20 +0000178 llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
179 std::string Name = Prefix.str() + Str;
180 auto *ConstStr = TheModule.getGlobalVariable(Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000181 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000182 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnalld3858d62011-03-25 11:57:33 +0000183 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +0000184 llvm::GlobalValue::LinkOnceODRLinkage,
185 value, Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000186 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000187 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
188 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
David Chisnall34d00052011-03-26 11:48:37 +0000191 /// Generates a global structure, initialized by the elements in the vector.
192 /// The element types must match the types of the structure elements in the
193 /// first argument.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000194 llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
John McCall7f416cc2015-09-08 08:05:57 +0000195 CharUnits Align,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000196 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000199 auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
John McCall7f416cc2015-09-08 08:05:57 +0000200 linkage, C, Name);
201 GV->setAlignment(Align.getQuantity());
202 return GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000203 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000204
David Chisnalla5f59412012-10-16 15:11:55 +0000205 /// Returns a property name and encoding string.
206 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
207 const Decl *Container) {
David Chisnallbeb80132013-02-28 13:59:29 +0000208 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnalla5f59412012-10-16 15:11:55 +0000209 if ((R.getKind() == ObjCRuntime::GNUstep) &&
210 (R.getVersion() >= VersionTuple(1, 6))) {
211 std::string NameAndAttributes;
212 std::string TypeStr;
213 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
214 NameAndAttributes += '\0';
215 NameAndAttributes += TypeStr.length() + 3;
216 NameAndAttributes += TypeStr;
217 NameAndAttributes += '\0';
218 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000219 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000220 }
221 return MakeConstantString(PD->getNameAsString());
222 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000223
David Chisnallbeb80132013-02-28 13:59:29 +0000224 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000225 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnallbeb80132013-02-28 13:59:29 +0000226 ObjCPropertyDecl *property, bool isSynthesized=true, bool
227 isDynamic=true) {
228 int attrs = property->getPropertyAttributes();
229 // For read-only properties, clear the copy and retain flags
230 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
231 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
232 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
233 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
234 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
235 }
236 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000237 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000238 attrs >>= 8;
239 attrs <<= 2;
240 // For protocol properties, synthesized and dynamic have no meaning, so we
241 // reuse these flags to indicate that this is a protocol property (both set
242 // has no meaning, as a property can't be both synthesized and dynamic)
243 attrs |= isSynthesized ? (1<<0) : 0;
244 attrs |= isDynamic ? (1<<1) : 0;
245 // The second field is the next four fields left shifted by two, with the
246 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000247 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000248 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000249 Fields.addInt(Int8Ty, 0);
250 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000251 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000252
David Chisnall34d00052011-03-26 11:48:37 +0000253 /// Ensures that the value has the required type, by inserting a bitcast if
254 /// required. This function lets us avoid inserting bitcasts that are
255 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000256 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000257 if (V->getType() == Ty) return V;
258 return B.CreateBitCast(V, Ty);
259 }
John McCall7f416cc2015-09-08 08:05:57 +0000260 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
261 if (V.getType() == Ty) return V;
262 return B.CreateBitCast(V, Ty);
263 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000264
David Chisnall76803412011-03-23 22:52:06 +0000265 // Some zeros used for GEPs in lots of places.
266 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000267 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000268 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000269 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000270 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000271
David Chisnall76803412011-03-23 22:52:06 +0000272private:
David Chisnall34d00052011-03-26 11:48:37 +0000273 /// Placeholder for the class. Lots of things refer to the class before we've
274 /// actually emitted it. We use this alias as a placeholder, and then replace
275 /// it with a pointer to the class structure before finally emitting the
276 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000277 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000278 /// Placeholder for the metaclass. Lots of things refer to the class before
279 /// we've / actually emitted it. We use this alias as a placeholder, and then
280 /// replace / it with a pointer to the metaclass structure before finally
281 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000282 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000283 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000284 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000285 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000286 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000287 /// All of the Objective-C constant strings that have been generated for this
288 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000289 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000290 /// Map from string values to Objective-C constant strings in the output.
291 /// Used to prevent emitting Objective-C strings more than once. This should
292 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000293 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000294 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000295 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000296 /// For each variant of a selector, we store the type encoding and a
297 /// placeholder value. For an untyped selector, the type will be the empty
298 /// string. Selector references are all done via the module's selector table,
299 /// so we create an alias as a placeholder and then replace it with the real
300 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000301 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000302 /// Type of the selector map. This is roughly equivalent to the structure
303 /// used in the GNUstep runtime, which maintains a list of all of the valid
304 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000305 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000306 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000307 /// A map from selectors to selector types. This allows us to emit all
308 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000309 SelectorMap SelectorTable;
310
David Chisnall34d00052011-03-26 11:48:37 +0000311 /// Selectors related to memory management. When compiling in GC mode, we
312 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000313 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000314 /// Runtime functions used for memory management in GC mode. Note that clang
315 /// supports code generation for calling these functions, but neither GNU
316 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000317 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
318 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000319
David Chisnall92d436b2012-01-31 18:59:20 +0000320 typedef std::pair<std::string, std::string> ClassAliasPair;
321 /// All classes that have aliases set for them.
322 std::vector<ClassAliasPair> ClassAliases;
323
David Chisnalld3858d62011-03-25 11:57:33 +0000324protected:
David Chisnall34d00052011-03-26 11:48:37 +0000325 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000326 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000327 /// Function used for rethrowing exceptions, used at the end of \@finally or
328 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000329 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000330 /// Function called when entering a catch function. This is required for
331 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000332 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000333 /// Function called when exiting from a catch block. Used to do exception
334 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000335 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000336 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000337 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000338 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000339 LazyRuntimeFunction SyncExitFn;
340
David Chisnalld3858d62011-03-25 11:57:33 +0000341private:
David Chisnall34d00052011-03-26 11:48:37 +0000342 /// Function called if fast enumeration detects that the collection is
343 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000344 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000345 /// Function for implementing synthesized property getters that return an
346 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000347 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000348 /// Function for implementing synthesized property setters that return an
349 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000350 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000351 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000352 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000354 LazyRuntimeFunction SetStructPropertyFn;
355
David Chisnall34d00052011-03-26 11:48:37 +0000356 /// The version of the runtime that this class targets. Must match the
357 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000358 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000359 /// The version of the protocol class. Used to differentiate between ObjC1
360 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
361 /// components and can not contain declared properties. We always emit
362 /// Objective-C 2 property structures, but we have to pretend that they're
363 /// Objective-C 1 property structures when targeting the GCC runtime or it
364 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000365 const int ProtocolVersion;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000366
David Chisnall34d00052011-03-26 11:48:37 +0000367 /// Generates an instance variable list structure. This is a structure
368 /// containing a size and an array of structures containing instance variable
369 /// metadata. This is used purely for introspection in the fragile ABI. In
370 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000371 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
372 ArrayRef<llvm::Constant *> IvarTypes,
373 ArrayRef<llvm::Constant *> IvarOffsets);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000374
David Chisnall34d00052011-03-26 11:48:37 +0000375 /// Generates a method list structure. This is a structure containing a size
376 /// and an array of structures containing method metadata.
377 ///
378 /// This structure is used by both classes and categories, and contains a next
379 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000380 llvm::Constant *GenerateMethodList(StringRef ClassName,
381 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000382 ArrayRef<Selector> MethodSels,
383 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000384 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000385
James Dennettb9199ee2012-06-13 22:07:09 +0000386 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000387 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
388 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000389 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000390
David Chisnall34d00052011-03-26 11:48:37 +0000391 /// Generates a list of property metadata structures. This follows the same
392 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000393 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000394 SmallVectorImpl<Selector> &InstanceMethodSels,
395 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000396
David Chisnall34d00052011-03-26 11:48:37 +0000397 /// Generates a list of referenced protocols. Classes, categories, and
398 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000399 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000400
David Chisnall34d00052011-03-26 11:48:37 +0000401 /// To ensure that all protocols are seen by the runtime, we add a category on
402 /// a class defined in the runtime, declaring no methods, but adopting the
403 /// protocols. This is a horribly ugly hack, but it allows us to collect all
404 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000405 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000406
David Chisnall34d00052011-03-26 11:48:37 +0000407 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000408 llvm::Constant *GenerateClassStructure(
409 llvm::Constant *MetaClass,
410 llvm::Constant *SuperClass,
411 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000412 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000413 llvm::Constant *Version,
414 llvm::Constant *InstanceSize,
415 llvm::Constant *IVars,
416 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000417 llvm::Constant *Protocols,
418 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000419 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000420 llvm::Constant *StrongIvarBitmap,
421 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000422 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000423
David Chisnall34d00052011-03-26 11:48:37 +0000424 /// Generates a method list. This is used by protocols to define the required
425 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000426 llvm::Constant *GenerateProtocolMethodList(
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000427 ArrayRef<llvm::Constant *> MethodNames,
428 ArrayRef<llvm::Constant *> MethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000429
David Chisnall34d00052011-03-26 11:48:37 +0000430 /// Returns a selector with the specified type encoding. An empty string is
431 /// used to return an untyped selector (with the types field set to NULL).
John McCall882987f2013-02-28 19:01:20 +0000432 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000433 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000434
David Chisnall34d00052011-03-26 11:48:37 +0000435 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000436 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
437 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000438 /// Emits a reference to a class. This allows the linker to object if there
439 /// is no class of the matching name.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000440
John McCall775086e2012-07-12 02:07:58 +0000441protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000442 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000443
David Chisnall920e83b2011-06-29 13:16:41 +0000444 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000445 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000446 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000447
David Chisnall34d00052011-03-26 11:48:37 +0000448 /// Looks up the method for sending a message to the specified object. This
449 /// mechanism differs between the GCC and GNU runtimes, so this method must be
450 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000451 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
452 llvm::Value *&Receiver,
453 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000454 llvm::MDNode *node,
455 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000456
David Chisnallcdd207e2011-10-04 15:35:30 +0000457 /// Looks up the method for sending a message to a superclass. This
458 /// mechanism differs between the GCC and GNU runtimes, so this method must
459 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000460 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000461 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000462 llvm::Value *cmd,
463 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000464
David Chisnallcdd207e2011-10-04 15:35:30 +0000465 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
466 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
467 /// bits set to their values, LSB first, while larger ones are stored in a
468 /// structure of this / form:
469 ///
470 /// struct { int32_t length; int32_t values[length]; };
471 ///
472 /// The values in the array are stored in host-endian format, with the least
473 /// significant bit being assumed to come first in the bitfield. Therefore,
474 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
475 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000476 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000477
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000478public:
David Chisnalld7972f52011-03-23 16:36:54 +0000479 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
480 unsigned protocolClassVersion);
481
John McCall7f416cc2015-09-08 08:05:57 +0000482 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000483
Craig Topper4f12f102014-03-12 06:41:41 +0000484 RValue
485 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
486 QualType ResultType, Selector Sel,
487 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000488 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000489 const ObjCMethodDecl *Method) override;
490 RValue
491 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
492 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000493 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000494 bool isCategoryImpl, llvm::Value *Receiver,
495 bool IsClassMessage, const CallArgList &CallArgs,
496 const ObjCMethodDecl *Method) override;
497 llvm::Value *GetClass(CodeGenFunction &CGF,
498 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000499 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
500 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000501 llvm::Value *GetSelector(CodeGenFunction &CGF,
502 const ObjCMethodDecl *Method) override;
503 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000504
Craig Topper4f12f102014-03-12 06:41:41 +0000505 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD) override;
507 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
508 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
509 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
510 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
511 const ObjCProtocolDecl *PD) override;
512 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
513 llvm::Function *ModuleInitFunction() override;
514 llvm::Constant *GetPropertyGetFunction() override;
515 llvm::Constant *GetPropertySetFunction() override;
516 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
517 bool copy) override;
518 llvm::Constant *GetSetStructFunction() override;
519 llvm::Constant *GetGetStructFunction() override;
520 llvm::Constant *GetCppAtomicObjectGetFunction() override;
521 llvm::Constant *GetCppAtomicObjectSetFunction() override;
522 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Craig Topper4f12f102014-03-12 06:41:41 +0000524 void EmitTryStmt(CodeGenFunction &CGF,
525 const ObjCAtTryStmt &S) override;
526 void EmitSynchronizedStmt(CodeGenFunction &CGF,
527 const ObjCAtSynchronizedStmt &S) override;
528 void EmitThrowStmt(CodeGenFunction &CGF,
529 const ObjCAtThrowStmt &S,
530 bool ClearInsertionPoint=true) override;
531 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000532 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000533 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000534 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000535 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000536 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000537 bool threadlocal=false) override;
538 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000539 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000540 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000541 llvm::Value *src, Address dest) override;
542 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
543 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000544 llvm::Value *Size) override;
545 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
546 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
547 unsigned CVRQualifiers) override;
548 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
549 const ObjCInterfaceDecl *Interface,
550 const ObjCIvarDecl *Ivar) override;
551 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
552 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
553 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000554 return NULLPtr;
555 }
Craig Topper4f12f102014-03-12 06:41:41 +0000556 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
557 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000558 return NULLPtr;
559 }
Craig Topper4f12f102014-03-12 06:41:41 +0000560
561 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000562 return NULLPtr;
563 }
Rafael Espindola554256c2014-02-26 22:25:45 +0000564
Benjamin Kramer0772c422016-02-13 13:42:54 +0000565 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +0000566 bool Weak = false) override {
Craig Topper8a13c412014-05-21 05:09:00 +0000567 return nullptr;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000568 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000569};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000570
David Chisnall34d00052011-03-26 11:48:37 +0000571/// Class representing the legacy GCC Objective-C ABI. This is the default when
572/// -fobjc-nonfragile-abi is not specified.
573///
574/// The GCC ABI target actually generates code that is approximately compatible
575/// with the new GNUstep runtime ABI, but refrains from using any features that
576/// would not work with the GCC runtime. For example, clang always generates
577/// the extended form of the class structure, and the extra fields are simply
578/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000579class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000580 /// The GCC ABI message lookup function. Returns an IMP pointing to the
581 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000582 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000583 /// The GCC ABI superclass message lookup function. Takes a pointer to a
584 /// structure describing the receiver and the class, and a selector as
585 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000586 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000587
David Chisnall76803412011-03-23 22:52:06 +0000588protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000589 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
590 llvm::Value *cmd, llvm::MDNode *node,
591 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000592 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000593 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000594 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000595 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000596 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000597 imp->setMetadata(msgSendMDKind, node);
598 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000599 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000600
John McCall7f416cc2015-09-08 08:05:57 +0000601 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000602 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000603 CGBuilderTy &Builder = CGF.Builder;
604 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
605 PtrToObjCSuperTy).getPointer(), cmd};
606 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
607 }
608
609public:
610 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
611 // IMP objc_msg_lookup(id, SEL);
612 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
613 nullptr);
614 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
615 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
616 PtrToObjCSuperTy, SelectorTy, nullptr);
617 }
David Chisnalld7972f52011-03-23 16:36:54 +0000618};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000619
David Chisnall34d00052011-03-26 11:48:37 +0000620/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000621class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000622 /// The slot lookup function. Returns a pointer to a cacheable structure
623 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000624 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000625 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
626 /// a structure describing the receiver and the class, and a selector as
627 /// arguments. Returns the slot for the corresponding method. Superclass
628 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000629 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000630 /// Specialised function for setting atomic retain properties
631 LazyRuntimeFunction SetPropertyAtomic;
632 /// Specialised function for setting atomic copy properties
633 LazyRuntimeFunction SetPropertyAtomicCopy;
634 /// Specialised function for setting nonatomic retain properties
635 LazyRuntimeFunction SetPropertyNonAtomic;
636 /// Specialised function for setting nonatomic copy properties
637 LazyRuntimeFunction SetPropertyNonAtomicCopy;
638 /// Function to perform atomic copies of C++ objects with nontrivial copy
639 /// constructors from Objective-C ivars.
640 LazyRuntimeFunction CxxAtomicObjectGetFn;
641 /// Function to perform atomic copies of C++ objects with nontrivial copy
642 /// constructors to Objective-C ivars.
643 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000644 /// Type of an slot structure pointer. This is returned by the various
645 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000646 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000647
John McCallc31d8932012-11-14 09:08:34 +0000648 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000649 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000650
David Chisnall76803412011-03-23 22:52:06 +0000651 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000652 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
653 llvm::Value *cmd, llvm::MDNode *node,
654 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000655 CGBuilderTy &Builder = CGF.Builder;
656 llvm::Function *LookupFn = SlotLookupFn;
657
658 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000659 Address ReceiverPtr =
660 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000661 Builder.CreateStore(Receiver, ReceiverPtr);
662
663 llvm::Value *self;
664
665 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
666 self = CGF.LoadObjCSelf();
667 } else {
668 self = llvm::ConstantPointerNull::get(IdTy);
669 }
670
671 // The lookup function is guaranteed not to capture the receiver pointer.
672 LookupFn->setDoesNotCapture(1);
673
David Chisnall0cc83e72011-10-28 17:55:06 +0000674 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000675 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000676 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000677 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000678 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000679 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000680 slot->setMetadata(msgSendMDKind, node);
681
682 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000683 llvm::Value *imp = Builder.CreateAlignedLoad(
684 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
685 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000686
687 // The lookup function may have changed the receiver, so make sure we use
688 // the new one.
689 Receiver = Builder.CreateLoad(ReceiverPtr, true);
690 return imp;
691 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000692
John McCall7f416cc2015-09-08 08:05:57 +0000693 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000694 llvm::Value *cmd,
695 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000696 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000697 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000698
John McCall882987f2013-02-28 19:01:20 +0000699 llvm::CallInst *slot =
700 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000701 slot->setOnlyReadsMemory();
702
John McCall7f416cc2015-09-08 08:05:57 +0000703 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
704 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000705 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000706
David Chisnalld7972f52011-03-23 16:36:54 +0000707 public:
David Chisnall76803412011-03-23 22:52:06 +0000708 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000709 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000710
Chris Lattner845511f2011-06-18 22:49:11 +0000711 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000712 PtrTy, PtrTy, IntTy, IMPTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000713 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
714 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
715 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000716 SelectorTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000717 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
718 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000719 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000720 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000721 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000722 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000723 // void *__cxa_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000724 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000725 // void __cxa_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000726 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000727 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000728 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000729 PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000730 } else if (R.getVersion() >= VersionTuple(1, 7)) {
731 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
732 // id objc_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000733 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000734 // void objc_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000735 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000736 // void _Unwind_Resume_or_Rethrow(void*)
737 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000738 PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000739 }
David Chisnall0d75e062012-12-17 18:54:24 +0000740 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
741 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000742 SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000743 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000744 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000745 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000746 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000747 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Craig Topper8a13c412014-05-21 05:09:00 +0000748 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000749 // void objc_setCppObjectAtomic(void *dest, const void *src, void
750 // *helper);
751 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000752 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000753 // void objc_getCppObjectAtomic(void *dest, const void *src, void
754 // *helper);
755 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000756 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000757 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000758
Craig Topper4f12f102014-03-12 06:41:41 +0000759 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000760 // The optimised functions were added in version 1.7 of the GNUstep
761 // runtime.
762 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
763 VersionTuple(1, 7));
764 return CxxAtomicObjectGetFn;
765 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000766
Craig Topper4f12f102014-03-12 06:41:41 +0000767 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000768 // The optimised functions were added in version 1.7 of the GNUstep
769 // runtime.
770 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
771 VersionTuple(1, 7));
772 return CxxAtomicObjectSetFn;
773 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000774
Craig Topper4f12f102014-03-12 06:41:41 +0000775 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
776 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000777 // The optimised property functions omit the GC check, and so are not
778 // safe to use in GC mode. The standard functions are fast in GC mode,
779 // so there is less advantage in using them.
780 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
781 // The optimised functions were added in version 1.7 of the GNUstep
782 // runtime.
783 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
784 VersionTuple(1, 7));
785
786 if (atomic) {
787 if (copy) return SetPropertyAtomicCopy;
788 return SetPropertyAtomic;
789 }
David Chisnall0d75e062012-12-17 18:54:24 +0000790
Ted Kremenek090a2732014-03-07 18:53:05 +0000791 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000792 }
David Chisnalld7972f52011-03-23 16:36:54 +0000793};
794
Alp Toker272e9bc2013-11-25 00:40:53 +0000795/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000796class CGObjCObjFW: public CGObjCGNU {
797protected:
798 /// The GCC ABI message lookup function. Returns an IMP pointing to the
799 /// method implementation for this message.
800 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000801 /// stret lookup function. While this does not seem to make sense at the
802 /// first look, this is required to call the correct forwarding function.
803 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000804 /// The GCC ABI superclass message lookup function. Takes a pointer to a
805 /// structure describing the receiver and the class, and a selector as
806 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000807 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000808
Craig Topper4f12f102014-03-12 06:41:41 +0000809 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
810 llvm::Value *cmd, llvm::MDNode *node,
811 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000812 CGBuilderTy &Builder = CGF.Builder;
813 llvm::Value *args[] = {
814 EnforceType(Builder, Receiver, IdTy),
815 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000816
817 llvm::CallSite imp;
818 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
819 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
820 else
821 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
822
John McCall3deb1ad2012-08-21 02:47:43 +0000823 imp->setMetadata(msgSendMDKind, node);
824 return imp.getInstruction();
825 }
826
John McCall7f416cc2015-09-08 08:05:57 +0000827 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000828 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000829 CGBuilderTy &Builder = CGF.Builder;
830 llvm::Value *lookupArgs[] = {
831 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
832 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000833
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000834 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
835 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
836 else
837 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
838 }
John McCall3deb1ad2012-08-21 02:47:43 +0000839
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000840 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
841 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000842 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000843 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000844
845 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +0000846 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +0000847 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000848 if (!ClassSymbol)
849 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
850 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000851 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000852 return ClassSymbol;
853 }
854
855public:
John McCall3deb1ad2012-08-21 02:47:43 +0000856 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
857 // IMP objc_msg_lookup(id, SEL);
Craig Topper8a13c412014-05-21 05:09:00 +0000858 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000859 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000860 SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000861 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
862 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000863 PtrToObjCSuperTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000864 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000865 PtrToObjCSuperTy, SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000866 }
John McCall775086e2012-07-12 02:07:58 +0000867};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000868} // end anonymous namespace
869
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000870/// Emits a reference to a dummy variable which is emitted with each class.
871/// This ensures that a linker error will be generated when trying to link
872/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000873void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000874 std::string symbolRef = "__objc_class_ref_" + className;
875 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000876 if (TheModule.getGlobalVariable(symbolRef))
877 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000878 std::string symbolName = "__objc_class_name_" + className;
879 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
880 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000881 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +0000882 llvm::GlobalValue::ExternalLinkage,
883 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000884 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000885 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000886 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000887}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000888
Craig Topperbf3e3272014-08-30 16:55:52 +0000889static std::string SymbolNameForMethod( StringRef ClassName,
890 StringRef CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000891 bool isClassMethod) {
892 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000893 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
894 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000895 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000896 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000897}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000898
David Chisnalld7972f52011-03-23 16:36:54 +0000899CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Craig Topper8a13c412014-05-21 05:09:00 +0000900 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000901 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +0000902 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
903 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
904 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000905
906 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
907
David Chisnalld7972f52011-03-23 16:36:54 +0000908 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000909 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000910 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000911 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000912 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000913 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000914 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000915 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000916 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000917 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000918
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000919 Int8Ty = llvm::Type::getInt8Ty(VMContext);
920 // C string type. Used in lots of places.
921 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
922
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000923 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000924 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000925 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000926 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000927 QualType selTy = CGM.getContext().getObjCSelType();
928 if (QualType() == selTy) {
929 SelectorTy = PtrToInt8Ty;
930 } else {
931 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
932 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000933
Owen Anderson9793f0e2009-07-29 22:16:19 +0000934 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000935 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000936
David Chisnallcdd207e2011-10-04 15:35:30 +0000937 Int32Ty = llvm::Type::getInt32Ty(VMContext);
938 Int64Ty = llvm::Type::getInt64Ty(VMContext);
939
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000940 IntPtrTy =
941 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000942
Chris Lattner4bd55962008-03-30 23:03:07 +0000943 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000944 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
945 ASTIdTy = CanQualType();
946 if (UnqualIdTy != QualType()) {
947 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000948 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000949 } else {
950 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000951 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000952 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000953
Craig Topper8a13c412014-05-21 05:09:00 +0000954 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000955 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
956
Chris Lattnera5f58b02011-07-09 17:41:47 +0000957 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000958
959 // void objc_exception_throw(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000960 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
961 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000962 // int objc_sync_enter(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000963 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000964 // int objc_sync_exit(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000965 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000966
967 // void objc_enumerationMutation (id)
968 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000969 IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000970
971 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
972 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000973 PtrDiffTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000974 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
975 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000976 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000977 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
978 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000979 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000980 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
981 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000982 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000983
Chris Lattner4bd55962008-03-30 23:03:07 +0000984 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000985 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000986 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
987 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000988
David Blaikiebbafb8a2012-03-11 07:00:24 +0000989 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +0000990 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000991 RuntimeVersion = 10;
992
David Chisnalld3858d62011-03-25 11:57:33 +0000993 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000994 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000995 // This is a bit of an hack. We should sort this out by having a proper
996 // CGObjCGNUstep subclass for GC, but we may want to really support the old
997 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000998 // Get selectors needed in GC mode
999 RetainSel = GetNullarySelector("retain", CGM.getContext());
1000 ReleaseSel = GetNullarySelector("release", CGM.getContext());
1001 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
1002
1003 // Get functions needed in GC mode
1004
1005 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001006 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001007 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001008 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00001009 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001010 PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001011 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001012 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001013 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001014 // id objc_assign_weak(id, id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001015 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001016 // id objc_read_weak(id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001017 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001018 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001019 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001020 SizeTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001021 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001022}
Mike Stumpdd93a192009-07-31 21:31:32 +00001023
John McCall882987f2013-02-28 19:01:20 +00001024llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001025 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00001026 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001027 // With the incompatible ABI, this will need to be replaced with a direct
1028 // reference to the class symbol. For the compatible nonfragile ABI we are
1029 // still performing this lookup at run time but emitting the symbol for the
1030 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001031 //
1032 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1033 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001034 if (!isWeak)
1035 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001036
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001037 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001038 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001039 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001040 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001041}
1042
David Chisnall920e83b2011-06-29 13:16:41 +00001043// This has to perform the lookup every time, since posing and related
1044// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001045llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001046 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001047 auto *Value =
1048 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1049 if (CGM.getTriple().isOSBinFormatCOFF()) {
1050 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1051 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1052 if (OID->hasAttr<DLLExportAttr>())
1053 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1054 else if (OID->hasAttr<DLLImportAttr>())
1055 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1056 ClassSymbol->setDLLStorageClass(DLLStorage);
1057 }
1058 }
1059 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001060}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001061
John McCall882987f2013-02-28 19:01:20 +00001062llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001063 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1064 if (CGM.getTriple().isOSBinFormatCOFF()) {
1065 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1066 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1067 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1068 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1069
1070 const VarDecl *VD = nullptr;
1071 for (const auto &Result : DC->lookup(&II))
1072 if ((VD = dyn_cast<VarDecl>(Result)))
1073 break;
1074
1075 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1076 if (!VD || VD->hasAttr<DLLImportAttr>())
1077 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1078 else if (VD->hasAttr<DLLExportAttr>())
1079 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1080
1081 ClassSymbol->setDLLStorageClass(DLLStorage);
1082 }
1083 }
1084 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001085}
1086
John McCall882987f2013-02-28 19:01:20 +00001087llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00001088 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00001089 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00001090 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00001091
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001092 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001093 e = Types.end() ; i!=e ; i++) {
1094 if (i->first == TypeEncoding) {
1095 SelValue = i->second;
1096 break;
1097 }
1098 }
Craig Topper8a13c412014-05-21 05:09:00 +00001099 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001100 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001101 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001102 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001103 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00001104 }
1105
David Chisnall76803412011-03-23 22:52:06 +00001106 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001107}
1108
John McCall7f416cc2015-09-08 08:05:57 +00001109Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1110 llvm::Value *SelValue = GetSelector(CGF, Sel);
1111
1112 // Store it to a temporary. Does this satisfy the semantics of
1113 // GetAddrOfSelector? Hopefully.
1114 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1115 CGF.getPointerAlign());
1116 CGF.Builder.CreateStore(SelValue, tmp);
1117 return tmp;
1118}
1119
1120llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1121 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001122}
1123
John McCall882987f2013-02-28 19:01:20 +00001124llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1125 const ObjCMethodDecl *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001126 std::string SelTypes;
1127 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCall7f416cc2015-09-08 08:05:57 +00001128 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00001129}
1130
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001131llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001132 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1133 // With the old ABI, there was only one kind of catchall, which broke
1134 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1135 // a pointer indicating object catchalls, and NULL to indicate real
1136 // catchalls
1137 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1138 return MakeConstantString("@id");
1139 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00001141 }
David Chisnalld3858d62011-03-25 11:57:33 +00001142 }
John McCallc31d8932012-11-14 09:08:34 +00001143
1144 // All other types should be Objective-C interface pointer types.
1145 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1146 assert(OPT && "Invalid @catch type.");
1147 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1148 assert(IDecl && "Invalid @catch type.");
1149 return MakeConstantString(IDecl->getIdentifier()->getName());
1150}
1151
1152llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1153 if (!CGM.getLangOpts().CPlusPlus)
1154 return CGObjCGNU::GetEHType(T);
1155
David Chisnalle1d2584d2011-03-20 21:35:39 +00001156 // For Objective-C++, we want to provide the ability to catch both C++ and
1157 // Objective-C objects in the same function.
1158
1159 // There's a particular fixed type info for 'id'.
1160 if (T->isObjCIdType() ||
1161 T->isObjCQualifiedIdType()) {
1162 llvm::Constant *IDEHType =
1163 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1164 if (!IDEHType)
1165 IDEHType =
1166 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1167 false,
1168 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001169 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00001170 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1171 }
1172
1173 const ObjCObjectPointerType *PT =
1174 T->getAs<ObjCObjectPointerType>();
1175 assert(PT && "Invalid @catch type.");
1176 const ObjCInterfaceType *IT = PT->getInterfaceType();
1177 assert(IT && "Invalid @catch type.");
1178 std::string className = IT->getDecl()->getIdentifier()->getName();
1179
1180 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1181
1182 // Return the existing typeinfo if it exists
1183 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001184 if (typeinfo)
1185 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001186
1187 // Otherwise create it.
1188
1189 // vtable for gnustep::libobjc::__objc_class_type_info
1190 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1191 // platform's name mangling.
1192 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00001193 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001194 if (!Vtable) {
1195 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00001196 llvm::GlobalValue::ExternalLinkage,
1197 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001198 }
1199 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00001200 auto *BVtable = llvm::ConstantExpr::getBitCast(
1201 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1202 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001203
1204 llvm::Constant *typeName =
1205 ExportUniqueString(className, "__objc_eh_typename_");
1206
John McCall23c9dc62016-11-28 22:18:27 +00001207 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001208 auto fields = builder.beginStruct();
1209 fields.add(BVtable);
1210 fields.add(typeName);
1211 llvm::Constant *TI =
1212 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1213 CGM.getPointerAlign(),
1214 /*constant*/ false,
1215 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001216 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001217}
1218
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001219/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00001220ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001221
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001222 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00001223 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00001224
David Chisnall358e7512010-01-27 12:49:23 +00001225 // Look for an existing one
1226 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1227 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00001228 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00001229
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001231
1232 if (StringClass.empty()) StringClass = "NXConstantString";
1233
1234 std::string Sym = "_OBJC_CLASS_";
1235 Sym += StringClass;
1236
1237 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1238
1239 if (!isa)
1240 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00001241 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00001242 else if (isa->getType() != PtrToIdTy)
1243 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1244
John McCall23c9dc62016-11-28 22:18:27 +00001245 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001246 auto Fields = Builder.beginStruct();
1247 Fields.add(isa);
1248 Fields.add(MakeConstantString(Str));
1249 Fields.addInt(IntTy, Str.size());
1250 llvm::Constant *ObjCStr =
1251 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00001252 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1253 ObjCStrings[Str] = ObjCStr;
1254 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00001255 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001256}
1257
1258///Generates a message send where the super is the receiver. This is a message
1259///send to self with special delivery semantics indicating which class's method
1260///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001261RValue
1262CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001263 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001264 QualType ResultType,
1265 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001266 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001267 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001268 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001269 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001270 const CallArgList &CallArgs,
1271 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001272 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001273 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001274 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001275 return RValue::get(EnforceType(Builder, Receiver,
1276 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001277 }
1278 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001279 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001280 }
1281 }
David Chisnallea529a42010-05-01 12:37:16 +00001282
John McCall882987f2013-02-28 19:01:20 +00001283 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001284 CallArgList ActualArgs;
1285
Eli Friedman43dca6a2011-05-02 17:57:46 +00001286 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1287 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001288 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001289
John McCalla729c622012-02-17 03:33:10 +00001290 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001291
Craig Topper8a13c412014-05-21 05:09:00 +00001292 llvm::Value *ReceiverClass = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001293 if (isCategoryImpl) {
Craig Topper8a13c412014-05-21 05:09:00 +00001294 llvm::Constant *classLookupFunction = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001295 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001296 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001297 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001298 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001299 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001300 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001301 }
David Chisnallea529a42010-05-01 12:37:16 +00001302 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001303 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001304 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001305 // Set up global aliases for the metaclass or class pointer if they do not
1306 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001307 // pointers to the class and metaclass structure created for the runtime
1308 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001309 // super_class pointer from either the class or metaclass structure.
1310 if (IsClassMessage) {
1311 if (!MetaClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001312 MetaClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001313 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001314 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001315 }
1316 ReceiverClass = MetaClassPtrAlias;
1317 } else {
1318 if (!ClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001319 ClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001320 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001321 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001322 }
1323 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001324 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001325 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001326 // Cast the pointer to a simplified version of the class structure
David Blaikie1ed728c2015-04-05 22:45:47 +00001327 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnallea529a42010-05-01 12:37:16 +00001328 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
David Blaikie1ed728c2015-04-05 22:45:47 +00001329 llvm::PointerType::getUnqual(CastTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001330 // Get the superclass pointer
David Blaikie1ed728c2015-04-05 22:45:47 +00001331 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001332 // Load the superclass pointer
John McCall7f416cc2015-09-08 08:05:57 +00001333 ReceiverClass =
1334 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001335 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001336 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Craig Topper8a13c412014-05-21 05:09:00 +00001337 Receiver->getType(), IdTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00001338
1339 // FIXME: Is this really supposed to be a dynamic alloca?
1340 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1341 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001342
David Blaikie2e804282015-04-05 22:47:07 +00001343 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00001344 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00001345 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00001346 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001347
David Chisnall76803412011-03-23 22:52:06 +00001348 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001349
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001350 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001351 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001352 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001353
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001354 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00001355 llvm::MDString::get(VMContext, Sel.getAsString()),
1356 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001357 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1358 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00001359 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001360
John McCallb92ab1a2016-10-26 23:46:34 +00001361 CGCallee callee(CGCalleeInfo(), imp);
1362
David Chisnallff5f88c2010-05-02 13:41:58 +00001363 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001364 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001365 call->setMetadata(msgSendMDKind, node);
1366 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001367}
1368
Mike Stump11289f42009-09-09 15:08:12 +00001369/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001370RValue
1371CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001372 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001373 QualType ResultType,
1374 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001375 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001376 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001377 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001378 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001379 CGBuilderTy &Builder = CGF.Builder;
1380
David Chisnall75afda62010-04-27 15:08:48 +00001381 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001382 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001383 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001384 return RValue::get(EnforceType(Builder, Receiver,
1385 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001386 }
1387 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001388 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001389 }
1390 }
David Chisnall75afda62010-04-27 15:08:48 +00001391
David Chisnall75afda62010-04-27 15:08:48 +00001392 // If the return type is something that goes in an integer register, the
1393 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1394 // ourselves.
1395 //
1396 // The language spec says the result of this kind of message send is
1397 // undefined, but lots of people seem to have forgotten to read that
1398 // paragraph and insist on sending messages to nil that have structure
1399 // returns. With GCC, this generates a random return value (whatever happens
1400 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001401 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1402 // the stack.
1403 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1404 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001405
Craig Topper8a13c412014-05-21 05:09:00 +00001406 llvm::BasicBlock *startBB = nullptr;
1407 llvm::BasicBlock *messageBB = nullptr;
1408 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00001409
1410 if (!isPointerSizedReturn) {
1411 startBB = Builder.GetInsertBlock();
1412 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001413 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001414
1415 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1416 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001417 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001418 CGF.EmitBlock(messageBB);
1419 }
1420
David Chisnall9f57c292009-08-17 16:35:33 +00001421 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001422 llvm::Value *cmd;
1423 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001424 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001425 else
John McCall882987f2013-02-28 19:01:20 +00001426 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001427 cmd = EnforceType(Builder, cmd, SelectorTy);
1428 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001429
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001430 llvm::Metadata *impMD[] = {
1431 llvm::MDString::get(VMContext, Sel.getAsString()),
1432 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1433 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1434 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00001435 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001436
David Chisnall76803412011-03-23 22:52:06 +00001437 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001438 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1439 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001440 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001441
1442 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1443
David Chisnall8c93cf22011-10-24 14:07:03 +00001444 // Get the IMP to call
1445 llvm::Value *imp;
1446
1447 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1448 // functions. These are not supported on all platforms (or all runtimes on a
1449 // given platform), so we
1450 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001451 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001452 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001453 break;
1454 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001455 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001456 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1457 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1458 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001459 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001460 // The actual types here don't matter - we're going to bitcast the
1461 // function anyway
1462 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1463 "objc_msgSend_stret");
1464 } else {
1465 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1466 "objc_msgSend");
1467 }
1468 }
1469
David Chisnall6aec31a2011-12-01 18:40:09 +00001470 // Reset the receiver in case the lookup modified it
1471 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001472
John McCalla729c622012-02-17 03:33:10 +00001473 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001474
David Chisnallff5f88c2010-05-02 13:41:58 +00001475 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001476 CGCallee callee(CGCalleeInfo(), imp);
1477 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001478 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001479
David Chisnall29cefd12010-05-20 13:45:48 +00001480
David Chisnall75afda62010-04-27 15:08:48 +00001481 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001482 messageBB = CGF.Builder.GetInsertBlock();
1483 CGF.Builder.CreateBr(continueBB);
1484 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001485 if (msgRet.isScalar()) {
1486 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001487 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001488 phi->addIncoming(v, messageBB);
1489 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1490 msgRet = RValue::get(phi);
1491 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00001492 Address v = msgRet.getAggregateAddress();
1493 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1494 llvm::Type *RetTy = v.getElementType();
1495 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1496 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1497 phi->addIncoming(v.getPointer(), messageBB);
1498 phi->addIncoming(NullVal.getPointer(), startBB);
1499 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00001500 } else /* isComplex() */ {
1501 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001502 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001503 phi->addIncoming(v.first, messageBB);
1504 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1505 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001506 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001507 phi2->addIncoming(v.second, messageBB);
1508 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1509 startBB);
1510 msgRet = RValue::getComplex(phi, phi2);
1511 }
1512 }
1513 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001514}
1515
Mike Stump11289f42009-09-09 15:08:12 +00001516/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001517/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001518llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00001519GenerateMethodList(StringRef ClassName,
1520 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001521 ArrayRef<Selector> MethodSels,
1522 ArrayRef<llvm::Constant *> MethodTypes,
1523 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001524 if (MethodSels.empty())
1525 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001526
John McCall23c9dc62016-11-28 22:18:27 +00001527 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001528
1529 auto MethodList = Builder.beginStruct();
1530 MethodList.addNullPointer(CGM.Int8PtrTy);
1531 MethodList.addInt(Int32Ty, MethodTypes.size());
1532
Mike Stump11289f42009-09-09 15:08:12 +00001533 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001534 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001535 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1536 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001537 IMPTy, //Method pointer
Craig Topper8a13c412014-05-21 05:09:00 +00001538 nullptr);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001539 auto Methods = MethodList.beginArray();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001540 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
David Chisnalld7972f52011-03-23 16:36:54 +00001541 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001542 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001543 MethodSels[i],
1544 isClassMethodList));
1545 assert(Method && "Can't generate metadata for method that doesn't exist");
1546 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
David Chisnalld7972f52011-03-23 16:36:54 +00001547 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001548 IMPTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001549 Methods.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00001550 llvm::ConstantStruct::get(ObjCMethodTy, {C, MethodTypes[i], Method}));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001551 }
John McCallf1788632016-11-28 22:18:30 +00001552 Methods.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00001553
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001554 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001555 return MethodList.finishAndCreateGlobal(".objc_method_list",
1556 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001557}
1558
1559/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001560llvm::Constant *CGObjCGNU::
1561GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1562 ArrayRef<llvm::Constant *> IvarTypes,
1563 ArrayRef<llvm::Constant *> IvarOffsets) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001564 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00001565 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001566
John McCall23c9dc62016-11-28 22:18:27 +00001567 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001568
1569 // Structure containing array count followed by array.
1570 auto IvarList = Builder.beginStruct();
1571 IvarList.addInt(IntTy, (int)IvarNames.size());
1572
1573 // Get the ivar structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001574 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001575 PtrToInt8Ty,
1576 PtrToInt8Ty,
1577 IntTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001578 nullptr);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001579
1580 // Array of ivar structures.
1581 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001582 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001583 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1584 Ivar.add(IvarNames[i]);
1585 Ivar.add(IvarTypes[i]);
1586 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00001587 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001588 }
John McCallf1788632016-11-28 22:18:30 +00001589 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001590
1591 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001592 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1593 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001594}
1595
1596/// Generate a class structure
1597llvm::Constant *CGObjCGNU::GenerateClassStructure(
1598 llvm::Constant *MetaClass,
1599 llvm::Constant *SuperClass,
1600 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001601 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001602 llvm::Constant *Version,
1603 llvm::Constant *InstanceSize,
1604 llvm::Constant *IVars,
1605 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001606 llvm::Constant *Protocols,
1607 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001608 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001609 llvm::Constant *StrongIvarBitmap,
1610 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001611 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001612 // Set up the class structure
1613 // Note: Several of these are char*s when they should be ids. This is
1614 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001615 //
1616 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1617 // anyway; the classes will still work with the GNU runtime, they will just
1618 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001619 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall207a6302012-01-04 12:02:13 +00001620 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001621 PtrToInt8Ty, // super_class
1622 PtrToInt8Ty, // name
1623 LongTy, // version
1624 LongTy, // info
1625 LongTy, // instance_size
1626 IVars->getType(), // ivars
1627 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001628 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001629 PtrTy, // dtable
1630 PtrTy, // subclass_list
1631 PtrTy, // sibling_class
1632 PtrTy, // protocols
1633 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001634 // New ABI:
1635 LongTy, // abi_version
1636 IvarOffsets->getType(), // ivar_offsets
1637 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001638 IntPtrTy, // strong_pointers
1639 IntPtrTy, // weak_pointers
Craig Topper8a13c412014-05-21 05:09:00 +00001640 nullptr);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001641
John McCall23c9dc62016-11-28 22:18:27 +00001642 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001643 auto Elements = Builder.beginStruct(ClassTy);
1644
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001645 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001646
1647 // isa
1648 Elements.add(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1649 // super_class
1650 Elements.add(SuperClass);
1651 // name
1652 Elements.add(MakeConstantString(Name, ".class_name"));
1653 // version
1654 Elements.addInt(LongTy, 0);
1655 // info
1656 Elements.addInt(LongTy, info);
1657 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00001658 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001659 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001660 Elements.addInt(LongTy,
1661 td.getTypeSizeInBits(ClassTy) /
1662 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00001663 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00001664 Elements.add(InstanceSize);
1665 // ivars
1666 Elements.add(IVars);
1667 // methods
1668 Elements.add(Methods);
1669 // These are all filled in by the runtime, so we pretend
1670 // dtable
1671 Elements.add(NULLPtr);
1672 // subclass_list
1673 Elements.add(NULLPtr);
1674 // sibling_class
1675 Elements.add(NULLPtr);
1676 // protocols
1677 Elements.add(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1678 // gc_object_type
1679 Elements.add(NULLPtr);
1680 // abi_version
1681 Elements.addInt(LongTy, 1);
1682 // ivar_offsets
1683 Elements.add(IvarOffsets);
1684 // properties
1685 Elements.add(Properties);
1686 // strong_pointers
1687 Elements.add(StrongIvarBitmap);
1688 // weak_pointers
1689 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001690 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001691 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001692 // messages in the next ABI. We may already have some weak references to
1693 // this, so check and fix them properly.
1694 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1695 std::string(Name));
1696 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00001697 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001698 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1699 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00001700 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001701 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00001702 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00001703 ClassRef->removeFromParent();
1704 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00001705 }
1706 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001707}
1708
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001709llvm::Constant *CGObjCGNU::
1710GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1711 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001712 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001713 llvm::StructType *ObjCMethodDescTy =
1714 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
John McCall23c9dc62016-11-28 22:18:27 +00001715 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001716 auto MethodList = Builder.beginStruct();
1717 MethodList.addInt(IntTy, MethodNames.size());
1718 auto Methods = MethodList.beginArray(ObjCMethodDescTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001719 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001720 auto Method = Methods.beginStruct(ObjCMethodDescTy);
1721 Method.add(MethodNames[i]);
1722 Method.add(MethodTypes[i]);
John McCallf1788632016-11-28 22:18:30 +00001723 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001724 }
John McCallf1788632016-11-28 22:18:30 +00001725 Methods.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001726 return MethodList.finishAndCreateGlobal(".objc_method_list",
1727 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001728}
Mike Stumpdd93a192009-07-31 21:31:32 +00001729
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001730// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00001731llvm::Constant *
1732CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1733
John McCall23c9dc62016-11-28 22:18:27 +00001734 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001735 auto ProtocolList = Builder.beginStruct();
1736 ProtocolList.add(NULLPtr);
1737 ProtocolList.addInt(LongTy, Protocols.size());
1738
1739 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001740 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1741 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00001742 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00001743 llvm::StringMap<llvm::Constant*>::iterator value =
1744 ExistingProtocols.find(*iter);
1745 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001746 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001747 } else {
1748 protocol = value->getValue();
1749 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001750 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001751 PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001752 Elements.add(Ptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001753 }
John McCallf1788632016-11-28 22:18:30 +00001754 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001755 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1756 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001757}
1758
John McCall882987f2013-02-28 19:01:20 +00001759llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001760 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001761 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001762 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001763 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001764 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001765}
1766
John McCall6c9f1fdb2016-11-19 08:17:24 +00001767llvm::Constant *
1768CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1769 llvm::Constant *ProtocolList = GenerateProtocolList({});
1770 llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001771 // Protocols are objects containing lists of the methods implemented and
1772 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00001773 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001774 auto Elements = Builder.beginStruct();
1775
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001776 // The isa pointer must be set to a magic number so the runtime knows it's
1777 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001778 Elements.add(llvm::ConstantExpr::getIntToPtr(
1779 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1780
1781 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1782 Elements.add(ProtocolList);
1783 Elements.add(MethodList);
1784 Elements.add(MethodList);
1785 Elements.add(MethodList);
1786 Elements.add(MethodList);
1787 return Elements.finishAndCreateGlobal(".objc_protocol",
1788 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001789}
1790
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001791void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1792 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001793 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001794
1795 // Use the protocol definition, if there is one.
1796 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1797 PD = Def;
1798
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001799 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001800 for (const auto *PI : PD->protocols())
1801 Protocols.push_back(PI->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001802 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1803 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1804 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1805 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001806 for (const auto *I : PD->instance_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001807 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001808 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1809 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001810 OptionalInstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001811 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001812 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001813 } else {
1814 InstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001815 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001816 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001817 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001818 }
1819 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001820 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1821 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1822 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1823 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001824 for (const auto *I : PD->class_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001825 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001826 Context.getObjCEncodingForMethodDecl(I,TypeStr);
1827 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001828 OptionalClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001829 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001830 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001831 } else {
1832 ClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001833 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001834 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001835 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001836 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001837
1838 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1839 llvm::Constant *InstanceMethodList =
1840 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1841 llvm::Constant *ClassMethodList =
1842 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001843 llvm::Constant *OptionalInstanceMethodList =
1844 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1845 OptionalInstanceMethodTypes);
1846 llvm::Constant *OptionalClassMethodList =
1847 GenerateProtocolMethodList(OptionalClassMethodNames,
1848 OptionalClassMethodTypes);
1849
1850 // Property metadata: name, attributes, isSynthesized, setter name, setter
1851 // types, getter name, getter types.
1852 // The isSynthesized value is always set to 0 in a protocol. It exists to
1853 // simplify the runtime library by allowing it to use the same data
1854 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001855
John McCall6c9f1fdb2016-11-19 08:17:24 +00001856 llvm::Constant *PropertyList;
1857 llvm::Constant *OptionalPropertyList;
1858 {
1859 llvm::StructType *propertyMetadataTy =
1860 llvm::StructType::get(CGM.getLLVMContext(),
1861 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1862 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001863
John McCall6c9f1fdb2016-11-19 08:17:24 +00001864 unsigned numReqProperties = 0, numOptProperties = 0;
1865 for (auto property : PD->instance_properties()) {
1866 if (property->isOptional())
1867 numOptProperties++;
1868 else
1869 numReqProperties++;
1870 }
David Chisnalla5f59412012-10-16 15:11:55 +00001871
John McCall23c9dc62016-11-28 22:18:27 +00001872 ConstantInitBuilder reqPropertyListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001873 auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1874 reqPropertiesList.addInt(IntTy, numReqProperties);
1875 reqPropertiesList.add(NULLPtr);
1876 auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1877
John McCall23c9dc62016-11-28 22:18:27 +00001878 ConstantInitBuilder optPropertyListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001879 auto optPropertiesList = optPropertyListBuilder.beginStruct();
1880 optPropertiesList.addInt(IntTy, numOptProperties);
1881 optPropertiesList.add(NULLPtr);
1882 auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1883
1884 // Add all of the property methods need adding to the method list and to the
1885 // property metadata list.
1886 for (auto *property : PD->instance_properties()) {
1887 auto &propertiesArray =
1888 (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1889 auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1890
1891 fields.add(MakePropertyEncodingString(property, nullptr));
1892 PushPropertyAttributes(fields, property);
1893
1894 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1895 std::string typeStr;
1896 Context.getObjCEncodingForMethodDecl(getter, typeStr);
1897 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1898 InstanceMethodTypes.push_back(typeEncoding);
1899 fields.add(MakeConstantString(getter->getSelector().getAsString()));
1900 fields.add(typeEncoding);
1901 } else {
1902 fields.add(NULLPtr);
1903 fields.add(NULLPtr);
1904 }
1905 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1906 std::string typeStr;
1907 Context.getObjCEncodingForMethodDecl(setter, typeStr);
1908 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1909 InstanceMethodTypes.push_back(typeEncoding);
1910 fields.add(MakeConstantString(setter->getSelector().getAsString()));
1911 fields.add(typeEncoding);
1912 } else {
1913 fields.add(NULLPtr);
1914 fields.add(NULLPtr);
1915 }
1916
John McCallf1788632016-11-28 22:18:30 +00001917 fields.finishAndAddTo(propertiesArray);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001918 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00001919
John McCallf1788632016-11-28 22:18:30 +00001920 reqPropertiesArray.finishAndAddTo(reqPropertiesList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001921 PropertyList =
1922 reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1923 CGM.getPointerAlign());
1924
John McCallf1788632016-11-28 22:18:30 +00001925 optPropertiesArray.finishAndAddTo(optPropertiesList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001926 OptionalPropertyList =
1927 optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1928 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001929 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001930
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001931 // Protocols are objects containing lists of the methods implemented and
1932 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001933 // The isa pointer must be set to a magic number so the runtime knows it's
1934 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00001935 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001936 auto Elements = Builder.beginStruct();
1937 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00001938 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001939 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1940 Elements.add(
1941 MakeConstantString(ProtocolName, ".objc_protocol_name"));
1942 Elements.add(ProtocolList);
1943 Elements.add(InstanceMethodList);
1944 Elements.add(ClassMethodList);
1945 Elements.add(OptionalInstanceMethodList);
1946 Elements.add(OptionalClassMethodList);
1947 Elements.add(PropertyList);
1948 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001949 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001950 llvm::ConstantExpr::getBitCast(
1951 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1952 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001953}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001954void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001955 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001956 SmallVector<Selector, 1> MethodSels;
1957 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001958
John McCall23c9dc62016-11-28 22:18:27 +00001959 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001960 auto Elements = Builder.beginStruct();
1961
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001962 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1963 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00001964 Elements.add(MakeConstantString(CategoryName));
1965 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001966 // Instance method list
John McCall6c9f1fdb2016-11-19 08:17:24 +00001967 Elements.add(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001968 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1969 // Class method list
John McCall6c9f1fdb2016-11-19 08:17:24 +00001970 Elements.add(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001971 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
John McCall6c9f1fdb2016-11-19 08:17:24 +00001972
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001973 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00001974 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001975 auto ProtocolList = ProtocolListBuilder.beginStruct();
1976 ProtocolList.add(NULLPtr);
1977 ProtocolList.addInt(LongTy, ExistingProtocols.size());
1978 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1979 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001980 iter != endIter ; iter++) {
1981 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1982 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001983 ProtocolElements.add(Ptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001984 }
John McCallf1788632016-11-28 22:18:30 +00001985 ProtocolElements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001986 Elements.add(llvm::ConstantExpr::getBitCast(
1987 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1988 CGM.getPointerAlign()),
1989 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001990 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001991 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00001992 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001993}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001994
David Chisnallcdd207e2011-10-04 15:35:30 +00001995/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1996/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1997/// bits set to their values, LSB first, while larger ones are stored in a
1998/// structure of this / form:
1999///
2000/// struct { int32_t length; int32_t values[length]; };
2001///
2002/// The values in the array are stored in host-endian format, with the least
2003/// significant bit being assumed to come first in the bitfield. Therefore, a
2004/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
2005/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002006llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002007 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002008 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00002009 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002010 uint64_t val = 1;
2011 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00002012 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00002013 }
David Chisnalle89ac062011-10-25 10:12:21 +00002014 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00002015 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002016 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00002017 int v=0;
2018 while (v < bitCount) {
2019 int32_t word = 0;
2020 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2021 if (bits[v]) word |= 1<<i;
2022 v++;
2023 }
2024 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2025 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002026
John McCall23c9dc62016-11-28 22:18:27 +00002027 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002028 auto fields = builder.beginStruct();
2029 fields.addInt(Int32Ty, values.size());
2030 auto array = fields.beginArray();
2031 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00002032 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002033
2034 llvm::Constant *GS =
2035 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002036 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002037 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002038}
2039
Daniel Dunbar92992502008-08-15 22:20:32 +00002040void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002041 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2042 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002043 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002044 SmallVector<Selector, 16> InstanceMethodSels;
2045 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002046 for (const auto *I : OCD->instance_methods()) {
2047 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002048 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002049 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002050 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002051 }
2052
2053 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002054 SmallVector<Selector, 16> ClassMethodSels;
2055 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002056 for (const auto *I : OCD->class_methods()) {
2057 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002058 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002059 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002060 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002061 }
2062
2063 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002064 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002065 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2066 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002067 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2068 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002069 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002070
John McCall23c9dc62016-11-28 22:18:27 +00002071 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002072 auto Elements = Builder.beginStruct();
2073 Elements.add(MakeConstantString(CategoryName));
2074 Elements.add(MakeConstantString(ClassName));
2075 // Instance method list
2076 Elements.add(llvm::ConstantExpr::getBitCast(
Benjamin Kramer30934732016-07-02 11:41:41 +00002077 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2078 InstanceMethodTypes, false),
John McCall6c9f1fdb2016-11-19 08:17:24 +00002079 PtrTy));
2080 // Class method list
2081 Elements.add(llvm::ConstantExpr::getBitCast(
2082 GenerateMethodList(ClassName, CategoryName,
2083 ClassMethodSels, ClassMethodTypes, true),
2084 PtrTy));
2085 // Protocol list
2086 Elements.add(llvm::ConstantExpr::getBitCast(
2087 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00002088 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002089 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00002090 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002091}
Daniel Dunbar92992502008-08-15 22:20:32 +00002092
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002093llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002094 SmallVectorImpl<Selector> &InstanceMethodSels,
2095 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002096 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002097 // Property metadata: name, attributes, attributes2, padding1, padding2,
2098 // setter name, setter types, getter name, getter types.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002099 llvm::StructType *propertyMetadataTy =
2100 llvm::StructType::get(CGM.getLLVMContext(),
2101 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2102 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2103
2104 unsigned numProperties = 0;
2105 for (auto *propertyImpl : OID->property_impls()) {
2106 (void) propertyImpl;
2107 numProperties++;
2108 }
2109
John McCall23c9dc62016-11-28 22:18:27 +00002110 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002111 auto propertyList = builder.beginStruct();
2112 propertyList.addInt(IntTy, numProperties);
2113 propertyList.add(NULLPtr);
2114 auto properties = propertyList.beginArray(propertyMetadataTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002115
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002116 // Add all of the property methods need adding to the method list and to the
2117 // property metadata list.
Aaron Ballmand85eff42014-03-14 15:02:45 +00002118 for (auto *propertyImpl : OID->property_impls()) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002119 auto fields = properties.beginStruct(propertyMetadataTy);
Aaron Ballmand85eff42014-03-14 15:02:45 +00002120 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00002121 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2122 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002123 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2124 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002125
John McCall6c9f1fdb2016-11-19 08:17:24 +00002126 fields.add(MakePropertyEncodingString(property, OID));
2127 PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002128 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002129 std::string TypeStr;
2130 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2131 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002132 if (isSynthesized) {
2133 InstanceMethodTypes.push_back(TypeEncoding);
2134 InstanceMethodSels.push_back(getter->getSelector());
2135 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002136 fields.add(MakeConstantString(getter->getSelector().getAsString()));
2137 fields.add(TypeEncoding);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002138 } else {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002139 fields.add(NULLPtr);
2140 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002141 }
2142 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002143 std::string TypeStr;
2144 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2145 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002146 if (isSynthesized) {
2147 InstanceMethodTypes.push_back(TypeEncoding);
2148 InstanceMethodSels.push_back(setter->getSelector());
2149 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002150 fields.add(MakeConstantString(setter->getSelector().getAsString()));
2151 fields.add(TypeEncoding);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002152 } else {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002153 fields.add(NULLPtr);
2154 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002155 }
John McCallf1788632016-11-28 22:18:30 +00002156 fields.finishAndAddTo(properties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002157 }
John McCallf1788632016-11-28 22:18:30 +00002158 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002159
John McCall6c9f1fdb2016-11-19 08:17:24 +00002160 return propertyList.finishAndCreateGlobal(".objc_property_list",
2161 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002162}
2163
David Chisnall92d436b2012-01-31 18:59:20 +00002164void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2165 // Get the class declaration for which the alias is specified.
2166 ObjCInterfaceDecl *ClassDecl =
2167 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00002168 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2169 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00002170}
2171
Daniel Dunbar92992502008-08-15 22:20:32 +00002172void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2173 ASTContext &Context = CGM.getContext();
2174
2175 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002176 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002177 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002178 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002179 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002180 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002181 EmitClassRef(SuperClassName);
2182 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002183
2184 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002185 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002186 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002187 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002188
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002189 // Emit the symbol that is used to generate linker errors if this class is
2190 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002191 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002192 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002193 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002194 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002195 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002196 llvm::GlobalValue::ExternalLinkage,
2197 llvm::ConstantInt::get(LongTy, 0),
2198 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Daniel Dunbar12119b92009-05-03 10:46:44 +00002201 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002202 int instanceSize =
2203 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002204
2205 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002206 SmallVector<llvm::Constant*, 16> IvarNames;
2207 SmallVector<llvm::Constant*, 16> IvarTypes;
2208 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002209
John McCall23c9dc62016-11-28 22:18:27 +00002210 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002211 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00002212 SmallVector<bool, 16> WeakIvars;
2213 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002214
Mike Stump11289f42009-09-09 15:08:12 +00002215 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002216 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002217 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2218 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002219 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002220 instanceSize = 0 - (instanceSize - superInstanceSize);
2221 }
David Chisnall18cf7372010-04-19 00:45:34 +00002222
Jordy Rosea91768e2011-07-22 02:08:32 +00002223 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2224 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002225 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002226 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002227 // Get the type encoding for this ivar
2228 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002229 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002230 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002231 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002232 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002233 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002234 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002235 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002236 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002237 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2238 // Create the direct offset value
2239 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2240 IVD->getNameAsString();
2241 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2242 if (OffsetVar) {
2243 OffsetVar->setInitializer(OffsetValue);
2244 // If this is the real definition, change its linkage type so that
2245 // different modules will use this one, rather than their private
2246 // copy.
2247 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2248 } else
2249 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002250 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002251 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002252 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002253 IVD->getNameAsString());
2254 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002255 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002256 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2257 switch (lt) {
2258 case Qualifiers::OCL_Strong:
2259 StrongIvars.push_back(true);
2260 WeakIvars.push_back(false);
2261 break;
2262 case Qualifiers::OCL_Weak:
2263 StrongIvars.push_back(false);
2264 WeakIvars.push_back(true);
2265 break;
2266 default:
2267 StrongIvars.push_back(false);
2268 WeakIvars.push_back(false);
2269 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002270 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002271 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2272 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002273 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002274 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2275 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00002276
Daniel Dunbar92992502008-08-15 22:20:32 +00002277 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002278 SmallVector<Selector, 16> InstanceMethodSels;
2279 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002280 for (const auto *I : OID->instance_methods()) {
2281 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002282 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002283 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002284 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002285 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002286
2287 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2288 InstanceMethodTypes);
2289
Daniel Dunbar92992502008-08-15 22:20:32 +00002290 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002291 SmallVector<Selector, 16> ClassMethodSels;
2292 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002293 for (const auto *I : OID->class_methods()) {
2294 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002295 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002296 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002297 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002298 }
2299 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002300 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00002301 for (const auto *I : ClassDecl->protocols())
2302 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002303
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002304 // Get the superclass pointer.
2305 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002306 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002307 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2308 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002309 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002310 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002311 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002312 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002313 // Generate the method and instance variable lists
2314 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002315 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002316 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002317 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002318 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2319 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002320 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002321 // we emit a symbol containing the offset for each ivar in the class. This
2322 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2323 // for the legacy ABI, without causing problems. The converse is also
2324 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002325
David Chisnall5778fce2009-08-31 16:41:57 +00002326 // Offset pointer for getting at the correct field in the ivar list when
2327 // setting up the alias. These are: The base address for the global, the
2328 // ivar array (second field), the ivar in this list (set for each ivar), and
2329 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002330 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002331 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Craig Topper8a13c412014-05-21 05:09:00 +00002332 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall5778fce2009-08-31 16:41:57 +00002333 llvm::ConstantInt::get(IndexTy, 2) };
2334
Jordy Rosea91768e2011-07-22 02:08:32 +00002335 unsigned ivarIndex = 0;
2336 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2337 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002338 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002339 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002340 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002341 // Get the correct ivar field
2342 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00002343 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2344 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002345 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002346 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2347 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002348 offset->setInitializer(offsetValue);
2349 // If this is the real definition, change its linkage type so that
2350 // different modules will use this one, rather than their private
2351 // copy.
2352 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002353 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002354 // Add a new alias if there isn't one already.
2355 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2356 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2357 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002358 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002359 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002360 }
David Chisnalle89ac062011-10-25 10:12:21 +00002361 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002362
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002363 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002364 llvm::Constant *MetaClassStruct = GenerateClassStructure(
2365 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2366 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2367 NULLPtr, ZeroPtr, ZeroPtr, true);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002368 if (CGM.getTriple().isOSBinFormatCOFF()) {
2369 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2370 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2371 Storage = llvm::GlobalValue::DLLImportStorageClass;
2372 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2373 Storage = llvm::GlobalValue::DLLExportStorageClass;
2374 cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2375 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002376
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002377 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002378 llvm::Constant *ClassStruct = GenerateClassStructure(
2379 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2380 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2381 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2382 StrongIvarBitmap, WeakIvarBitmap);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002383 if (CGM.getTriple().isOSBinFormatCOFF()) {
2384 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2385 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2386 Storage = llvm::GlobalValue::DLLImportStorageClass;
2387 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2388 Storage = llvm::GlobalValue::DLLExportStorageClass;
2389 cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2390 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002391
2392 // Resolve the class aliases, if they exist.
2393 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002394 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002395 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002396 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002397 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002398 }
2399 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002400 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002401 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002402 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002403 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002404 }
2405
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002406 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002407 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002408 Classes.push_back(ClassStruct);
2409}
2410
Mike Stump11289f42009-09-09 15:08:12 +00002411llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002412 // Only emit an ObjC load function if no Objective-C stuff has been called
2413 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002414 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00002415 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00002416
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002417 // Add all referenced protocols to a category.
2418 GenerateProtocolHolderCategory();
2419
Chris Lattner2192fe52011-07-18 04:24:23 +00002420 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002421 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002422 llvm::Type *SelStructPtrTy = SelectorTy;
Craig Topper8a13c412014-05-21 05:09:00 +00002423 if (!SelStructTy) {
2424 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002425 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002426 }
2427
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002428 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002429 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002430 // Generate statics list:
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00002431 if (!ConstantStrings.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002432 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002433 ConstantStrings.size() + 1);
2434 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002435
David Blaikiebbafb8a2012-03-11 07:00:24 +00002436 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002437
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002438 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002439
David Chisnall5778fce2009-08-31 16:41:57 +00002440 Elements.push_back(MakeConstantString(StringClass,
John McCall6c9f1fdb2016-11-19 08:17:24 +00002441 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002442 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
John McCall6c9f1fdb2016-11-19 08:17:24 +00002443 ConstantStrings));
2444 Statics = MakeGlobal(llvm::ConstantStruct::getAnon(Elements),
2445 CGM.getPointerAlign(), ".objc_statics");
2446 llvm::Type *StaticsListPtrTy = Statics->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002447 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002448 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002449 Elements.clear();
2450 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002451 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002452 Statics = MakeGlobal(llvm::ConstantArray::get(StaticsListArrayTy, Elements),
John McCall7f416cc2015-09-08 08:05:57 +00002453 CGM.getPointerAlign(), ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002454 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002455 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002456 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002457 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002458 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002459 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002460 llvm::Type::getInt16Ty(VMContext),
2461 llvm::Type::getInt16Ty(VMContext),
Craig Topper8a13c412014-05-21 05:09:00 +00002462 ClassListTy, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002463
2464 Elements.clear();
2465 // Pointer to an array of selectors used in this module.
John McCall23c9dc62016-11-28 22:18:27 +00002466 ConstantInitBuilder SelectorBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002467 auto Selectors = SelectorBuilder.beginArray(SelStructTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002468 std::vector<llvm::GlobalAlias*> SelectorAliases;
2469 for (SelectorMap::iterator iter = SelectorTable.begin(),
2470 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2471
2472 std::string SelNameStr = iter->first.getAsString();
2473 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2474
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002475 SmallVectorImpl<TypedSelector> &Types = iter->second;
2476 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002477 e = Types.end() ; i!=e ; i++) {
2478
2479 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2480 if (!i->first.empty())
2481 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2482
John McCall6c9f1fdb2016-11-19 08:17:24 +00002483 auto SelStruct = Selectors.beginStruct(SelStructTy);
2484 SelStruct.add(SelName);
2485 SelStruct.add(SelectorTypeEncoding);
John McCallf1788632016-11-28 22:18:30 +00002486 SelStruct.finishAndAddTo(Selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00002487
2488 // Store the selector alias for later replacement
2489 SelectorAliases.push_back(i->second);
2490 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002491 }
David Chisnalld7972f52011-03-23 16:36:54 +00002492 unsigned SelectorCount = Selectors.size();
2493 // NULL-terminate the selector list. This should not actually be required,
2494 // because the selector list has a length field. Unfortunately, the GCC
2495 // runtime decides to ignore the length field and expects a NULL terminator,
2496 // and GCC cooperates with this by always setting the length to 0.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002497 {
2498 auto SelStruct = Selectors.beginStruct(SelStructTy);
2499 SelStruct.add(NULLPtr);
2500 SelStruct.add(NULLPtr);
John McCallf1788632016-11-28 22:18:30 +00002501 SelStruct.finishAndAddTo(Selectors);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002502 }
David Chisnalld7972f52011-03-23 16:36:54 +00002503
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002504 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002505 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
David Blaikiee3b172a2015-04-02 18:55:21 +00002506 llvm::GlobalVariable *SelectorList =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002507 Selectors.finishAndCreateGlobal(".objc_selector_list",
2508 CGM.getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00002509 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002510 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002511
2512 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002513 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2514
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002515 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002516 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002517 // FIXME: We're generating redundant loads and stores here!
David Blaikiee3b172a2015-04-02 18:55:21 +00002518 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(
2519 SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002520 // If selectors are defined as an opaque type, cast the pointer to this
2521 // type.
David Chisnall76803412011-03-23 22:52:06 +00002522 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002523 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2524 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002525 }
David Chisnalld7972f52011-03-23 16:36:54 +00002526
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002527 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002528 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002529 Classes.size()));
2530 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002531 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002532 Categories.size()));
2533 // Create an array of classes, then categories, then static object instances
2534 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2535 // NULL-terminated list of static object instances (mainly constant strings)
2536 Classes.push_back(Statics);
2537 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002538 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002539 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002540 // Construct the symbol table
John McCall7f416cc2015-09-08 08:05:57 +00002541 llvm::Constant *SymTab =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002542 MakeGlobal(llvm::ConstantStruct::get(SymTabTy, Elements),
2543 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002544
2545 // The symbol table is contained in a module which has some version-checking
2546 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002547 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002548 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
Craig Topper8a13c412014-05-21 05:09:00 +00002549 (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002550 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002551 // Runtime version, used for ABI compatibility checking.
2552 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002553 // sizeof(ModuleTy)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002554 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002555 Elements.push_back(
2556 llvm::ConstantInt::get(LongTy,
2557 td.getTypeSizeInBits(ModuleTy) /
2558 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002559
2560 // The path to the source file where this module was declared
2561 SourceManager &SM = CGM.getContext().getSourceManager();
2562 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2563 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00002564 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
David Chisnalld7972f52011-03-23 16:36:54 +00002565 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002566 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002567
David Chisnalla918b882011-07-07 11:22:31 +00002568 if (RuntimeVersion >= 10)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002569 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002570 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002571 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002572 break;
David Chisnalla918b882011-07-07 11:22:31 +00002573 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002574 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002575 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2576 else
2577 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2578 break;
2579 case LangOptions::HybridGC:
2580 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2581 break;
2582 }
David Chisnall5c511772011-05-22 22:37:08 +00002583
John McCall6c9f1fdb2016-11-19 08:17:24 +00002584 llvm::Value *Module =
2585 MakeGlobal(llvm::ConstantStruct::get(ModuleTy, Elements),
2586 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002587
2588 // Create the load function calling the runtime entry point with the module
2589 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002590 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002591 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002592 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2593 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002594 llvm::BasicBlock *EntryBB =
2595 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00002596 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002597 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002598
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002599 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002600 llvm::FunctionType::get(Builder.getVoidTy(),
2601 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002602 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002603 Builder.CreateCall(Register, Module);
David Chisnall92d436b2012-01-31 18:59:20 +00002604
David Chisnallaf066bbb2012-02-01 19:16:56 +00002605 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002606 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2607 llvm::FunctionType *RegisterAliasTy =
2608 llvm::FunctionType::get(Builder.getVoidTy(),
2609 ArgTypes, false);
2610 llvm::Function *RegisterAlias = llvm::Function::Create(
2611 RegisterAliasTy,
2612 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2613 &TheModule);
2614 llvm::BasicBlock *AliasBB =
2615 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2616 llvm::BasicBlock *NoAliasBB =
2617 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2618
2619 // Branch based on whether the runtime provided class_registerAlias_np()
2620 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2621 llvm::Constant::getNullValue(RegisterAlias->getType()));
2622 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2623
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002624 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002625 Builder.SetInsertPoint(AliasBB);
2626 // Emit alias registration calls:
2627 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2628 iter != ClassAliases.end(); ++iter) {
2629 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002630 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00002631 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00002632 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002633 Builder.CreateCall(RegisterAlias,
2634 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00002635 }
2636 }
2637 // Jump to end:
2638 Builder.CreateBr(NoAliasBB);
2639
2640 // Missing alias registration function, just return from the function:
2641 Builder.SetInsertPoint(NoAliasBB);
2642 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002643 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002644
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002645 return LoadFunction;
2646}
Daniel Dunbar92992502008-08-15 22:20:32 +00002647
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002648llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002649 const ObjCContainerDecl *CD) {
2650 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002651 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002652 StringRef CategoryName = OCD ? OCD->getName() : "";
2653 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002654 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002655 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002656
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002657 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002658 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002659 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002660 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2661 MethodName, isClassMethod);
2662
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002663 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002664 = llvm::Function::Create(MethodTy,
2665 llvm::GlobalValue::InternalLinkage,
2666 FunctionName,
2667 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002668 return Method;
2669}
2670
David Chisnall3fe89562011-05-23 22:33:28 +00002671llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002672 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002673}
2674
David Chisnall3fe89562011-05-23 22:33:28 +00002675llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002676 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002677}
2678
Ted Kremeneke65b0862012-03-06 20:05:56 +00002679llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2680 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00002681 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002682}
2683
David Chisnall3fe89562011-05-23 22:33:28 +00002684llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002685 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002686}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002687
David Chisnall3fe89562011-05-23 22:33:28 +00002688llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002689 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002690}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002691
David Chisnall0d75e062012-12-17 18:54:24 +00002692llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002693 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00002694}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002695
David Chisnall0d75e062012-12-17 18:54:24 +00002696llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002697 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002698}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002699
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002700llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002701 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002702}
2703
David Chisnalld7972f52011-03-23 16:36:54 +00002704void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002705 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002706 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002707}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002708
David Chisnall3a509cd2009-12-24 02:26:34 +00002709
David Chisnalld7972f52011-03-23 16:36:54 +00002710void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002711 const ObjCAtTryStmt &S) {
2712 // Unlike the Apple non-fragile runtimes, which also uses
2713 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2714 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002715 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002716 // the personality function; this avoids the need for bracketing
2717 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2718 // (or even _Unwind_DeleteException), but probably doesn't
2719 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002720 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002721 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002722 // exception handler.
2723 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002724}
2725
David Chisnalld7972f52011-03-23 16:36:54 +00002726void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002727 const ObjCAtThrowStmt &S,
2728 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002729 llvm::Value *ExceptionAsObject;
2730
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002731 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002732 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002733 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002734 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002735 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002736 "Unexpected rethrow outside @catch block.");
2737 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2738 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002739 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002740 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002741 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002742 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002743 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002744 if (ClearInsertionPoint)
2745 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002746}
2747
David Chisnalld7972f52011-03-23 16:36:54 +00002748llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002749 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002750 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002751 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002752 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2753 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002754}
2755
David Chisnalld7972f52011-03-23 16:36:54 +00002756void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002757 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002758 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002759 src = EnforceType(B, src, IdTy);
2760 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002761 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2762 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002763}
2764
David Chisnalld7972f52011-03-23 16:36:54 +00002765void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002766 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002767 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002768 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002769 src = EnforceType(B, src, IdTy);
2770 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002771 // FIXME. Add threadloca assign API
2772 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00002773 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2774 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002775}
2776
David Chisnalld7972f52011-03-23 16:36:54 +00002777void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002778 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002779 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002780 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002781 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002782 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002783 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2784 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002785}
2786
David Chisnalld7972f52011-03-23 16:36:54 +00002787void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002788 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002789 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002790 src = EnforceType(B, src, IdTy);
2791 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002792 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2793 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002794}
2795
David Chisnalld7972f52011-03-23 16:36:54 +00002796void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002797 Address DestPtr,
2798 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002799 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002800 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002801 DestPtr = EnforceType(B, DestPtr, PtrTy);
2802 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002803
John McCall7f416cc2015-09-08 08:05:57 +00002804 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2805 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002806}
2807
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002808llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2809 const ObjCInterfaceDecl *ID,
2810 const ObjCIvarDecl *Ivar) {
2811 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2812 + '.' + Ivar->getNameAsString();
2813 // Emit the variable and initialize it with what we think the correct value
2814 // is. This allows code compiled with non-fragile ivars to work correctly
2815 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002816 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2817 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002818 // This will cause a run-time crash if we accidentally use it. A value of
2819 // 0 would seem more sensible, but will silently overwrite the isa pointer
2820 // causing a great deal of confusion.
2821 uint64_t Offset = -1;
2822 // We can't call ComputeIvarBaseOffset() here if we have the
2823 // implementation, because it will create an invalid ASTRecordLayout object
2824 // that we are then stuck with forever, so we only initialize the ivar
2825 // offset variable with a guess if we only have the interface. The
2826 // initializer will be reset later anyway, when we are generating the class
2827 // description.
2828 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002829 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002830 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002831
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002832 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002833 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002834 // Don't emit the guess in non-PIC code because the linker will not be able
2835 // to replace it with the real version for a library. In non-PIC code you
2836 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002837 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002838 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002839 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002840 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002841 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2842 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2843 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2844 IvarOffsetGV, Name);
2845 } else {
2846 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002847 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002848 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002849 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002850 }
David Chisnall5778fce2009-08-31 16:41:57 +00002851 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002852}
2853
David Chisnalld7972f52011-03-23 16:36:54 +00002854LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002855 QualType ObjectTy,
2856 llvm::Value *BaseValue,
2857 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002858 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002859 const ObjCInterfaceDecl *ID =
2860 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002861 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2862 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002863}
Mike Stumpdd93a192009-07-31 21:31:32 +00002864
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002865static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2866 const ObjCInterfaceDecl *OID,
2867 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002868 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2869 next = next->getNextIvar()) {
2870 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002871 return OID;
2872 }
Mike Stump11289f42009-09-09 15:08:12 +00002873
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002874 // Otherwise check in the super class.
2875 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2876 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002877
Craig Topper8a13c412014-05-21 05:09:00 +00002878 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002879}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002880
David Chisnalld7972f52011-03-23 16:36:54 +00002881llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002882 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002883 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002884 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002885 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002886
2887 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2888 // and ExternalLinkage, so create a reference to the ivar global and rely on
2889 // the definition being created as part of GenerateClass.
2890 if (RuntimeVersion < 10 ||
2891 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00002892 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00002893 CGF.Builder.CreateAlignedLoad(
2894 Int32Ty, CGF.Builder.CreateAlignedLoad(
2895 ObjCIvarOffsetVariable(Interface, Ivar),
2896 CGF.getPointerAlign(), "ivar"),
2897 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00002898 PtrDiffTy);
2899 std::string name = "__objc_ivar_offset_value_" +
2900 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00002901 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00002902 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00002903 if (!Offset) {
2904 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002905 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2906 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00002907 GV->setAlignment(Align.getQuantity());
2908 Offset = GV;
2909 }
2910 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00002911 if (Offset->getType() != PtrDiffTy)
2912 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2913 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002914 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002915 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2916 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002917}
2918
David Chisnalld7972f52011-03-23 16:36:54 +00002919CGObjCRuntime *
2920clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002921 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002922 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002923 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002924
David Chisnallb601c962012-07-03 20:49:52 +00002925 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002926 return new CGObjCGCC(CGM);
2927
John McCall775086e2012-07-12 02:07:58 +00002928 case ObjCRuntime::ObjFW:
2929 return new CGObjCObjFW(CGM);
2930
John McCall5fb5df92012-06-20 06:18:46 +00002931 case ObjCRuntime::FragileMacOSX:
2932 case ObjCRuntime::MacOSX:
2933 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00002934 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00002935 llvm_unreachable("these runtimes are not GNU runtimes");
2936 }
2937 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002938}