blob: 0699ef41a16a8884f4e621359ab071b9b1b3eded [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"
Chris Lattner87ab27d2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000026#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000028#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000029#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000030#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000036#include <cstdarg>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000037
38
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 +000042
Chris Lattnerb7256cd2008-03-01 08:50:34 +000043namespace {
David Chisnall34d00052011-03-26 11:48:37 +000044/// Class that lazily initialises the runtime function. Avoids inserting the
45/// types and the function declaration into a module if they're not used, and
46/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000047class LazyRuntimeFunction {
48 CodeGenModule *CGM;
Chris Lattnera5f58b02011-07-09 17:41:47 +000049 std::vector<llvm::Type*> ArgTys;
David Chisnalld7972f52011-03-23 16:36:54 +000050 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000051 llvm::Constant *Function;
David Chisnalld7972f52011-03-23 16:36:54 +000052 public:
David Chisnall34d00052011-03-26 11:48:37 +000053 /// 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.
Craig Topper8a13c412014-05-21 05:09:00 +000056 LazyRuntimeFunction()
57 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000058
David Chisnall34d00052011-03-26 11:48:37 +000059 /// Initialises the lazy function with the name, return type, and the types
60 /// of the arguments.
Reid Kleckner8cd00792014-11-04 01:13:43 +000061 LLVM_END_WITH_NULL
David Chisnalld7972f52011-03-23 16:36:54 +000062 void init(CodeGenModule *Mod, const char *name,
Chris Lattnera5f58b02011-07-09 17:41:47 +000063 llvm::Type *RetTy, ...) {
David Chisnalld7972f52011-03-23 16:36:54 +000064 CGM =Mod;
65 FunctionName = name;
Craig Topper8a13c412014-05-21 05:09:00 +000066 Function = nullptr;
David Chisnalld3858d62011-03-25 11:57:33 +000067 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000068 va_list Args;
69 va_start(Args, RetTy);
Chris Lattnera5f58b02011-07-09 17:41:47 +000070 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnalld7972f52011-03-23 16:36:54 +000071 ArgTys.push_back(ArgTy);
72 va_end(Args);
73 // Push the return type on at the end so we can pop it off easily
74 ArgTys.push_back(RetTy);
75 }
David Chisnall34d00052011-03-26 11:48:37 +000076 /// Overloaded cast operator, allows the class to be implicitly cast to an
77 /// LLVM constant.
David Chisnall3fe89562011-05-23 22:33:28 +000078 operator llvm::Constant*() {
David Chisnalld7972f52011-03-23 16:36:54 +000079 if (!Function) {
Craig Topper8a13c412014-05-21 05:09:00 +000080 if (!FunctionName) return nullptr;
David Chisnalld3858d62011-03-25 11:57:33 +000081 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2192fe52011-07-18 04:24:23 +000082 llvm::Type *RetTy = ArgTys.back();
David Chisnalld7972f52011-03-23 16:36:54 +000083 ArgTys.pop_back();
84 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
85 Function =
David Chisnall3fe89562011-05-23 22:33:28 +000086 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000087 // We won't need to use the types again, so we may as well clean up the
88 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +000089 ArgTys.resize(0);
90 }
91 return Function;
92 }
David Chisnall3fe89562011-05-23 22:33:28 +000093 operator llvm::Function*() {
David Chisnallb85775c2011-05-23 23:15:11 +000094 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall3fe89562011-05-23 22:33:28 +000095 }
David Chisnallb85775c2011-05-23 23:15:11 +000096
David Chisnalld7972f52011-03-23 16:36:54 +000097};
98
99
David Chisnall34d00052011-03-26 11:48:37 +0000100/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000101/// Objective-C support that are specific to the GNU family of runtimes (GCC,
102/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000103class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000104protected:
David Chisnall34d00052011-03-26 11:48:37 +0000105 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000106 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// strut objc_super. Used for sending messages to super. This structure
108 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000109 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000110 /// struct objc_super*. The type of the argument to the superclass message
111 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000112 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000113 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
114 /// SEL is included in a header somewhere, in which case it will be whatever
115 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000116 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000117 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
118 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000119 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000120 /// Pointer to i8 - LLVM type of char*, for all of the places where the
121 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// Instance Method Pointer type. This is a pointer to a function that takes,
124 /// at a minimum, an object and a selector, and is the generic type for
125 /// Objective-C methods. Due to differences between variadic / non-variadic
126 /// calling conventions, it must always be cast to the correct type before
127 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000128 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000129 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
130 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
131 /// but if the runtime header declaring it is included then it may be a
132 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000133 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000134 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
135 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000136 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000137 /// The clang type of id. Used when using the clang CGCall infrastructure to
138 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000139 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000141 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000142 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
143 /// used in the code to document the difference between i8* meaning a pointer
144 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000145 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000146 /// LLVM type for C long type. The runtime uses this in a lot of places where
147 /// it should be using intptr_t, but we can't fix this without breaking
148 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000149 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000150 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000151 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000152 /// LLVM type for C intptr_t.
153 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000154 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000155 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
157 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000158 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000159 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000160 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000161 /// 32-bit integer type, to save us needing to look it up every time it's used.
162 llvm::IntegerType *Int32Ty;
163 /// 64-bit integer type, to save us needing to look it up every time it's used.
164 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000165 /// Metadata kind used to tie method lookups to message sends. The GNUstep
166 /// runtime provides some LLVM passes that can use this to do things like
167 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000168 unsigned msgSendMDKind;
David Chisnall34d00052011-03-26 11:48:37 +0000169 /// Helper function that generates a constant string and returns a pointer to
170 /// the start of the string. The result of this function can be used anywhere
171 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000172 llvm::Constant *MakeConstantString(const std::string &Str,
173 const std::string &Name="") {
David Blaikiee3b172a2015-04-02 18:55:21 +0000174 auto *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
175 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
176 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000177 }
David Chisnall34d00052011-03-26 11:48:37 +0000178 /// Emits a linkonce_odr string, whose name is the prefix followed by the
179 /// string value. This allows the linker to combine the strings between
180 /// different modules. Used for EH typeinfo names, selector strings, and a
181 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000182 llvm::Constant *ExportUniqueString(const std::string &Str,
183 const std::string prefix) {
184 std::string name = prefix + Str;
David Blaikiee3b172a2015-04-02 18:55:21 +0000185 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000186 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000187 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnalld3858d62011-03-25 11:57:33 +0000188 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
189 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
190 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000191 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
192 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000193 }
David Chisnall34d00052011-03-26 11:48:37 +0000194 /// Generates a global structure, initialized by the elements in the vector.
195 /// The element types must match the types of the structure elements in the
196 /// first argument.
Chris Lattner2192fe52011-07-18 04:24:23 +0000197 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000198 ArrayRef<llvm::Constant *> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000199 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000200 llvm::GlobalValue::LinkageTypes linkage
201 =llvm::GlobalValue::InternalLinkage) {
202 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
203 return new llvm::GlobalVariable(TheModule, Ty, false,
204 linkage, C, Name);
205 }
David Chisnall34d00052011-03-26 11:48:37 +0000206 /// Generates a global array. The vector must contain the same number of
207 /// elements that the array type declares, of the type specified as the array
208 /// element type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000209 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000210 ArrayRef<llvm::Constant *> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000211 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000212 llvm::GlobalValue::LinkageTypes linkage
213 =llvm::GlobalValue::InternalLinkage) {
214 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
215 return new llvm::GlobalVariable(TheModule, Ty, false,
216 linkage, C, Name);
217 }
David Chisnall34d00052011-03-26 11:48:37 +0000218 /// Generates a global array, inferring the array type from the specified
219 /// element type and the size of the initialiser.
Chris Lattner2192fe52011-07-18 04:24:23 +0000220 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000221 ArrayRef<llvm::Constant *> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000222 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000223 llvm::GlobalValue::LinkageTypes linkage
224 =llvm::GlobalValue::InternalLinkage) {
225 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
226 return MakeGlobal(ArrayTy, V, Name, linkage);
227 }
David Chisnalla5f59412012-10-16 15:11:55 +0000228 /// Returns a property name and encoding string.
229 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
230 const Decl *Container) {
David Chisnallbeb80132013-02-28 13:59:29 +0000231 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnalla5f59412012-10-16 15:11:55 +0000232 if ((R.getKind() == ObjCRuntime::GNUstep) &&
233 (R.getVersion() >= VersionTuple(1, 6))) {
234 std::string NameAndAttributes;
235 std::string TypeStr;
236 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
237 NameAndAttributes += '\0';
238 NameAndAttributes += TypeStr.length() + 3;
239 NameAndAttributes += TypeStr;
240 NameAndAttributes += '\0';
241 NameAndAttributes += PD->getNameAsString();
David Blaikiee3b172a2015-04-02 18:55:21 +0000242 auto *ConstStr = CGM.GetAddrOfConstantCString(NameAndAttributes);
243 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
244 ConstStr, Zeros);
David Chisnalla5f59412012-10-16 15:11:55 +0000245 }
246 return MakeConstantString(PD->getNameAsString());
247 }
David Chisnallbeb80132013-02-28 13:59:29 +0000248 /// Push the property attributes into two structure fields.
249 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
250 ObjCPropertyDecl *property, bool isSynthesized=true, bool
251 isDynamic=true) {
252 int attrs = property->getPropertyAttributes();
253 // For read-only properties, clear the copy and retain flags
254 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
256 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
257 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
259 }
260 // The first flags field has the same attribute values as clang uses internally
261 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
262 attrs >>= 8;
263 attrs <<= 2;
264 // For protocol properties, synthesized and dynamic have no meaning, so we
265 // reuse these flags to indicate that this is a protocol property (both set
266 // has no meaning, as a property can't be both synthesized and dynamic)
267 attrs |= isSynthesized ? (1<<0) : 0;
268 attrs |= isDynamic ? (1<<1) : 0;
269 // The second field is the next four fields left shifted by two, with the
270 // low bit set to indicate whether the field is synthesized or dynamic.
271 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
272 // Two padding fields
273 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
274 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
275 }
David Chisnall34d00052011-03-26 11:48:37 +0000276 /// Ensures that the value has the required type, by inserting a bitcast if
277 /// required. This function lets us avoid inserting bitcasts that are
278 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000279 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000280 if (V->getType() == Ty) return V;
281 return B.CreateBitCast(V, Ty);
282 }
283 // Some zeros used for GEPs in lots of places.
284 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000285 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000286 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000287 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000288 llvm::LLVMContext &VMContext;
289private:
David Chisnall34d00052011-03-26 11:48:37 +0000290 /// Placeholder for the class. Lots of things refer to the class before we've
291 /// actually emitted it. We use this alias as a placeholder, and then replace
292 /// it with a pointer to the class structure before finally emitting the
293 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000294 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000295 /// Placeholder for the metaclass. Lots of things refer to the class before
296 /// we've / actually emitted it. We use this alias as a placeholder, and then
297 /// replace / it with a pointer to the metaclass structure before finally
298 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000299 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000300 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000301 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000302 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000303 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000304 /// All of the Objective-C constant strings that have been generated for this
305 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000306 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000307 /// Map from string values to Objective-C constant strings in the output.
308 /// Used to prevent emitting Objective-C strings more than once. This should
309 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000310 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000311 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000312 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000313 /// For each variant of a selector, we store the type encoding and a
314 /// placeholder value. For an untyped selector, the type will be the empty
315 /// string. Selector references are all done via the module's selector table,
316 /// so we create an alias as a placeholder and then replace it with the real
317 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000318 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000319 /// Type of the selector map. This is roughly equivalent to the structure
320 /// used in the GNUstep runtime, which maintains a list of all of the valid
321 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000322 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000323 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000324 /// A map from selectors to selector types. This allows us to emit all
325 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000326 SelectorMap SelectorTable;
327
David Chisnall34d00052011-03-26 11:48:37 +0000328 /// Selectors related to memory management. When compiling in GC mode, we
329 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000330 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000331 /// Runtime functions used for memory management in GC mode. Note that clang
332 /// supports code generation for calling these functions, but neither GNU
333 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000334 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
335 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000336
David Chisnall92d436b2012-01-31 18:59:20 +0000337 typedef std::pair<std::string, std::string> ClassAliasPair;
338 /// All classes that have aliases set for them.
339 std::vector<ClassAliasPair> ClassAliases;
340
David Chisnalld3858d62011-03-25 11:57:33 +0000341protected:
David Chisnall34d00052011-03-26 11:48:37 +0000342 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000343 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000344 /// Function used for rethrowing exceptions, used at the end of \@finally or
345 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000346 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Function called when entering a catch function. This is required for
348 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000349 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000350 /// Function called when exiting from a catch block. Used to do exception
351 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000352 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000353 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000354 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000355 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000356 LazyRuntimeFunction SyncExitFn;
357
David Chisnalld3858d62011-03-25 11:57:33 +0000358private:
359
David Chisnall34d00052011-03-26 11:48:37 +0000360 /// Function called if fast enumeration detects that the collection is
361 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000362 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000363 /// Function for implementing synthesized property getters that return an
364 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000365 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000366 /// Function for implementing synthesized property setters that return an
367 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000368 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000369 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000370 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000371 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000372 LazyRuntimeFunction SetStructPropertyFn;
373
David Chisnall34d00052011-03-26 11:48:37 +0000374 /// The version of the runtime that this class targets. Must match the
375 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000376 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000377 /// The version of the protocol class. Used to differentiate between ObjC1
378 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
379 /// components and can not contain declared properties. We always emit
380 /// Objective-C 2 property structures, but we have to pretend that they're
381 /// Objective-C 1 property structures when targeting the GCC runtime or it
382 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000383 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000384private:
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// Generates an instance variable list structure. This is a structure
386 /// containing a size and an array of structures containing instance variable
387 /// metadata. This is used purely for introspection in the fragile ABI. In
388 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000389 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
390 ArrayRef<llvm::Constant *> IvarTypes,
391 ArrayRef<llvm::Constant *> IvarOffsets);
David Chisnall34d00052011-03-26 11:48:37 +0000392 /// Generates a method list structure. This is a structure containing a size
393 /// and an array of structures containing method metadata.
394 ///
395 /// This structure is used by both classes and categories, and contains a next
396 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000397 llvm::Constant *GenerateMethodList(StringRef ClassName,
398 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000399 ArrayRef<Selector> MethodSels,
400 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000401 bool isClassMethodList);
James Dennettb9199ee2012-06-13 22:07:09 +0000402 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000403 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
404 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000405 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-03-26 11:48:37 +0000406 /// Generates a list of property metadata structures. This follows the same
407 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000408 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000409 SmallVectorImpl<Selector> &InstanceMethodSels,
410 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000411 /// Generates a list of referenced protocols. Classes, categories, and
412 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000413 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
David Chisnall34d00052011-03-26 11:48:37 +0000414 /// To ensure that all protocols are seen by the runtime, we add a category on
415 /// a class defined in the runtime, declaring no methods, but adopting the
416 /// protocols. This is a horribly ugly hack, but it allows us to collect all
417 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000418 void GenerateProtocolHolderCategory();
David Chisnall34d00052011-03-26 11:48:37 +0000419 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000420 llvm::Constant *GenerateClassStructure(
421 llvm::Constant *MetaClass,
422 llvm::Constant *SuperClass,
423 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000424 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000425 llvm::Constant *Version,
426 llvm::Constant *InstanceSize,
427 llvm::Constant *IVars,
428 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000429 llvm::Constant *Protocols,
430 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000431 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000432 llvm::Constant *StrongIvarBitmap,
433 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000434 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000435 /// Generates a method list. This is used by protocols to define the required
436 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000437 llvm::Constant *GenerateProtocolMethodList(
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000438 ArrayRef<llvm::Constant *> MethodNames,
439 ArrayRef<llvm::Constant *> MethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000440 /// Returns a selector with the specified type encoding. An empty string is
441 /// used to return an untyped selector (with the types field set to NULL).
John McCall882987f2013-02-28 19:01:20 +0000442 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000443 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000444 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000445 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
446 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000447 /// Emits a reference to a class. This allows the linker to object if there
448 /// is no class of the matching name.
John McCall775086e2012-07-12 02:07:58 +0000449protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000450 void EmitClassRef(const std::string &className);
David Chisnall920e83b2011-06-29 13:16:41 +0000451 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000452 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000453 const std::string &Name, bool isWeak);
David Chisnall34d00052011-03-26 11:48:37 +0000454 /// Looks up the method for sending a message to the specified object. This
455 /// mechanism differs between the GCC and GNU runtimes, so this method must be
456 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000457 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
458 llvm::Value *&Receiver,
459 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000460 llvm::MDNode *node,
461 MessageSendInfo &MSI) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000462 /// Looks up the method for sending a message to a superclass. This
463 /// mechanism differs between the GCC and GNU runtimes, so this method must
464 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000465 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
466 llvm::Value *ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000467 llvm::Value *cmd,
468 MessageSendInfo &MSI) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000469 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
470 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
471 /// bits set to their values, LSB first, while larger ones are stored in a
472 /// structure of this / form:
473 ///
474 /// struct { int32_t length; int32_t values[length]; };
475 ///
476 /// The values in the array are stored in host-endian format, with the least
477 /// significant bit being assumed to come first in the bitfield. Therefore,
478 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
479 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000480 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000481public:
David Chisnalld7972f52011-03-23 16:36:54 +0000482 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
483 unsigned protocolClassVersion);
484
Craig Topper4f12f102014-03-12 06:41:41 +0000485 llvm::Constant *GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000486
Craig Topper4f12f102014-03-12 06:41:41 +0000487 RValue
488 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
489 QualType ResultType, Selector Sel,
490 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000491 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000492 const ObjCMethodDecl *Method) override;
493 RValue
494 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
495 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000496 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000497 bool isCategoryImpl, llvm::Value *Receiver,
498 bool IsClassMessage, const CallArgList &CallArgs,
499 const ObjCMethodDecl *Method) override;
500 llvm::Value *GetClass(CodeGenFunction &CGF,
501 const ObjCInterfaceDecl *OID) override;
502 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
503 bool lval = false) override;
504 llvm::Value *GetSelector(CodeGenFunction &CGF,
505 const ObjCMethodDecl *Method) override;
506 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Craig Topper4f12f102014-03-12 06:41:41 +0000508 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
509 const ObjCContainerDecl *CD) override;
510 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
511 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
512 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
513 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
514 const ObjCProtocolDecl *PD) override;
515 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
516 llvm::Function *ModuleInitFunction() override;
517 llvm::Constant *GetPropertyGetFunction() override;
518 llvm::Constant *GetPropertySetFunction() override;
519 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
520 bool copy) override;
521 llvm::Constant *GetSetStructFunction() override;
522 llvm::Constant *GetGetStructFunction() override;
523 llvm::Constant *GetCppAtomicObjectGetFunction() override;
524 llvm::Constant *GetCppAtomicObjectSetFunction() override;
525 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Craig Topper4f12f102014-03-12 06:41:41 +0000527 void EmitTryStmt(CodeGenFunction &CGF,
528 const ObjCAtTryStmt &S) override;
529 void EmitSynchronizedStmt(CodeGenFunction &CGF,
530 const ObjCAtSynchronizedStmt &S) override;
531 void EmitThrowStmt(CodeGenFunction &CGF,
532 const ObjCAtThrowStmt &S,
533 bool ClearInsertionPoint=true) override;
534 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
535 llvm::Value *AddrWeakObj) override;
536 void EmitObjCWeakAssign(CodeGenFunction &CGF,
537 llvm::Value *src, llvm::Value *dst) override;
538 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
539 llvm::Value *src, llvm::Value *dest,
540 bool threadlocal=false) override;
541 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
542 llvm::Value *dest, llvm::Value *ivarOffset) override;
543 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
544 llvm::Value *src, llvm::Value *dest) override;
545 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, llvm::Value *DestPtr,
546 llvm::Value *SrcPtr,
547 llvm::Value *Size) override;
548 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
549 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
550 unsigned CVRQualifiers) override;
551 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
552 const ObjCInterfaceDecl *Interface,
553 const ObjCIvarDecl *Ivar) override;
554 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
555 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
556 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000557 return NULLPtr;
558 }
Craig Topper4f12f102014-03-12 06:41:41 +0000559 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
560 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000561 return NULLPtr;
562 }
Craig Topper4f12f102014-03-12 06:41:41 +0000563
564 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000565 return NULLPtr;
566 }
Rafael Espindola554256c2014-02-26 22:25:45 +0000567
568 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
Craig Toppera798a9d2014-03-02 09:32:10 +0000569 bool Weak = false) override {
Craig Topper8a13c412014-05-21 05:09:00 +0000570 return nullptr;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000571 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000572};
David Chisnall34d00052011-03-26 11:48:37 +0000573/// Class representing the legacy GCC Objective-C ABI. This is the default when
574/// -fobjc-nonfragile-abi is not specified.
575///
576/// The GCC ABI target actually generates code that is approximately compatible
577/// with the new GNUstep runtime ABI, but refrains from using any features that
578/// would not work with the GCC runtime. For example, clang always generates
579/// the extended form of the class structure, and the extra fields are simply
580/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000581class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000582 /// The GCC ABI message lookup function. Returns an IMP pointing to the
583 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000584 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000585 /// The GCC ABI superclass message lookup function. Takes a pointer to a
586 /// structure describing the receiver and the class, and a selector as
587 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000588 LazyRuntimeFunction MsgLookupSuperFn;
589protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000590 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
591 llvm::Value *cmd, llvm::MDNode *node,
592 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000593 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000594 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000595 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000596 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000597 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000598 imp->setMetadata(msgSendMDKind, node);
599 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000600 }
Craig Topper4f12f102014-03-12 06:41:41 +0000601 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
602 llvm::Value *cmd, MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000603 CGBuilderTy &Builder = CGF.Builder;
604 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
605 PtrToObjCSuperTy), cmd};
John McCall882987f2013-02-28 19:01:20 +0000606 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000607 }
David Chisnalld7972f52011-03-23 16:36:54 +0000608 public:
David Chisnall76803412011-03-23 22:52:06 +0000609 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
610 // IMP objc_msg_lookup(id, SEL);
Craig Topper8a13c412014-05-21 05:09:00 +0000611 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
612 nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000613 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
614 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000615 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000616 }
David Chisnalld7972f52011-03-23 16:36:54 +0000617};
David Chisnall34d00052011-03-26 11:48:37 +0000618/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000619class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000620 /// The slot lookup function. Returns a pointer to a cacheable structure
621 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000622 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000623 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
624 /// a structure describing the receiver and the class, and a selector as
625 /// arguments. Returns the slot for the corresponding method. Superclass
626 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000627 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000628 /// Specialised function for setting atomic retain properties
629 LazyRuntimeFunction SetPropertyAtomic;
630 /// Specialised function for setting atomic copy properties
631 LazyRuntimeFunction SetPropertyAtomicCopy;
632 /// Specialised function for setting nonatomic retain properties
633 LazyRuntimeFunction SetPropertyNonAtomic;
634 /// Specialised function for setting nonatomic copy properties
635 LazyRuntimeFunction SetPropertyNonAtomicCopy;
636 /// Function to perform atomic copies of C++ objects with nontrivial copy
637 /// constructors from Objective-C ivars.
638 LazyRuntimeFunction CxxAtomicObjectGetFn;
639 /// Function to perform atomic copies of C++ objects with nontrivial copy
640 /// constructors to Objective-C ivars.
641 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000642 /// Type of an slot structure pointer. This is returned by the various
643 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000644 llvm::Type *SlotTy;
John McCallc31d8932012-11-14 09:08:34 +0000645 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000646 llvm::Constant *GetEHType(QualType T) override;
David Chisnall76803412011-03-23 22:52:06 +0000647 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000648 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
649 llvm::Value *cmd, llvm::MDNode *node,
650 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000651 CGBuilderTy &Builder = CGF.Builder;
652 llvm::Function *LookupFn = SlotLookupFn;
653
654 // Store the receiver on the stack so that we can reload it later
655 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
656 Builder.CreateStore(Receiver, ReceiverPtr);
657
658 llvm::Value *self;
659
660 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
661 self = CGF.LoadObjCSelf();
662 } else {
663 self = llvm::ConstantPointerNull::get(IdTy);
664 }
665
666 // The lookup function is guaranteed not to capture the receiver pointer.
667 LookupFn->setDoesNotCapture(1);
668
David Chisnall0cc83e72011-10-28 17:55:06 +0000669 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000670 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
671 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000672 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000673 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000674 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000675 slot->setMetadata(msgSendMDKind, node);
676
677 // Load the imp from the slot
David Blaikie1ed728c2015-04-05 22:45:47 +0000678 llvm::Value *imp = Builder.CreateLoad(
679 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4));
David Chisnall76803412011-03-23 22:52:06 +0000680
681 // The lookup function may have changed the receiver, so make sure we use
682 // the new one.
683 Receiver = Builder.CreateLoad(ReceiverPtr, true);
684 return imp;
685 }
Craig Topper4f12f102014-03-12 06:41:41 +0000686 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
687 llvm::Value *cmd,
688 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000689 CGBuilderTy &Builder = CGF.Builder;
690 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
691
John McCall882987f2013-02-28 19:01:20 +0000692 llvm::CallInst *slot =
693 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000694 slot->setOnlyReadsMemory();
695
David Blaikie1ed728c2015-04-05 22:45:47 +0000696 return Builder.CreateLoad(Builder.CreateStructGEP(nullptr, slot, 4));
David Chisnall76803412011-03-23 22:52:06 +0000697 }
David Chisnalld7972f52011-03-23 16:36:54 +0000698 public:
David Chisnall76803412011-03-23 22:52:06 +0000699 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000700 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000701
Chris Lattner845511f2011-06-18 22:49:11 +0000702 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000703 PtrTy, PtrTy, IntTy, IMPTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000704 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
705 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
706 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000707 SelectorTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000708 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
709 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000710 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000711 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000712 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000713 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000714 // void *__cxa_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000715 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000716 // void __cxa_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000717 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000718 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000719 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000720 PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000721 } else if (R.getVersion() >= VersionTuple(1, 7)) {
722 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
723 // id objc_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000724 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000725 // void objc_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000726 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000727 // void _Unwind_Resume_or_Rethrow(void*)
728 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000729 PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000730 }
David Chisnall0d75e062012-12-17 18:54:24 +0000731 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
732 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000733 SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000734 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000735 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000736 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000737 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000738 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Craig Topper8a13c412014-05-21 05:09:00 +0000739 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000740 // void objc_setCppObjectAtomic(void *dest, const void *src, void
741 // *helper);
742 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000743 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000744 // void objc_getCppObjectAtomic(void *dest, const void *src, void
745 // *helper);
746 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000747 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000748 }
Craig Topper4f12f102014-03-12 06:41:41 +0000749 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000750 // The optimised functions were added in version 1.7 of the GNUstep
751 // runtime.
752 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
753 VersionTuple(1, 7));
754 return CxxAtomicObjectGetFn;
755 }
Craig Topper4f12f102014-03-12 06:41:41 +0000756 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000757 // The optimised functions were added in version 1.7 of the GNUstep
758 // runtime.
759 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
760 VersionTuple(1, 7));
761 return CxxAtomicObjectSetFn;
762 }
Craig Topper4f12f102014-03-12 06:41:41 +0000763 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
764 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000765 // The optimised property functions omit the GC check, and so are not
766 // safe to use in GC mode. The standard functions are fast in GC mode,
767 // so there is less advantage in using them.
768 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
769 // The optimised functions were added in version 1.7 of the GNUstep
770 // runtime.
771 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
772 VersionTuple(1, 7));
773
774 if (atomic) {
775 if (copy) return SetPropertyAtomicCopy;
776 return SetPropertyAtomic;
777 }
David Chisnall0d75e062012-12-17 18:54:24 +0000778
Ted Kremenek090a2732014-03-07 18:53:05 +0000779 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000780 }
David Chisnalld7972f52011-03-23 16:36:54 +0000781};
782
Alp Toker272e9bc2013-11-25 00:40:53 +0000783/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000784class CGObjCObjFW: public CGObjCGNU {
785protected:
786 /// The GCC ABI message lookup function. Returns an IMP pointing to the
787 /// method implementation for this message.
788 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000789 /// stret lookup function. While this does not seem to make sense at the
790 /// first look, this is required to call the correct forwarding function.
791 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000792 /// The GCC ABI superclass message lookup function. Takes a pointer to a
793 /// structure describing the receiver and the class, and a selector as
794 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000795 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000796
Craig Topper4f12f102014-03-12 06:41:41 +0000797 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
798 llvm::Value *cmd, llvm::MDNode *node,
799 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000800 CGBuilderTy &Builder = CGF.Builder;
801 llvm::Value *args[] = {
802 EnforceType(Builder, Receiver, IdTy),
803 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000804
805 llvm::CallSite imp;
806 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
807 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
808 else
809 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
810
John McCall3deb1ad2012-08-21 02:47:43 +0000811 imp->setMetadata(msgSendMDKind, node);
812 return imp.getInstruction();
813 }
814
Craig Topper4f12f102014-03-12 06:41:41 +0000815 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
816 llvm::Value *cmd, MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000817 CGBuilderTy &Builder = CGF.Builder;
818 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
819 PtrToObjCSuperTy), cmd};
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000820
821 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
822 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
823 else
824 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
John McCall3deb1ad2012-08-21 02:47:43 +0000825 }
826
Craig Topper4f12f102014-03-12 06:41:41 +0000827 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
828 const std::string &Name, bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000829 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000830 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000831
832 EmitClassRef(Name);
833
834 std::string SymbolName = "_OBJC_CLASS_" + Name;
835
836 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
837
838 if (!ClassSymbol)
839 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
840 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000841 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000842
843 return ClassSymbol;
844 }
845
846public:
John McCall3deb1ad2012-08-21 02:47:43 +0000847 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
848 // IMP objc_msg_lookup(id, SEL);
Craig Topper8a13c412014-05-21 05:09:00 +0000849 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000850 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000851 SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000852 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
853 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000854 PtrToObjCSuperTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000855 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000856 PtrToObjCSuperTy, SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000857 }
John McCall775086e2012-07-12 02:07:58 +0000858};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000859} // end anonymous namespace
860
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000861
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000862/// Emits a reference to a dummy variable which is emitted with each class.
863/// This ensures that a linker error will be generated when trying to link
864/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000865void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000866 std::string symbolRef = "__objc_class_ref_" + className;
867 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000868 if (TheModule.getGlobalVariable(symbolRef))
869 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000870 std::string symbolName = "__objc_class_name_" + className;
871 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
872 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000873 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +0000874 llvm::GlobalValue::ExternalLinkage,
875 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000876 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000877 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000878 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000879}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000880
Craig Topperbf3e3272014-08-30 16:55:52 +0000881static std::string SymbolNameForMethod( StringRef ClassName,
882 StringRef CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000883 bool isClassMethod) {
884 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000885 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
886 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000887 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000888 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000889}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000890
David Chisnalld7972f52011-03-23 16:36:54 +0000891CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Craig Topper8a13c412014-05-21 05:09:00 +0000892 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000893 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +0000894 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
895 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
896 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000897
898 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
899
David Chisnalld7972f52011-03-23 16:36:54 +0000900 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000901 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000902 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000903 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000904 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000905 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000906 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000907 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000908 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000909 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000910
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000911 Int8Ty = llvm::Type::getInt8Ty(VMContext);
912 // C string type. Used in lots of places.
913 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
914
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000915 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000916 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000917 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000918 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000919 QualType selTy = CGM.getContext().getObjCSelType();
920 if (QualType() == selTy) {
921 SelectorTy = PtrToInt8Ty;
922 } else {
923 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
924 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000925
Owen Anderson9793f0e2009-07-29 22:16:19 +0000926 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000927 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000928
David Chisnallcdd207e2011-10-04 15:35:30 +0000929 Int32Ty = llvm::Type::getInt32Ty(VMContext);
930 Int64Ty = llvm::Type::getInt64Ty(VMContext);
931
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000932 IntPtrTy =
933 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000934
Chris Lattner4bd55962008-03-30 23:03:07 +0000935 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000936 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
937 ASTIdTy = CanQualType();
938 if (UnqualIdTy != QualType()) {
939 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000940 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000941 } else {
942 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000943 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000944 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Craig Topper8a13c412014-05-21 05:09:00 +0000946 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000947 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
948
Chris Lattnera5f58b02011-07-09 17:41:47 +0000949 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000950
951 // void objc_exception_throw(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000952 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
953 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000954 // int objc_sync_enter(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000955 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000956 // int objc_sync_exit(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000957 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000958
959 // void objc_enumerationMutation (id)
960 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000961 IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000962
963 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
964 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000965 PtrDiffTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000966 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
967 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000968 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000969 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
970 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000971 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000972 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
973 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000974 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000975
Chris Lattner4bd55962008-03-30 23:03:07 +0000976 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000977 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000978 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
979 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000980
David Blaikiebbafb8a2012-03-11 07:00:24 +0000981 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +0000982 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000983 RuntimeVersion = 10;
984
David Chisnalld3858d62011-03-25 11:57:33 +0000985 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000986 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000987 // This is a bit of an hack. We should sort this out by having a proper
988 // CGObjCGNUstep subclass for GC, but we may want to really support the old
989 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000990 // Get selectors needed in GC mode
991 RetainSel = GetNullarySelector("retain", CGM.getContext());
992 ReleaseSel = GetNullarySelector("release", CGM.getContext());
993 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
994
995 // Get functions needed in GC mode
996
997 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000998 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000999 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001000 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00001001 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001002 PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001003 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001004 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001005 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001006 // id objc_assign_weak(id, id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001007 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001008 // id objc_read_weak(id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001009 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001010 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001011 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001012 SizeTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001013 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001014}
Mike Stumpdd93a192009-07-31 21:31:32 +00001015
John McCall882987f2013-02-28 19:01:20 +00001016llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
David Chisnall08d67332011-06-30 10:14:37 +00001017 const std::string &Name,
1018 bool isWeak) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001019 llvm::GlobalVariable *ClassNameGV = CGM.GetAddrOfConstantCString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001020 // With the incompatible ABI, this will need to be replaced with a direct
1021 // reference to the class symbol. For the compatible nonfragile ABI we are
1022 // still performing this lookup at run time but emitting the symbol for the
1023 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001024 //
1025 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1026 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001027 if (!isWeak)
1028 EmitClassRef(Name);
David Blaikie1ed728c2015-04-05 22:45:47 +00001029 llvm::Value *ClassName =
1030 CGF.Builder.CreateStructGEP(ClassNameGV->getValueType(), ClassNameGV, 0);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001031
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001032 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001033 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001034 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001035 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001036}
1037
David Chisnall920e83b2011-06-29 13:16:41 +00001038// This has to perform the lookup every time, since posing and related
1039// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001040llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001041 const ObjCInterfaceDecl *OID) {
John McCall882987f2013-02-28 19:01:20 +00001042 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +00001043}
John McCall882987f2013-02-28 19:01:20 +00001044llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1045 return GetClassNamed(CGF, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +00001046}
1047
John McCall882987f2013-02-28 19:01:20 +00001048llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +00001049 const std::string &TypeEncoding, bool lval) {
1050
Craig Topperfa159c12013-07-14 16:47:36 +00001051 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00001052 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00001053
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001054 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001055 e = Types.end() ; i!=e ; i++) {
1056 if (i->first == TypeEncoding) {
1057 SelValue = i->second;
1058 break;
1059 }
1060 }
Craig Topper8a13c412014-05-21 05:09:00 +00001061 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001062 SelValue = llvm::GlobalAlias::create(
David Blaikie881b2342015-04-29 21:22:47 +00001063 SelectorTy, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001064 ".objc_selector_" + Sel.getAsString(), &TheModule);
David Chisnalld7972f52011-03-23 16:36:54 +00001065 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1066 }
1067
David Chisnall76803412011-03-23 22:52:06 +00001068 if (lval) {
John McCall882987f2013-02-28 19:01:20 +00001069 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1070 CGF.Builder.CreateStore(SelValue, tmp);
David Chisnall76803412011-03-23 22:52:06 +00001071 return tmp;
1072 }
1073 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001074}
1075
John McCall882987f2013-02-28 19:01:20 +00001076llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +00001077 bool lval) {
John McCall882987f2013-02-28 19:01:20 +00001078 return GetSelector(CGF, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001079}
1080
John McCall882987f2013-02-28 19:01:20 +00001081llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1082 const ObjCMethodDecl *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001083 std::string SelTypes;
1084 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCall882987f2013-02-28 19:01:20 +00001085 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +00001086}
1087
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001088llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001089 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1090 // With the old ABI, there was only one kind of catchall, which broke
1091 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1092 // a pointer indicating object catchalls, and NULL to indicate real
1093 // catchalls
1094 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1095 return MakeConstantString("@id");
1096 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001097 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00001098 }
David Chisnalld3858d62011-03-25 11:57:33 +00001099 }
John McCallc31d8932012-11-14 09:08:34 +00001100
1101 // All other types should be Objective-C interface pointer types.
1102 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1103 assert(OPT && "Invalid @catch type.");
1104 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1105 assert(IDecl && "Invalid @catch type.");
1106 return MakeConstantString(IDecl->getIdentifier()->getName());
1107}
1108
1109llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1110 if (!CGM.getLangOpts().CPlusPlus)
1111 return CGObjCGNU::GetEHType(T);
1112
David Chisnalle1d2584d2011-03-20 21:35:39 +00001113 // For Objective-C++, we want to provide the ability to catch both C++ and
1114 // Objective-C objects in the same function.
1115
1116 // There's a particular fixed type info for 'id'.
1117 if (T->isObjCIdType() ||
1118 T->isObjCQualifiedIdType()) {
1119 llvm::Constant *IDEHType =
1120 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1121 if (!IDEHType)
1122 IDEHType =
1123 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1124 false,
1125 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001126 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00001127 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1128 }
1129
1130 const ObjCObjectPointerType *PT =
1131 T->getAs<ObjCObjectPointerType>();
1132 assert(PT && "Invalid @catch type.");
1133 const ObjCInterfaceType *IT = PT->getInterfaceType();
1134 assert(IT && "Invalid @catch type.");
1135 std::string className = IT->getDecl()->getIdentifier()->getName();
1136
1137 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1138
1139 // Return the existing typeinfo if it exists
1140 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001141 if (typeinfo)
1142 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001143
1144 // Otherwise create it.
1145
1146 // vtable for gnustep::libobjc::__objc_class_type_info
1147 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1148 // platform's name mangling.
1149 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00001150 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001151 if (!Vtable) {
1152 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00001153 llvm::GlobalValue::ExternalLinkage,
1154 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001155 }
1156 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00001157 auto *BVtable = llvm::ConstantExpr::getBitCast(
1158 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1159 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001160
1161 llvm::Constant *typeName =
1162 ExportUniqueString(className, "__objc_eh_typename_");
1163
1164 std::vector<llvm::Constant*> fields;
David Blaikiee3b172a2015-04-02 18:55:21 +00001165 fields.push_back(BVtable);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001166 fields.push_back(typeName);
1167 llvm::Constant *TI =
Chris Lattner845511f2011-06-18 22:49:11 +00001168 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00001169 nullptr), fields, "__objc_eh_typeinfo_" + className,
David Chisnalle1d2584d2011-03-20 21:35:39 +00001170 llvm::GlobalValue::LinkOnceODRLinkage);
1171 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001172}
1173
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001174/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +00001175llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001176
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001177 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +00001178
David Chisnall358e7512010-01-27 12:49:23 +00001179 // Look for an existing one
1180 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1181 if (old != ObjCStrings.end())
1182 return old->getValue();
1183
David Blaikiebbafb8a2012-03-11 07:00:24 +00001184 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001185
1186 if (StringClass.empty()) StringClass = "NXConstantString";
1187
1188 std::string Sym = "_OBJC_CLASS_";
1189 Sym += StringClass;
1190
1191 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1192
1193 if (!isa)
1194 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00001195 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00001196 else if (isa->getType() != PtrToIdTy)
1197 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1198
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001199 std::vector<llvm::Constant*> Ivars;
David Chisnall207a6302012-01-04 12:02:13 +00001200 Ivars.push_back(isa);
Chris Lattner091f6982008-06-21 21:44:18 +00001201 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001202 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001203 llvm::Constant *ObjCStr = MakeGlobal(
Craig Topper8a13c412014-05-21 05:09:00 +00001204 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001205 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +00001206 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1207 ObjCStrings[Str] = ObjCStr;
1208 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001209 return ObjCStr;
1210}
1211
1212///Generates a message send where the super is the receiver. This is a message
1213///send to self with special delivery semantics indicating which class's method
1214///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001215RValue
1216CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001217 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001218 QualType ResultType,
1219 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001220 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001221 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001222 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001223 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001224 const CallArgList &CallArgs,
1225 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001226 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001227 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001228 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001229 return RValue::get(EnforceType(Builder, Receiver,
1230 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001231 }
1232 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001233 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001234 }
1235 }
David Chisnallea529a42010-05-01 12:37:16 +00001236
John McCall882987f2013-02-28 19:01:20 +00001237 llvm::Value *cmd = GetSelector(CGF, Sel);
David Chisnallea529a42010-05-01 12:37:16 +00001238
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001239
1240 CallArgList ActualArgs;
1241
Eli Friedman43dca6a2011-05-02 17:57:46 +00001242 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1243 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001244 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001245
John McCalla729c622012-02-17 03:33:10 +00001246 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001247
Craig Topper8a13c412014-05-21 05:09:00 +00001248 llvm::Value *ReceiverClass = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001249 if (isCategoryImpl) {
Craig Topper8a13c412014-05-21 05:09:00 +00001250 llvm::Constant *classLookupFunction = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001251 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001252 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001253 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001254 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001255 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001256 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001257 }
David Chisnallea529a42010-05-01 12:37:16 +00001258 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001259 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001260 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001261 // Set up global aliases for the metaclass or class pointer if they do not
1262 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001263 // pointers to the class and metaclass structure created for the runtime
1264 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001265 // super_class pointer from either the class or metaclass structure.
1266 if (IsClassMessage) {
1267 if (!MetaClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001268 MetaClassPtrAlias = llvm::GlobalAlias::create(
David Blaikie881b2342015-04-29 21:22:47 +00001269 IdTy, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001270 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001271 }
1272 ReceiverClass = MetaClassPtrAlias;
1273 } else {
1274 if (!ClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001275 ClassPtrAlias = llvm::GlobalAlias::create(
David Blaikie881b2342015-04-29 21:22:47 +00001276 IdTy, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001277 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001278 }
1279 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001280 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001281 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001282 // Cast the pointer to a simplified version of the class structure
David Blaikie1ed728c2015-04-05 22:45:47 +00001283 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnallea529a42010-05-01 12:37:16 +00001284 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
David Blaikie1ed728c2015-04-05 22:45:47 +00001285 llvm::PointerType::getUnqual(CastTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001286 // Get the superclass pointer
David Blaikie1ed728c2015-04-05 22:45:47 +00001287 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001288 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001289 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001290 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001291 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Craig Topper8a13c412014-05-21 05:09:00 +00001292 Receiver->getType(), IdTy, nullptr);
David Chisnallea529a42010-05-01 12:37:16 +00001293 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001294
David Blaikie2e804282015-04-05 22:47:07 +00001295 Builder.CreateStore(Receiver,
1296 Builder.CreateStructGEP(ObjCSuperTy, ObjCSuper, 0));
1297 Builder.CreateStore(ReceiverClass,
1298 Builder.CreateStructGEP(ObjCSuperTy, ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001299
David Chisnall76803412011-03-23 22:52:06 +00001300 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001301
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001302 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001303 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001304 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001305
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001306 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00001307 llvm::MDString::get(VMContext, Sel.getAsString()),
1308 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001309 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1310 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00001311 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001312
David Chisnallff5f88c2010-05-02 13:41:58 +00001313 llvm::Instruction *call;
Craig Topper8a13c412014-05-21 05:09:00 +00001314 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1315 &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001316 call->setMetadata(msgSendMDKind, node);
1317 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001318}
1319
Mike Stump11289f42009-09-09 15:08:12 +00001320/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001321RValue
1322CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001323 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001324 QualType ResultType,
1325 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001326 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001327 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001328 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001329 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001330 CGBuilderTy &Builder = CGF.Builder;
1331
David Chisnall75afda62010-04-27 15:08:48 +00001332 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001333 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001334 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001335 return RValue::get(EnforceType(Builder, Receiver,
1336 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001337 }
1338 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001339 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001340 }
1341 }
David Chisnall75afda62010-04-27 15:08:48 +00001342
David Chisnall75afda62010-04-27 15:08:48 +00001343 // If the return type is something that goes in an integer register, the
1344 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1345 // ourselves.
1346 //
1347 // The language spec says the result of this kind of message send is
1348 // undefined, but lots of people seem to have forgotten to read that
1349 // paragraph and insist on sending messages to nil that have structure
1350 // returns. With GCC, this generates a random return value (whatever happens
1351 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001352 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1353 // the stack.
1354 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1355 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001356
Craig Topper8a13c412014-05-21 05:09:00 +00001357 llvm::BasicBlock *startBB = nullptr;
1358 llvm::BasicBlock *messageBB = nullptr;
1359 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00001360
1361 if (!isPointerSizedReturn) {
1362 startBB = Builder.GetInsertBlock();
1363 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001364 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001365
1366 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1367 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001368 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001369 CGF.EmitBlock(messageBB);
1370 }
1371
David Chisnall9f57c292009-08-17 16:35:33 +00001372 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001373 llvm::Value *cmd;
1374 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001375 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001376 else
John McCall882987f2013-02-28 19:01:20 +00001377 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001378 cmd = EnforceType(Builder, cmd, SelectorTy);
1379 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001380
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001381 llvm::Metadata *impMD[] = {
1382 llvm::MDString::get(VMContext, Sel.getAsString()),
1383 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1384 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1385 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00001386 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001387
David Chisnall76803412011-03-23 22:52:06 +00001388 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001389 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1390 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001391 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001392
1393 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1394
David Chisnall8c93cf22011-10-24 14:07:03 +00001395 // Get the IMP to call
1396 llvm::Value *imp;
1397
1398 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1399 // functions. These are not supported on all platforms (or all runtimes on a
1400 // given platform), so we
1401 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001402 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001403 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001404 break;
1405 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001406 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001407 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1408 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1409 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001410 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001411 // The actual types here don't matter - we're going to bitcast the
1412 // function anyway
1413 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1414 "objc_msgSend_stret");
1415 } else {
1416 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1417 "objc_msgSend");
1418 }
1419 }
1420
David Chisnall6aec31a2011-12-01 18:40:09 +00001421 // Reset the receiver in case the lookup modified it
1422 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001423
John McCalla729c622012-02-17 03:33:10 +00001424 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001425
David Chisnallff5f88c2010-05-02 13:41:58 +00001426 llvm::Instruction *call;
Craig Topper8a13c412014-05-21 05:09:00 +00001427 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1428 &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001429 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001430
David Chisnall29cefd12010-05-20 13:45:48 +00001431
David Chisnall75afda62010-04-27 15:08:48 +00001432 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001433 messageBB = CGF.Builder.GetInsertBlock();
1434 CGF.Builder.CreateBr(continueBB);
1435 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001436 if (msgRet.isScalar()) {
1437 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001438 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001439 phi->addIncoming(v, messageBB);
1440 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1441 msgRet = RValue::get(phi);
1442 } else if (msgRet.isAggregate()) {
1443 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001444 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2192fe52011-07-18 04:24:23 +00001445 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001446 llvm::AllocaInst *NullVal =
1447 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001448 CGF.InitTempAlloca(NullVal,
1449 llvm::Constant::getNullValue(RetTy->getElementType()));
1450 phi->addIncoming(v, messageBB);
1451 phi->addIncoming(NullVal, startBB);
1452 msgRet = RValue::getAggregate(phi);
1453 } else /* isComplex() */ {
1454 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001455 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001456 phi->addIncoming(v.first, messageBB);
1457 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1458 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001459 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001460 phi2->addIncoming(v.second, messageBB);
1461 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1462 startBB);
1463 msgRet = RValue::getComplex(phi, phi2);
1464 }
1465 }
1466 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001467}
1468
Mike Stump11289f42009-09-09 15:08:12 +00001469/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001470/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001471llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00001472GenerateMethodList(StringRef ClassName,
1473 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001474 ArrayRef<Selector> MethodSels,
1475 ArrayRef<llvm::Constant *> MethodTypes,
1476 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001477 if (MethodSels.empty())
1478 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001479 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001480 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001481 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1482 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001483 IMPTy, //Method pointer
Craig Topper8a13c412014-05-21 05:09:00 +00001484 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001485 std::vector<llvm::Constant*> Methods;
1486 std::vector<llvm::Constant*> Elements;
1487 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1488 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001489 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001490 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001491 MethodSels[i],
1492 isClassMethodList));
1493 assert(Method && "Can't generate metadata for method that doesn't exist");
1494 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1495 Elements.push_back(C);
1496 Elements.push_back(MethodTypes[i]);
1497 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001498 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001499 Elements.push_back(Method);
1500 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001501 }
1502
1503 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001504 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001505 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001506 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001507 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001508
1509 // Structure containing list pointer, array and array count
Chris Lattner5ec04a52011-08-12 17:43:31 +00001510 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattnera5f58b02011-07-09 17:41:47 +00001511 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1512 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001513 NextPtrTy,
1514 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001515 ObjCMethodArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001516 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001517
1518 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001519 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001520 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnallcdd207e2011-10-04 15:35:30 +00001521 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001522 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001523
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001524 // Create an instance of the structure
1525 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1526}
1527
1528/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001529llvm::Constant *CGObjCGNU::
1530GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1531 ArrayRef<llvm::Constant *> IvarTypes,
1532 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001533 if (IvarNames.size() == 0)
1534 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001535 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001536 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001537 PtrToInt8Ty,
1538 PtrToInt8Ty,
1539 IntTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001540 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001541 std::vector<llvm::Constant*> Ivars;
1542 std::vector<llvm::Constant*> Elements;
1543 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1544 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001545 Elements.push_back(IvarNames[i]);
1546 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001547 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001548 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001549 }
1550
1551 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001552 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001553 IvarNames.size());
1554
Mike Stump11289f42009-09-09 15:08:12 +00001555
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001556 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001557 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001558 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001559 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001560 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001561 ObjCIvarArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001562 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001563
1564 // Create an instance of the structure
1565 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1566}
1567
1568/// Generate a class structure
1569llvm::Constant *CGObjCGNU::GenerateClassStructure(
1570 llvm::Constant *MetaClass,
1571 llvm::Constant *SuperClass,
1572 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001573 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001574 llvm::Constant *Version,
1575 llvm::Constant *InstanceSize,
1576 llvm::Constant *IVars,
1577 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001578 llvm::Constant *Protocols,
1579 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001580 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001581 llvm::Constant *StrongIvarBitmap,
1582 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001583 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001584 // Set up the class structure
1585 // Note: Several of these are char*s when they should be ids. This is
1586 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001587 //
1588 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1589 // anyway; the classes will still work with the GNU runtime, they will just
1590 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001591 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall207a6302012-01-04 12:02:13 +00001592 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001593 PtrToInt8Ty, // super_class
1594 PtrToInt8Ty, // name
1595 LongTy, // version
1596 LongTy, // info
1597 LongTy, // instance_size
1598 IVars->getType(), // ivars
1599 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001600 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001601 PtrTy, // dtable
1602 PtrTy, // subclass_list
1603 PtrTy, // sibling_class
1604 PtrTy, // protocols
1605 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001606 // New ABI:
1607 LongTy, // abi_version
1608 IvarOffsets->getType(), // ivar_offsets
1609 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001610 IntPtrTy, // strong_pointers
1611 IntPtrTy, // weak_pointers
Craig Topper8a13c412014-05-21 05:09:00 +00001612 nullptr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001613 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001614 // Fill in the structure
1615 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001616 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001617 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001618 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001619 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001620 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001621 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001622 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001623 Elements.push_back(
1624 llvm::ConstantInt::get(LongTy,
1625 td.getTypeSizeInBits(ClassTy) /
1626 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001627 } else
1628 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001629 Elements.push_back(IVars);
1630 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001631 Elements.push_back(NULLPtr);
1632 Elements.push_back(NULLPtr);
1633 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001634 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001635 Elements.push_back(NULLPtr);
David Chisnallcdd207e2011-10-04 15:35:30 +00001636 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001637 Elements.push_back(IvarOffsets);
1638 Elements.push_back(Properties);
David Chisnallcdd207e2011-10-04 15:35:30 +00001639 Elements.push_back(StrongIvarBitmap);
1640 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001641 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001642 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001643 // messages in the next ABI. We may already have some weak references to
1644 // this, so check and fix them properly.
1645 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1646 std::string(Name));
1647 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1648 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1649 llvm::GlobalValue::ExternalLinkage);
1650 if (ClassRef) {
1651 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1652 ClassRef->getType()));
1653 ClassRef->removeFromParent();
1654 Class->setName(ClassSym);
1655 }
1656 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001657}
1658
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001659llvm::Constant *CGObjCGNU::
1660GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1661 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001662 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001663 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001664 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1665 PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00001666 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001667 std::vector<llvm::Constant*> Methods;
1668 std::vector<llvm::Constant*> Elements;
1669 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1670 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001671 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001672 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001673 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001674 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001675 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001676 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001677 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001678 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001679 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Craig Topper8a13c412014-05-21 05:09:00 +00001680 IntTy, ObjCMethodArrayTy, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001681 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001682 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001683 Methods.push_back(Array);
1684 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1685}
Mike Stumpdd93a192009-07-31 21:31:32 +00001686
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001687// Create the protocol list structure used in classes, categories and so on
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001688llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson9793f0e2009-07-29 22:16:19 +00001689 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001690 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001691 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001692 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001693 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001694 ProtocolArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001695 nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00001696 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001697 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1698 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00001699 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00001700 llvm::StringMap<llvm::Constant*>::iterator value =
1701 ExistingProtocols.find(*iter);
1702 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001703 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001704 } else {
1705 protocol = value->getValue();
1706 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001707 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001708 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001709 Elements.push_back(Ptr);
1710 }
Owen Anderson47034e12009-07-28 18:33:04 +00001711 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001712 Elements);
1713 Elements.clear();
1714 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001715 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001716 Elements.push_back(ProtocolArray);
1717 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1718}
1719
John McCall882987f2013-02-28 19:01:20 +00001720llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001721 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001722 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001723 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001724 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001725 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001726}
1727
1728llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1729 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001730 SmallVector<std::string, 0> EmptyStringVector;
1731 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001732
1733 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001734 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001735 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1736 // Protocols are objects containing lists of the methods implemented and
1737 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001738 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001739 PtrToInt8Ty,
1740 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001741 MethodList->getType(),
1742 MethodList->getType(),
1743 MethodList->getType(),
1744 MethodList->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +00001745 nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00001746 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001747 // The isa pointer must be set to a magic number so the runtime knows it's
1748 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001749 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001750 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001751 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1752 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001753 Elements.push_back(MethodList);
1754 Elements.push_back(MethodList);
1755 Elements.push_back(MethodList);
1756 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001757 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001758}
1759
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001760void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1761 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001762 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001763
1764 // Use the protocol definition, if there is one.
1765 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1766 PD = Def;
1767
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001768 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001769 for (const auto *PI : PD->protocols())
1770 Protocols.push_back(PI->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001771 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1772 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1773 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1774 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001775 for (const auto *I : PD->instance_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001776 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001777 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1778 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001779 OptionalInstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001780 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001781 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001782 } else {
1783 InstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001784 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001785 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001786 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001787 }
1788 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001789 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1790 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1791 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1792 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001793 for (const auto *I : PD->class_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001794 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001795 Context.getObjCEncodingForMethodDecl(I,TypeStr);
1796 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001797 OptionalClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001798 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001799 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001800 } else {
1801 ClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001802 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001803 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001804 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001805 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001806
1807 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1808 llvm::Constant *InstanceMethodList =
1809 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1810 llvm::Constant *ClassMethodList =
1811 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001812 llvm::Constant *OptionalInstanceMethodList =
1813 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1814 OptionalInstanceMethodTypes);
1815 llvm::Constant *OptionalClassMethodList =
1816 GenerateProtocolMethodList(OptionalClassMethodNames,
1817 OptionalClassMethodTypes);
1818
1819 // Property metadata: name, attributes, isSynthesized, setter name, setter
1820 // types, getter name, getter types.
1821 // The isSynthesized value is always set to 0 in a protocol. It exists to
1822 // simplify the runtime library by allowing it to use the same data
1823 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001824 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00001825 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00001826 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001827 std::vector<llvm::Constant*> Properties;
1828 std::vector<llvm::Constant*> OptionalProperties;
1829
1830 // Add all of the property methods need adding to the method list and to the
1831 // property metadata list.
Aaron Ballmand174edf2014-03-13 19:11:50 +00001832 for (auto *property : PD->properties()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001833 std::vector<llvm::Constant*> Fields;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001834
Craig Topper8a13c412014-05-21 05:09:00 +00001835 Fields.push_back(MakePropertyEncodingString(property, nullptr));
David Chisnallbeb80132013-02-28 13:59:29 +00001836 PushPropertyAttributes(Fields, property);
David Chisnalla5f59412012-10-16 15:11:55 +00001837
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001838 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1839 std::string TypeStr;
1840 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1841 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1842 InstanceMethodTypes.push_back(TypeEncoding);
1843 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1844 Fields.push_back(TypeEncoding);
1845 } else {
1846 Fields.push_back(NULLPtr);
1847 Fields.push_back(NULLPtr);
1848 }
1849 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1850 std::string TypeStr;
1851 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1852 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1853 InstanceMethodTypes.push_back(TypeEncoding);
1854 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1855 Fields.push_back(TypeEncoding);
1856 } else {
1857 Fields.push_back(NULLPtr);
1858 Fields.push_back(NULLPtr);
1859 }
1860 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1861 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1862 } else {
1863 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1864 }
1865 }
1866 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1867 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1868 llvm::Constant* PropertyListInitFields[] =
1869 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1870
1871 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001872 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001873 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1874 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1875 PropertyListInit, ".objc_property_list");
1876
1877 llvm::Constant *OptionalPropertyArray =
1878 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1879 OptionalProperties.size()) , OptionalProperties);
1880 llvm::Constant* OptionalPropertyListInitFields[] = {
1881 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1882 OptionalPropertyArray };
1883
1884 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001885 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001886 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1887 OptionalPropertyListInit->getType(), false,
1888 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1889 ".objc_property_list");
1890
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001891 // Protocols are objects containing lists of the methods implemented and
1892 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001893 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001894 PtrToInt8Ty,
1895 ProtocolList->getType(),
1896 InstanceMethodList->getType(),
1897 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001898 OptionalInstanceMethodList->getType(),
1899 OptionalClassMethodList->getType(),
1900 PropertyList->getType(),
1901 OptionalPropertyList->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +00001902 nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00001903 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001904 // The isa pointer must be set to a magic number so the runtime knows it's
1905 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001906 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001907 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001908 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1909 Elements.push_back(ProtocolList);
1910 Elements.push_back(InstanceMethodList);
1911 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001912 Elements.push_back(OptionalInstanceMethodList);
1913 Elements.push_back(OptionalClassMethodList);
1914 Elements.push_back(PropertyList);
1915 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001916 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001917 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001918 ".objc_protocol"), IdTy);
1919}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001920void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001921 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001922 SmallVector<Selector, 1> MethodSels;
1923 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001924
1925 std::vector<llvm::Constant*> Elements;
1926 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1927 const std::string CategoryName = "AnotherHack";
1928 Elements.push_back(MakeConstantString(CategoryName));
1929 Elements.push_back(MakeConstantString(ClassName));
1930 // Instance method list
1931 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1932 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1933 // Class method list
1934 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1935 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1936 // Protocol list
1937 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1938 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001939 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001940 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001941 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001942 ProtocolArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001943 nullptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001944 std::vector<llvm::Constant*> ProtocolElements;
1945 for (llvm::StringMapIterator<llvm::Constant*> iter =
1946 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1947 iter != endIter ; iter++) {
1948 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1949 PtrTy);
1950 ProtocolElements.push_back(Ptr);
1951 }
1952 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1953 ProtocolElements);
1954 ProtocolElements.clear();
1955 ProtocolElements.push_back(NULLPtr);
1956 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1957 ExistingProtocols.size()));
1958 ProtocolElements.push_back(ProtocolArray);
1959 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1960 ProtocolElements, ".objc_protocol_list"), PtrTy));
1961 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001962 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00001963 PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001964}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001965
David Chisnallcdd207e2011-10-04 15:35:30 +00001966/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1967/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1968/// bits set to their values, LSB first, while larger ones are stored in a
1969/// structure of this / form:
1970///
1971/// struct { int32_t length; int32_t values[length]; };
1972///
1973/// The values in the array are stored in host-endian format, with the least
1974/// significant bit being assumed to come first in the bitfield. Therefore, a
1975/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1976/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001977llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001978 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001979 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00001980 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001981 uint64_t val = 1;
1982 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00001983 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00001984 }
David Chisnalle89ac062011-10-25 10:12:21 +00001985 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00001986 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001987 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00001988 int v=0;
1989 while (v < bitCount) {
1990 int32_t word = 0;
1991 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1992 if (bits[v]) word |= 1<<i;
1993 v++;
1994 }
1995 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1996 }
1997 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1998 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1999 llvm::Constant *fields[2] = {
2000 llvm::ConstantInt::get(Int32Ty, values.size()),
2001 array };
2002 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00002003 nullptr), fields);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002004 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002005 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002006}
2007
Daniel Dunbar92992502008-08-15 22:20:32 +00002008void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002009 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2010 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002011 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002012 SmallVector<Selector, 16> InstanceMethodSels;
2013 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002014 for (const auto *I : OCD->instance_methods()) {
2015 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002016 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002017 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002018 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002019 }
2020
2021 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002022 SmallVector<Selector, 16> ClassMethodSels;
2023 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002024 for (const auto *I : OCD->class_methods()) {
2025 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002026 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002027 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002028 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002029 }
2030
2031 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002032 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002033 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2034 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002035 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2036 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002037 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002038
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002039 std::vector<llvm::Constant*> Elements;
2040 Elements.push_back(MakeConstantString(CategoryName));
2041 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00002042 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00002043 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00002044 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002045 false), PtrTy));
2046 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00002047 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00002048 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002049 PtrTy));
2050 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00002051 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002052 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00002053 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00002054 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00002055 PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002056}
Daniel Dunbar92992502008-08-15 22:20:32 +00002057
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002058llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002059 SmallVectorImpl<Selector> &InstanceMethodSels,
2060 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002061 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002062 // Property metadata: name, attributes, attributes2, padding1, padding2,
2063 // setter name, setter types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00002064 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00002065 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00002066 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002067 std::vector<llvm::Constant*> Properties;
2068
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002069 // Add all of the property methods need adding to the method list and to the
2070 // property metadata list.
Aaron Ballmand85eff42014-03-14 15:02:45 +00002071 for (auto *propertyImpl : OID->property_impls()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002072 std::vector<llvm::Constant*> Fields;
Aaron Ballmand85eff42014-03-14 15:02:45 +00002073 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00002074 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2075 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002076 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2077 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002078
David Chisnalla5f59412012-10-16 15:11:55 +00002079 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallbeb80132013-02-28 13:59:29 +00002080 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002081 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002082 std::string TypeStr;
2083 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2084 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002085 if (isSynthesized) {
2086 InstanceMethodTypes.push_back(TypeEncoding);
2087 InstanceMethodSels.push_back(getter->getSelector());
2088 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002089 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2090 Fields.push_back(TypeEncoding);
2091 } else {
2092 Fields.push_back(NULLPtr);
2093 Fields.push_back(NULLPtr);
2094 }
2095 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002096 std::string TypeStr;
2097 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2098 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002099 if (isSynthesized) {
2100 InstanceMethodTypes.push_back(TypeEncoding);
2101 InstanceMethodSels.push_back(setter->getSelector());
2102 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002103 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2104 Fields.push_back(TypeEncoding);
2105 } else {
2106 Fields.push_back(NULLPtr);
2107 Fields.push_back(NULLPtr);
2108 }
2109 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2110 }
2111 llvm::ArrayType *PropertyArrayTy =
2112 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2113 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2114 Properties);
2115 llvm::Constant* PropertyListInitFields[] =
2116 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2117
2118 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002119 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002120 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2121 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2122 ".objc_property_list");
2123}
2124
David Chisnall92d436b2012-01-31 18:59:20 +00002125void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2126 // Get the class declaration for which the alias is specified.
2127 ObjCInterfaceDecl *ClassDecl =
2128 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2129 std::string ClassName = ClassDecl->getNameAsString();
2130 std::string AliasName = OAD->getNameAsString();
2131 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2132}
2133
Daniel Dunbar92992502008-08-15 22:20:32 +00002134void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2135 ASTContext &Context = CGM.getContext();
2136
2137 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002138 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002139 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002140 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002141 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002142 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002143 EmitClassRef(SuperClassName);
2144 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002145
2146 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002147 ObjCInterfaceDecl *ClassDecl =
2148 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002149 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002150 // Emit the symbol that is used to generate linker errors if this class is
2151 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002152 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00002153 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002154 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002155 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002156 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002157 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002158 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00002159 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002160 }
Mike Stump11289f42009-09-09 15:08:12 +00002161
Daniel Dunbar12119b92009-05-03 10:46:44 +00002162 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002163 int instanceSize =
2164 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002165
2166 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002167 SmallVector<llvm::Constant*, 16> IvarNames;
2168 SmallVector<llvm::Constant*, 16> IvarTypes;
2169 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002170
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002171 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnallcdd207e2011-10-04 15:35:30 +00002172 SmallVector<bool, 16> WeakIvars;
2173 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002174
Mike Stump11289f42009-09-09 15:08:12 +00002175 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002176 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002177 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2178 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002179 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002180 instanceSize = 0 - (instanceSize - superInstanceSize);
2181 }
David Chisnall18cf7372010-04-19 00:45:34 +00002182
Jordy Rosea91768e2011-07-22 02:08:32 +00002183 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2184 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002185 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002186 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002187 // Get the type encoding for this ivar
2188 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002189 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002190 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002191 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002192 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002193 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002194 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002195 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002196 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002197 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2198 // Create the direct offset value
2199 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2200 IVD->getNameAsString();
2201 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2202 if (OffsetVar) {
2203 OffsetVar->setInitializer(OffsetValue);
2204 // If this is the real definition, change its linkage type so that
2205 // different modules will use this one, rather than their private
2206 // copy.
2207 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2208 } else
2209 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002210 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002211 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002212 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002213 IVD->getNameAsString());
2214 IvarOffsets.push_back(OffsetValue);
2215 IvarOffsetValues.push_back(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002216 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2217 switch (lt) {
2218 case Qualifiers::OCL_Strong:
2219 StrongIvars.push_back(true);
2220 WeakIvars.push_back(false);
2221 break;
2222 case Qualifiers::OCL_Weak:
2223 StrongIvars.push_back(false);
2224 WeakIvars.push_back(true);
2225 break;
2226 default:
2227 StrongIvars.push_back(false);
2228 WeakIvars.push_back(false);
2229 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002230 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002231 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2232 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002233 llvm::GlobalVariable *IvarOffsetArray =
2234 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2235
Daniel Dunbar92992502008-08-15 22:20:32 +00002236
2237 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002238 SmallVector<Selector, 16> InstanceMethodSels;
2239 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002240 for (const auto *I : OID->instance_methods()) {
2241 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002242 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002243 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002244 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002245 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002246
2247 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2248 InstanceMethodTypes);
2249
Daniel Dunbar92992502008-08-15 22:20:32 +00002250
2251 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002252 SmallVector<Selector, 16> ClassMethodSels;
2253 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002254 for (const auto *I : OID->class_methods()) {
2255 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002256 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002257 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002258 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002259 }
2260 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002261 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00002262 for (const auto *I : ClassDecl->protocols())
2263 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002264
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002265 // Get the superclass pointer.
2266 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002267 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002268 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2269 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002270 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002271 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002272 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002273 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002274 // Generate the method and instance variable lists
2275 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002276 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002277 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002278 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002279 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2280 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002281 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002282 // we emit a symbol containing the offset for each ivar in the class. This
2283 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2284 // for the legacy ABI, without causing problems. The converse is also
2285 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002286
David Chisnall5778fce2009-08-31 16:41:57 +00002287 // Offset pointer for getting at the correct field in the ivar list when
2288 // setting up the alias. These are: The base address for the global, the
2289 // ivar array (second field), the ivar in this list (set for each ivar), and
2290 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002291 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002292 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Craig Topper8a13c412014-05-21 05:09:00 +00002293 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall5778fce2009-08-31 16:41:57 +00002294 llvm::ConstantInt::get(IndexTy, 2) };
2295
Jordy Rosea91768e2011-07-22 02:08:32 +00002296 unsigned ivarIndex = 0;
2297 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2298 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002299 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002300 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002301 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002302 // Get the correct ivar field
2303 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00002304 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2305 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002306 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002307 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2308 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002309 offset->setInitializer(offsetValue);
2310 // If this is the real definition, change its linkage type so that
2311 // different modules will use this one, rather than their private
2312 // copy.
2313 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002314 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002315 // Add a new alias if there isn't one already.
2316 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2317 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2318 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002319 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002320 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002321 }
David Chisnalle89ac062011-10-25 10:12:21 +00002322 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002323 //Generate metaclass for class methods
2324 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Craig Topper8a13c412014-05-21 05:09:00 +00002325 NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
David Chisnallcdd207e2011-10-04 15:35:30 +00002326 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnalle89ac062011-10-25 10:12:21 +00002327 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002328
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002329 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002330 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002331 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Craig Topper8a13c412014-05-21 05:09:00 +00002332 ClassName.c_str(), nullptr,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002333 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002334 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnallcdd207e2011-10-04 15:35:30 +00002335 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002336
2337 // Resolve the class aliases, if they exist.
2338 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002339 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002340 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002341 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002342 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002343 }
2344 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002345 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002346 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002347 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002348 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002349 }
2350
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002351 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002352 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002353 Classes.push_back(ClassStruct);
2354}
2355
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002356
Mike Stump11289f42009-09-09 15:08:12 +00002357llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002358 // Only emit an ObjC load function if no Objective-C stuff has been called
2359 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002360 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00002361 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00002362
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002363 // Add all referenced protocols to a category.
2364 GenerateProtocolHolderCategory();
2365
Chris Lattner2192fe52011-07-18 04:24:23 +00002366 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002367 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002368 llvm::Type *SelStructPtrTy = SelectorTy;
Craig Topper8a13c412014-05-21 05:09:00 +00002369 if (!SelStructTy) {
2370 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002371 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002372 }
2373
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002374 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002375 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002376 // Generate statics list:
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00002377 if (!ConstantStrings.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002378 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002379 ConstantStrings.size() + 1);
2380 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002381
David Blaikiebbafb8a2012-03-11 07:00:24 +00002382 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002383
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002384 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002385
David Chisnall5778fce2009-08-31 16:41:57 +00002386 Elements.push_back(MakeConstantString(StringClass,
2387 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002388 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002389 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002390 llvm::StructType *StaticsListTy =
Craig Topper8a13c412014-05-21 05:09:00 +00002391 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
Owen Anderson170229f2009-07-14 23:10:40 +00002392 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002393 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002394 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002395 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002396 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002397 Elements.clear();
2398 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002399 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002400 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002401 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002402 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002403 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002404 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002405 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002406 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002407 llvm::Type::getInt16Ty(VMContext),
2408 llvm::Type::getInt16Ty(VMContext),
Craig Topper8a13c412014-05-21 05:09:00 +00002409 ClassListTy, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002410
2411 Elements.clear();
2412 // Pointer to an array of selectors used in this module.
2413 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002414 std::vector<llvm::GlobalAlias*> SelectorAliases;
2415 for (SelectorMap::iterator iter = SelectorTable.begin(),
2416 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2417
2418 std::string SelNameStr = iter->first.getAsString();
2419 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2420
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 SmallVectorImpl<TypedSelector> &Types = iter->second;
2422 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002423 e = Types.end() ; i!=e ; i++) {
2424
2425 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2426 if (!i->first.empty())
2427 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2428
2429 Elements.push_back(SelName);
2430 Elements.push_back(SelectorTypeEncoding);
2431 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2432 Elements.clear();
2433
2434 // Store the selector alias for later replacement
2435 SelectorAliases.push_back(i->second);
2436 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002437 }
David Chisnalld7972f52011-03-23 16:36:54 +00002438 unsigned SelectorCount = Selectors.size();
2439 // NULL-terminate the selector list. This should not actually be required,
2440 // because the selector list has a length field. Unfortunately, the GCC
2441 // runtime decides to ignore the length field and expects a NULL terminator,
2442 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002443 Elements.push_back(NULLPtr);
2444 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002445 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002446 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002447
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002448 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002449 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
David Blaikiee3b172a2015-04-02 18:55:21 +00002450 llvm::GlobalVariable *SelectorList =
2451 MakeGlobalArray(SelStructTy, Selectors, ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002452 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002453 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002454
2455 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002456 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2457
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002458 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002459 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002460 // FIXME: We're generating redundant loads and stores here!
David Blaikiee3b172a2015-04-02 18:55:21 +00002461 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(
2462 SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002463 // If selectors are defined as an opaque type, cast the pointer to this
2464 // type.
David Chisnall76803412011-03-23 22:52:06 +00002465 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002466 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2467 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002468 }
David Chisnalld7972f52011-03-23 16:36:54 +00002469
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002470 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002471 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002472 Classes.size()));
2473 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002474 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002475 Categories.size()));
2476 // Create an array of classes, then categories, then static object instances
2477 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2478 // NULL-terminated list of static object instances (mainly constant strings)
2479 Classes.push_back(Statics);
2480 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002481 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002482 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002483 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002484 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2485
2486 // The symbol table is contained in a module which has some version-checking
2487 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002488 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002489 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
Craig Topper8a13c412014-05-21 05:09:00 +00002490 (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002491 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002492 // Runtime version, used for ABI compatibility checking.
2493 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002494 // sizeof(ModuleTy)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002495 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002496 Elements.push_back(
2497 llvm::ConstantInt::get(LongTy,
2498 td.getTypeSizeInBits(ModuleTy) /
2499 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002500
2501 // The path to the source file where this module was declared
2502 SourceManager &SM = CGM.getContext().getSourceManager();
2503 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2504 std::string path =
2505 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2506 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002507 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002508
David Chisnalla918b882011-07-07 11:22:31 +00002509 if (RuntimeVersion >= 10)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002510 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002511 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002512 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002513 break;
David Chisnalla918b882011-07-07 11:22:31 +00002514 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002515 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002516 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2517 else
2518 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2519 break;
2520 case LangOptions::HybridGC:
2521 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2522 break;
2523 }
David Chisnall5c511772011-05-22 22:37:08 +00002524
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002525 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2526
2527 // Create the load function calling the runtime entry point with the module
2528 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002529 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002530 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002531 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2532 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002533 llvm::BasicBlock *EntryBB =
2534 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002535 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002536 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002537
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002538 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002539 llvm::FunctionType::get(Builder.getVoidTy(),
2540 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002541 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002542 Builder.CreateCall(Register, Module);
David Chisnall92d436b2012-01-31 18:59:20 +00002543
David Chisnallaf066bbb2012-02-01 19:16:56 +00002544 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002545 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2546 llvm::FunctionType *RegisterAliasTy =
2547 llvm::FunctionType::get(Builder.getVoidTy(),
2548 ArgTypes, false);
2549 llvm::Function *RegisterAlias = llvm::Function::Create(
2550 RegisterAliasTy,
2551 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2552 &TheModule);
2553 llvm::BasicBlock *AliasBB =
2554 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2555 llvm::BasicBlock *NoAliasBB =
2556 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2557
2558 // Branch based on whether the runtime provided class_registerAlias_np()
2559 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2560 llvm::Constant::getNullValue(RegisterAlias->getType()));
2561 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2562
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002563 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002564 Builder.SetInsertPoint(AliasBB);
2565 // Emit alias registration calls:
2566 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2567 iter != ClassAliases.end(); ++iter) {
2568 llvm::Constant *TheClass =
2569 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2570 true);
Craig Topper8a13c412014-05-21 05:09:00 +00002571 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00002572 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2573 Builder.CreateCall2(RegisterAlias, TheClass,
2574 MakeConstantString(iter->second));
2575 }
2576 }
2577 // Jump to end:
2578 Builder.CreateBr(NoAliasBB);
2579
2580 // Missing alias registration function, just return from the function:
2581 Builder.SetInsertPoint(NoAliasBB);
2582 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002583 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002584
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002585 return LoadFunction;
2586}
Daniel Dunbar92992502008-08-15 22:20:32 +00002587
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002588llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002589 const ObjCContainerDecl *CD) {
2590 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002591 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002592 StringRef CategoryName = OCD ? OCD->getName() : "";
2593 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002594 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002595 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002596
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002597 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002598 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002599 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002600 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2601 MethodName, isClassMethod);
2602
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002603 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002604 = llvm::Function::Create(MethodTy,
2605 llvm::GlobalValue::InternalLinkage,
2606 FunctionName,
2607 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002608 return Method;
2609}
2610
David Chisnall3fe89562011-05-23 22:33:28 +00002611llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002612 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002613}
2614
David Chisnall3fe89562011-05-23 22:33:28 +00002615llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002616 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002617}
2618
Ted Kremeneke65b0862012-03-06 20:05:56 +00002619llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2620 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00002621 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002622}
2623
David Chisnall3fe89562011-05-23 22:33:28 +00002624llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002625 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002626}
David Chisnall3fe89562011-05-23 22:33:28 +00002627llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002628 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002629}
David Chisnall0d75e062012-12-17 18:54:24 +00002630llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002631 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00002632}
2633llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002634 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002635}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002636
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002637llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002638 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002639}
2640
David Chisnalld7972f52011-03-23 16:36:54 +00002641void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002642 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002643 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002644}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002645
David Chisnall3a509cd2009-12-24 02:26:34 +00002646
David Chisnalld7972f52011-03-23 16:36:54 +00002647void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002648 const ObjCAtTryStmt &S) {
2649 // Unlike the Apple non-fragile runtimes, which also uses
2650 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2651 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002652 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002653 // the personality function; this avoids the need for bracketing
2654 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2655 // (or even _Unwind_DeleteException), but probably doesn't
2656 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002657 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002658 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002659 // exception handler.
2660 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2661 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002662}
2663
David Chisnalld7972f52011-03-23 16:36:54 +00002664void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002665 const ObjCAtThrowStmt &S,
2666 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002667 llvm::Value *ExceptionAsObject;
2668
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002669 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002670 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002671 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002672 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002673 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002674 "Unexpected rethrow outside @catch block.");
2675 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2676 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002677 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002678 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002679 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002680 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002681 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002682 if (ClearInsertionPoint)
2683 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002684}
2685
David Chisnalld7972f52011-03-23 16:36:54 +00002686llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002687 llvm::Value *AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002688 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002689 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002690 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002691}
2692
David Chisnalld7972f52011-03-23 16:36:54 +00002693void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002694 llvm::Value *src, llvm::Value *dst) {
John McCall882987f2013-02-28 19:01:20 +00002695 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002696 src = EnforceType(B, src, IdTy);
2697 dst = EnforceType(B, dst, PtrToIdTy);
2698 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002699}
2700
David Chisnalld7972f52011-03-23 16:36:54 +00002701void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002702 llvm::Value *src, llvm::Value *dst,
2703 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002704 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002705 src = EnforceType(B, src, IdTy);
2706 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002707 if (!threadlocal)
2708 B.CreateCall2(GlobalAssignFn, src, dst);
2709 else
2710 // FIXME. Add threadloca assign API
David Blaikie83d382b2011-09-23 05:06:16 +00002711 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002712}
2713
David Chisnalld7972f52011-03-23 16:36:54 +00002714void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002715 llvm::Value *src, llvm::Value *dst,
2716 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002717 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002718 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002719 dst = EnforceType(B, dst, IdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002720 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002721}
2722
David Chisnalld7972f52011-03-23 16:36:54 +00002723void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002724 llvm::Value *src, llvm::Value *dst) {
John McCall882987f2013-02-28 19:01:20 +00002725 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002726 src = EnforceType(B, src, IdTy);
2727 dst = EnforceType(B, dst, PtrToIdTy);
2728 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002729}
2730
David Chisnalld7972f52011-03-23 16:36:54 +00002731void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002732 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002733 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002734 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002735 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002736 DestPtr = EnforceType(B, DestPtr, PtrTy);
2737 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002738
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002739 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002740}
2741
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002742llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2743 const ObjCInterfaceDecl *ID,
2744 const ObjCIvarDecl *Ivar) {
2745 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2746 + '.' + Ivar->getNameAsString();
2747 // Emit the variable and initialize it with what we think the correct value
2748 // is. This allows code compiled with non-fragile ivars to work correctly
2749 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002750 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2751 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002752 // This will cause a run-time crash if we accidentally use it. A value of
2753 // 0 would seem more sensible, but will silently overwrite the isa pointer
2754 // causing a great deal of confusion.
2755 uint64_t Offset = -1;
2756 // We can't call ComputeIvarBaseOffset() here if we have the
2757 // implementation, because it will create an invalid ASTRecordLayout object
2758 // that we are then stuck with forever, so we only initialize the ivar
2759 // offset variable with a guess if we only have the interface. The
2760 // initializer will be reset later anyway, when we are generating the class
2761 // description.
2762 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002763 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002764 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002765
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002766 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002767 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002768 // Don't emit the guess in non-PIC code because the linker will not be able
2769 // to replace it with the real version for a library. In non-PIC code you
2770 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002771 // GCC-compiled class.
Chandler Carruthc0c04552012-04-08 16:40:35 +00002772 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002773 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002774 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002775 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2776 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2777 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2778 IvarOffsetGV, Name);
2779 } else {
2780 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002781 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002782 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002783 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002784 }
David Chisnall5778fce2009-08-31 16:41:57 +00002785 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002786}
2787
David Chisnalld7972f52011-03-23 16:36:54 +00002788LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002789 QualType ObjectTy,
2790 llvm::Value *BaseValue,
2791 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002792 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002793 const ObjCInterfaceDecl *ID =
2794 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002795 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2796 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002797}
Mike Stumpdd93a192009-07-31 21:31:32 +00002798
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002799static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2800 const ObjCInterfaceDecl *OID,
2801 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002802 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2803 next = next->getNextIvar()) {
2804 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002805 return OID;
2806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002808 // Otherwise check in the super class.
2809 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2810 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002811
Craig Topper8a13c412014-05-21 05:09:00 +00002812 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002813}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002814
David Chisnalld7972f52011-03-23 16:36:54 +00002815llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002816 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002817 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002818 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002819 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002820 if (RuntimeVersion < 10)
2821 return CGF.Builder.CreateZExtOrBitCast(
2822 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2823 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2824 PtrDiffTy);
2825 std::string name = "__objc_ivar_offset_value_" +
2826 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2827 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2828 if (!Offset)
2829 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002830 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2831 llvm::Constant::getNullValue(IntTy), name);
David Chisnalla79b4692012-04-06 15:39:12 +00002832 Offset = CGF.Builder.CreateLoad(Offset);
2833 if (Offset->getType() != PtrDiffTy)
2834 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2835 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002836 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002837 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2838 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002839}
2840
David Chisnalld7972f52011-03-23 16:36:54 +00002841CGObjCRuntime *
2842clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002843 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002844 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002845 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002846
David Chisnallb601c962012-07-03 20:49:52 +00002847 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002848 return new CGObjCGCC(CGM);
2849
John McCall775086e2012-07-12 02:07:58 +00002850 case ObjCRuntime::ObjFW:
2851 return new CGObjCObjFW(CGM);
2852
John McCall5fb5df92012-06-20 06:18:46 +00002853 case ObjCRuntime::FragileMacOSX:
2854 case ObjCRuntime::MacOSX:
2855 case ObjCRuntime::iOS:
2856 llvm_unreachable("these runtimes are not GNU runtimes");
2857 }
2858 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002859}