blob: fbf8a1abb0139d5ae0ae2c8e2a4fcddbe0d29404 [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCall36f893c2011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000026#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner0f984262008-03-01 08:50:34 +000028#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include "llvm/ADT/StringMap.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
David Chisnall80558d22011-03-20 21:35:39 +000034#include "llvm/Support/CallSite.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000036#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000037
38
Chris Lattnerdce14062008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041
Chris Lattner0f984262008-03-01 08:50:34 +000042
Chris Lattner0f984262008-03-01 08:50:34 +000043namespace {
David Chisnall81a65f52011-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 Chisnall9f6614e2011-03-23 16:36:54 +000047class LazyRuntimeFunction {
48 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000049 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000050 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000051 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000052 public:
David Chisnall81a65f52011-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.
David Chisnall9f6614e2011-03-23 16:36:54 +000056 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
57
David Chisnall81a65f52011-03-26 11:48:37 +000058 /// Initialises the lazy function with the name, return type, and the types
59 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000060 END_WITH_NULL
61 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000062 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000063 CGM =Mod;
64 FunctionName = name;
65 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000066 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000067 va_list Args;
68 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000069 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000070 ArgTys.push_back(ArgTy);
71 va_end(Args);
72 // Push the return type on at the end so we can pop it off easily
73 ArgTys.push_back(RetTy);
74 }
David Chisnall81a65f52011-03-26 11:48:37 +000075 /// Overloaded cast operator, allows the class to be implicitly cast to an
76 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000077 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000078 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000079 if (0 == FunctionName) return 0;
80 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000081 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000082 ArgTys.pop_back();
83 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
84 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000085 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000086 // We won't need to use the types again, so we may as well clean up the
87 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000088 ArgTys.resize(0);
89 }
90 return Function;
91 }
David Chisnall789ecde2011-05-23 22:33:28 +000092 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000093 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000094 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000095
David Chisnall9f6614e2011-03-23 16:36:54 +000096};
97
98
David Chisnall81a65f52011-03-26 11:48:37 +000099/// GNU Objective-C runtime code generation. This class implements the parts of
John McCallf7226fb2012-07-12 02:07:58 +0000100/// Objective-C support that are specific to the GNU family of runtimes (GCC,
101/// GNUstep and ObjFW).
David Chisnall9f6614e2011-03-23 16:36:54 +0000102class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000103protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000104 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000105 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000106 /// strut objc_super. Used for sending messages to super. This structure
107 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000108 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000109 /// struct objc_super*. The type of the argument to the superclass message
110 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000111 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000112 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
113 /// SEL is included in a header somewhere, in which case it will be whatever
114 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000115 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000116 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
117 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000118 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000119 /// Pointer to i8 - LLVM type of char*, for all of the places where the
120 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000121 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000122 /// Instance Method Pointer type. This is a pointer to a function that takes,
123 /// at a minimum, an object and a selector, and is the generic type for
124 /// Objective-C methods. Due to differences between variadic / non-variadic
125 /// calling conventions, it must always be cast to the correct type before
126 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000127 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000128 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
129 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
130 /// but if the runtime header declaring it is included then it may be a
131 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000132 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000133 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
134 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000135 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000136 /// The clang type of id. Used when using the clang CGCall infrastructure to
137 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000138 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000139 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000140 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
142 /// used in the code to document the difference between i8* meaning a pointer
143 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000144 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000145 /// LLVM type for C long type. The runtime uses this in a lot of places where
146 /// it should be using intptr_t, but we can't fix this without breaking
147 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000148 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000149 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000150 llvm::IntegerType *SizeTy;
David Chisnall49de5282011-10-08 08:54:36 +0000151 /// LLVM type for C intptr_t.
152 llvm::IntegerType *IntPtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000154 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000157 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000158 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000159 llvm::Type *BoolTy;
David Chisnall917b28b2011-10-04 15:35:30 +0000160 /// 32-bit integer type, to save us needing to look it up every time it's used.
161 llvm::IntegerType *Int32Ty;
162 /// 64-bit integer type, to save us needing to look it up every time it's used.
163 llvm::IntegerType *Int64Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000164 /// Metadata kind used to tie method lookups to message sends. The GNUstep
165 /// runtime provides some LLVM passes that can use this to do things like
166 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000167 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000168 /// Helper function that generates a constant string and returns a pointer to
169 /// the start of the string. The result of this function can be used anywhere
170 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000171 llvm::Constant *MakeConstantString(const std::string &Str,
172 const std::string &Name="") {
173 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000174 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000175 }
David Chisnall81a65f52011-03-26 11:48:37 +0000176 /// Emits a linkonce_odr string, whose name is the prefix followed by the
177 /// string value. This allows the linker to combine the strings between
178 /// different modules. Used for EH typeinfo names, selector strings, and a
179 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000180 llvm::Constant *ExportUniqueString(const std::string &Str,
181 const std::string prefix) {
182 std::string name = prefix + Str;
183 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
184 if (!ConstStr) {
Chris Lattner94010692012-02-05 02:30:40 +0000185 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall9735ca62011-03-25 11:57:33 +0000186 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
187 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
188 }
Jay Foada5c04342011-07-21 14:31:17 +0000189 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000190 }
David Chisnall81a65f52011-03-26 11:48:37 +0000191 /// Generates a global structure, initialized by the elements in the vector.
192 /// The element types must match the types of the structure elements in the
193 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000194 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000195 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000196 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
200 return new llvm::GlobalVariable(TheModule, Ty, false,
201 linkage, C, Name);
202 }
David Chisnall81a65f52011-03-26 11:48:37 +0000203 /// Generates a global array. The vector must contain the same number of
204 /// elements that the array type declares, of the type specified as the array
205 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000206 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000207 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000208 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000209 llvm::GlobalValue::LinkageTypes linkage
210 =llvm::GlobalValue::InternalLinkage) {
211 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
212 return new llvm::GlobalVariable(TheModule, Ty, false,
213 linkage, C, Name);
214 }
David Chisnall81a65f52011-03-26 11:48:37 +0000215 /// Generates a global array, inferring the array type from the specified
216 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000217 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000218 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000219 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000220 llvm::GlobalValue::LinkageTypes linkage
221 =llvm::GlobalValue::InternalLinkage) {
222 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
223 return MakeGlobal(ArrayTy, V, Name, linkage);
224 }
David Chisnall891dac72012-10-16 15:11:55 +0000225 /// Returns a property name and encoding string.
226 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
227 const Decl *Container) {
David Chisnallde38cb12013-02-28 13:59:29 +0000228 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall891dac72012-10-16 15:11:55 +0000229 if ((R.getKind() == ObjCRuntime::GNUstep) &&
230 (R.getVersion() >= VersionTuple(1, 6))) {
231 std::string NameAndAttributes;
232 std::string TypeStr;
233 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
234 NameAndAttributes += '\0';
235 NameAndAttributes += TypeStr.length() + 3;
236 NameAndAttributes += TypeStr;
237 NameAndAttributes += '\0';
238 NameAndAttributes += PD->getNameAsString();
David Chisnallde38cb12013-02-28 13:59:29 +0000239 NameAndAttributes += '\0';
David Chisnall891dac72012-10-16 15:11:55 +0000240 return llvm::ConstantExpr::getGetElementPtr(
241 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
242 }
243 return MakeConstantString(PD->getNameAsString());
244 }
David Chisnallde38cb12013-02-28 13:59:29 +0000245 /// Push the property attributes into two structure fields.
246 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
247 ObjCPropertyDecl *property, bool isSynthesized=true, bool
248 isDynamic=true) {
249 int attrs = property->getPropertyAttributes();
250 // For read-only properties, clear the copy and retain flags
251 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
252 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
256 }
257 // The first flags field has the same attribute values as clang uses internally
258 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
259 attrs >>= 8;
260 attrs <<= 2;
261 // For protocol properties, synthesized and dynamic have no meaning, so we
262 // reuse these flags to indicate that this is a protocol property (both set
263 // has no meaning, as a property can't be both synthesized and dynamic)
264 attrs |= isSynthesized ? (1<<0) : 0;
265 attrs |= isDynamic ? (1<<1) : 0;
266 // The second field is the next four fields left shifted by two, with the
267 // low bit set to indicate whether the field is synthesized or dynamic.
268 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
269 // Two padding fields
270 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
271 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
272 }
David Chisnall81a65f52011-03-26 11:48:37 +0000273 /// Ensures that the value has the required type, by inserting a bitcast if
274 /// required. This function lets us avoid inserting bitcasts that are
275 /// redundant.
John McCallbd7370a2013-02-28 19:01:20 +0000276 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000277 if (V->getType() == Ty) return V;
278 return B.CreateBitCast(V, Ty);
279 }
280 // Some zeros used for GEPs in lots of places.
281 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000282 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000283 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000284 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000285 llvm::LLVMContext &VMContext;
286private:
David Chisnall81a65f52011-03-26 11:48:37 +0000287 /// Placeholder for the class. Lots of things refer to the class before we've
288 /// actually emitted it. We use this alias as a placeholder, and then replace
289 /// it with a pointer to the class structure before finally emitting the
290 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000291 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000292 /// Placeholder for the metaclass. Lots of things refer to the class before
293 /// we've / actually emitted it. We use this alias as a placeholder, and then
294 /// replace / it with a pointer to the metaclass structure before finally
295 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000296 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000298 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000299 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000300 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000301 /// All of the Objective-C constant strings that have been generated for this
302 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000303 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000304 /// Map from string values to Objective-C constant strings in the output.
305 /// Used to prevent emitting Objective-C strings more than once. This should
306 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000307 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000308 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000309 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// For each variant of a selector, we store the type encoding and a
311 /// placeholder value. For an untyped selector, the type will be the empty
312 /// string. Selector references are all done via the module's selector table,
313 /// so we create an alias as a placeholder and then replace it with the real
314 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000315 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// Type of the selector map. This is roughly equivalent to the structure
317 /// used in the GNUstep runtime, which maintains a list of all of the valid
318 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000319 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000320 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000321 /// A map from selectors to selector types. This allows us to emit all
322 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000323 SelectorMap SelectorTable;
324
David Chisnall81a65f52011-03-26 11:48:37 +0000325 /// Selectors related to memory management. When compiling in GC mode, we
326 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000327 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000328 /// Runtime functions used for memory management in GC mode. Note that clang
329 /// supports code generation for calling these functions, but neither GNU
330 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000331 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
332 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000333
David Chisnall29254f42012-01-31 18:59:20 +0000334 typedef std::pair<std::string, std::string> ClassAliasPair;
335 /// All classes that have aliases set for them.
336 std::vector<ClassAliasPair> ClassAliases;
337
David Chisnall9735ca62011-03-25 11:57:33 +0000338protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000339 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000340 LazyRuntimeFunction ExceptionThrowFn;
James Dennett809d1be2012-06-13 22:07:09 +0000341 /// Function used for rethrowing exceptions, used at the end of \@finally or
342 /// \@synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000343 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000344 /// Function called when entering a catch function. This is required for
345 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000346 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000347 /// Function called when exiting from a catch block. Used to do exception
348 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000349 LazyRuntimeFunction ExitCatchFn;
James Dennett809d1be2012-06-13 22:07:09 +0000350 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000351 LazyRuntimeFunction SyncEnterFn;
James Dennett809d1be2012-06-13 22:07:09 +0000352 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000353 LazyRuntimeFunction SyncExitFn;
354
David Chisnall9735ca62011-03-25 11:57:33 +0000355private:
356
David Chisnall81a65f52011-03-26 11:48:37 +0000357 /// Function called if fast enumeration detects that the collection is
358 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000359 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000360 /// Function for implementing synthesized property getters that return an
361 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000362 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000363 /// Function for implementing synthesized property setters that return an
364 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000365 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000366 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000367 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000368 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000369 LazyRuntimeFunction SetStructPropertyFn;
370
David Chisnall81a65f52011-03-26 11:48:37 +0000371 /// The version of the runtime that this class targets. Must match the
372 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000373 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000374 /// The version of the protocol class. Used to differentiate between ObjC1
375 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
376 /// components and can not contain declared properties. We always emit
377 /// Objective-C 2 property structures, but we have to pretend that they're
378 /// Objective-C 1 property structures when targeting the GCC runtime or it
379 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000380 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000381private:
David Chisnall81a65f52011-03-26 11:48:37 +0000382 /// Generates an instance variable list structure. This is a structure
383 /// containing a size and an array of structures containing instance variable
384 /// metadata. This is used purely for introspection in the fragile ABI. In
385 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendling795b1002012-02-22 09:30:11 +0000386 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
387 ArrayRef<llvm::Constant *> IvarTypes,
388 ArrayRef<llvm::Constant *> IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000389 /// Generates a method list structure. This is a structure containing a size
390 /// and an array of structures containing method metadata.
391 ///
392 /// This structure is used by both classes and categories, and contains a next
393 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000394 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
395 const StringRef &CategoryName,
Bill Wendling795b1002012-02-22 09:30:11 +0000396 ArrayRef<Selector> MethodSels,
397 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000398 bool isClassMethodList);
James Dennett809d1be2012-06-13 22:07:09 +0000399 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall81a65f52011-03-26 11:48:37 +0000400 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
401 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000402 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000403 /// Generates a list of property metadata structures. This follows the same
404 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000405 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000406 SmallVectorImpl<Selector> &InstanceMethodSels,
407 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000408 /// Generates a list of referenced protocols. Classes, categories, and
409 /// protocols all use this structure.
Bill Wendling795b1002012-02-22 09:30:11 +0000410 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000411 /// To ensure that all protocols are seen by the runtime, we add a category on
412 /// a class defined in the runtime, declaring no methods, but adopting the
413 /// protocols. This is a horribly ugly hack, but it allows us to collect all
414 /// of the protocols without changing the ABI.
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000415 void GenerateProtocolHolderCategory();
David Chisnall81a65f52011-03-26 11:48:37 +0000416 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000417 llvm::Constant *GenerateClassStructure(
418 llvm::Constant *MetaClass,
419 llvm::Constant *SuperClass,
420 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000421 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000422 llvm::Constant *Version,
423 llvm::Constant *InstanceSize,
424 llvm::Constant *IVars,
425 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000426 llvm::Constant *Protocols,
427 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000428 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +0000429 llvm::Constant *StrongIvarBitmap,
430 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +0000431 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000432 /// Generates a method list. This is used by protocols to define the required
433 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000434 llvm::Constant *GenerateProtocolMethodList(
Bill Wendling795b1002012-02-22 09:30:11 +0000435 ArrayRef<llvm::Constant *> MethodNames,
436 ArrayRef<llvm::Constant *> MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000437 /// Returns a selector with the specified type encoding. An empty string is
438 /// used to return an untyped selector (with the types field set to NULL).
John McCallbd7370a2013-02-28 19:01:20 +0000439 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000440 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000441 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000442 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
443 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000444 /// Emits a reference to a class. This allows the linker to object if there
445 /// is no class of the matching name.
John McCallf7226fb2012-07-12 02:07:58 +0000446protected:
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000447 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000448 /// Emits a pointer to the named class
John McCallbd7370a2013-02-28 19:01:20 +0000449 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCallf7226fb2012-07-12 02:07:58 +0000450 const std::string &Name, bool isWeak);
David Chisnall81a65f52011-03-26 11:48:37 +0000451 /// Looks up the method for sending a message to the specified object. This
452 /// mechanism differs between the GCC and GNU runtimes, so this method must be
453 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000454 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
455 llvm::Value *&Receiver,
456 llvm::Value *cmd,
457 llvm::MDNode *node) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000458 /// Looks up the method for sending a message to a superclass. This
459 /// mechanism differs between the GCC and GNU runtimes, so this method must
460 /// be overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000461 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
462 llvm::Value *ObjCSuper,
463 llvm::Value *cmd) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000464 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466 /// bits set to their values, LSB first, while larger ones are stored in a
467 /// structure of this / form:
468 ///
469 /// struct { int32_t length; int32_t values[length]; };
470 ///
471 /// The values in the array are stored in host-endian format, with the least
472 /// significant bit being assumed to come first in the bitfield. Therefore,
473 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +0000475 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Chris Lattner0f984262008-03-01 08:50:34 +0000476public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000477 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
478 unsigned protocolClassVersion);
479
David Chisnall0d13f6f2010-01-23 02:40:42 +0000480 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000481
482 virtual RValue
483 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000484 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000485 QualType ResultType,
486 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000487 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000488 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000489 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000490 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000491 virtual RValue
492 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000493 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000494 QualType ResultType,
495 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000496 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000497 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000498 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000499 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000500 const CallArgList &CallArgs,
501 const ObjCMethodDecl *Method);
John McCallbd7370a2013-02-28 19:01:20 +0000502 virtual llvm::Value *GetClass(CodeGenFunction &CGF,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000503 const ObjCInterfaceDecl *OID);
John McCallbd7370a2013-02-28 19:01:20 +0000504 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000505 bool lval = false);
John McCallbd7370a2013-02-28 19:01:20 +0000506 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000507 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000508 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000509
510 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000511 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000512 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
513 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
David Chisnall29254f42012-01-31 18:59:20 +0000514 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
John McCallbd7370a2013-02-28 19:01:20 +0000515 virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000516 const ObjCProtocolDecl *PD);
517 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000518 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000519 virtual llvm::Constant *GetPropertyGetFunction();
520 virtual llvm::Constant *GetPropertySetFunction();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000521 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
522 bool copy);
David Chisnall789ecde2011-05-23 22:33:28 +0000523 virtual llvm::Constant *GetSetStructFunction();
524 virtual llvm::Constant *GetGetStructFunction();
David Chisnalld397cfe2012-12-17 18:54:24 +0000525 virtual llvm::Constant *GetCppAtomicObjectGetFunction();
526 virtual llvm::Constant *GetCppAtomicObjectSetFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000527 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000528
David Chisnall9f6614e2011-03-23 16:36:54 +0000529 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000530 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000531 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000532 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000533 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000534 const ObjCAtThrowStmt &S,
535 bool ClearInsertionPoint=true);
David Chisnall9f6614e2011-03-23 16:36:54 +0000536 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000537 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000538 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000539 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000540 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000541 llvm::Value *src, llvm::Value *dest,
542 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000543 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000544 llvm::Value *src, llvm::Value *dest,
545 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000546 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000547 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000548 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000549 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000550 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000551 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000552 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000553 QualType ObjectTy,
554 llvm::Value *BaseValue,
555 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000556 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000557 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000558 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000559 const ObjCIvarDecl *Ivar);
John McCallbd7370a2013-02-28 19:01:20 +0000560 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF);
David Chisnall9f6614e2011-03-23 16:36:54 +0000561 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000562 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000563 return NULLPtr;
564 }
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000565 virtual llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
566 const CGBlockInfo &blockInfo) {
567 return NULLPtr;
568 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +0000569
570 virtual llvm::Constant *BuildByrefLayout(CodeGenModule &CGM,
571 QualType T) {
572 return NULLPtr;
573 }
574
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000575 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
576 return 0;
577 }
Chris Lattner0f984262008-03-01 08:50:34 +0000578};
David Chisnall81a65f52011-03-26 11:48:37 +0000579/// Class representing the legacy GCC Objective-C ABI. This is the default when
580/// -fobjc-nonfragile-abi is not specified.
581///
582/// The GCC ABI target actually generates code that is approximately compatible
583/// with the new GNUstep runtime ABI, but refrains from using any features that
584/// would not work with the GCC runtime. For example, clang always generates
585/// the extended form of the class structure, and the extra fields are simply
586/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000587class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000588 /// The GCC ABI message lookup function. Returns an IMP pointing to the
589 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000590 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000591 /// The GCC ABI superclass message lookup function. Takes a pointer to a
592 /// structure describing the receiver and the class, and a selector as
593 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000594 LazyRuntimeFunction MsgLookupSuperFn;
595protected:
596 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
597 llvm::Value *&Receiver,
598 llvm::Value *cmd,
599 llvm::MDNode *node) {
600 CGBuilderTy &Builder = CGF.Builder;
David Chisnall6f3887e2011-10-28 17:55:06 +0000601 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000602 EnforceType(Builder, Receiver, IdTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000603 EnforceType(Builder, cmd, SelectorTy) };
John McCallbd7370a2013-02-28 19:01:20 +0000604 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall6f3887e2011-10-28 17:55:06 +0000605 imp->setMetadata(msgSendMDKind, node);
606 return imp.getInstruction();
David Chisnallc7ef4622011-03-23 22:52:06 +0000607 }
608 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
609 llvm::Value *ObjCSuper,
610 llvm::Value *cmd) {
611 CGBuilderTy &Builder = CGF.Builder;
612 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
613 PtrToObjCSuperTy), cmd};
John McCallbd7370a2013-02-28 19:01:20 +0000614 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000615 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000616 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000617 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
618 // IMP objc_msg_lookup(id, SEL);
619 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
620 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
621 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
622 PtrToObjCSuperTy, SelectorTy, NULL);
623 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000624};
David Chisnall81a65f52011-03-26 11:48:37 +0000625/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000626class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000627 /// The slot lookup function. Returns a pointer to a cacheable structure
628 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000629 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000630 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
631 /// a structure describing the receiver and the class, and a selector as
632 /// arguments. Returns the slot for the corresponding method. Superclass
633 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000634 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnalld397cfe2012-12-17 18:54:24 +0000635 /// Specialised function for setting atomic retain properties
636 LazyRuntimeFunction SetPropertyAtomic;
637 /// Specialised function for setting atomic copy properties
638 LazyRuntimeFunction SetPropertyAtomicCopy;
639 /// Specialised function for setting nonatomic retain properties
640 LazyRuntimeFunction SetPropertyNonAtomic;
641 /// Specialised function for setting nonatomic copy properties
642 LazyRuntimeFunction SetPropertyNonAtomicCopy;
643 /// Function to perform atomic copies of C++ objects with nontrivial copy
644 /// constructors from Objective-C ivars.
645 LazyRuntimeFunction CxxAtomicObjectGetFn;
646 /// Function to perform atomic copies of C++ objects with nontrivial copy
647 /// constructors to Objective-C ivars.
648 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000649 /// Type of an slot structure pointer. This is returned by the various
650 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000651 llvm::Type *SlotTy;
John McCall2b07dd32012-11-14 09:08:34 +0000652 public:
653 virtual llvm::Constant *GetEHType(QualType T);
David Chisnallc7ef4622011-03-23 22:52:06 +0000654 protected:
655 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
656 llvm::Value *&Receiver,
657 llvm::Value *cmd,
658 llvm::MDNode *node) {
659 CGBuilderTy &Builder = CGF.Builder;
660 llvm::Function *LookupFn = SlotLookupFn;
661
662 // Store the receiver on the stack so that we can reload it later
663 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
664 Builder.CreateStore(Receiver, ReceiverPtr);
665
666 llvm::Value *self;
667
668 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
669 self = CGF.LoadObjCSelf();
670 } else {
671 self = llvm::ConstantPointerNull::get(IdTy);
672 }
673
674 // The lookup function is guaranteed not to capture the receiver pointer.
675 LookupFn->setDoesNotCapture(1);
676
David Chisnall6f3887e2011-10-28 17:55:06 +0000677 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000678 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
679 EnforceType(Builder, cmd, SelectorTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000680 EnforceType(Builder, self, IdTy) };
John McCallbd7370a2013-02-28 19:01:20 +0000681 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall6f3887e2011-10-28 17:55:06 +0000682 slot.setOnlyReadsMemory();
David Chisnallc7ef4622011-03-23 22:52:06 +0000683 slot->setMetadata(msgSendMDKind, node);
684
685 // Load the imp from the slot
David Chisnall6f3887e2011-10-28 17:55:06 +0000686 llvm::Value *imp =
687 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnallc7ef4622011-03-23 22:52:06 +0000688
689 // The lookup function may have changed the receiver, so make sure we use
690 // the new one.
691 Receiver = Builder.CreateLoad(ReceiverPtr, true);
692 return imp;
693 }
694 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
695 llvm::Value *ObjCSuper,
696 llvm::Value *cmd) {
697 CGBuilderTy &Builder = CGF.Builder;
698 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
699
John McCallbd7370a2013-02-28 19:01:20 +0000700 llvm::CallInst *slot =
701 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000702 slot->setOnlyReadsMemory();
703
704 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
705 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000706 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000707 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallde38cb12013-02-28 13:59:29 +0000708 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000709
Chris Lattner7650d952011-06-18 22:49:11 +0000710 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000711 PtrTy, PtrTy, IntTy, IMPTy, NULL);
712 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
713 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
714 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
715 SelectorTy, IdTy, NULL);
716 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
717 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
718 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000719 // If we're in ObjC++ mode, then we want to make
David Blaikie4e4d0842012-03-11 07:00:24 +0000720 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000721 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000722 // void *__cxa_begin_catch(void *e)
723 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
724 // void __cxa_end_catch(void)
David Chisnall4bd5d092011-08-08 17:26:06 +0000725 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000726 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnalld397cfe2012-12-17 18:54:24 +0000727 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
728 PtrTy, NULL);
David Chisnall65bd4ac2013-01-11 15:33:01 +0000729 } else if (R.getVersion() >= VersionTuple(1, 7)) {
730 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
731 // id objc_begin_catch(void *e)
732 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, NULL);
733 // void objc_end_catch(void)
734 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, NULL);
735 // void _Unwind_Resume_or_Rethrow(void*)
736 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
737 PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000738 }
David Chisnalld397cfe2012-12-17 18:54:24 +0000739 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
740 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
741 SelectorTy, IdTy, PtrDiffTy, NULL);
742 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
743 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
744 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
745 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
746 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
747 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
748 // void objc_setCppObjectAtomic(void *dest, const void *src, void
749 // *helper);
750 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
751 PtrTy, PtrTy, NULL);
752 // void objc_getCppObjectAtomic(void *dest, const void *src, void
753 // *helper);
754 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
755 PtrTy, PtrTy, NULL);
756 }
757 virtual llvm::Constant *GetCppAtomicObjectGetFunction() {
758 // The optimised functions were added in version 1.7 of the GNUstep
759 // runtime.
760 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
761 VersionTuple(1, 7));
762 return CxxAtomicObjectGetFn;
763 }
764 virtual llvm::Constant *GetCppAtomicObjectSetFunction() {
765 // The optimised functions were added in version 1.7 of the GNUstep
766 // runtime.
767 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
768 VersionTuple(1, 7));
769 return CxxAtomicObjectSetFn;
770 }
771 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
772 bool copy) {
773 // The optimised property functions omit the GC check, and so are not
774 // safe to use in GC mode. The standard functions are fast in GC mode,
775 // so there is less advantage in using them.
776 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
777 // The optimised functions were added in version 1.7 of the GNUstep
778 // runtime.
779 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
780 VersionTuple(1, 7));
781
782 if (atomic) {
783 if (copy) return SetPropertyAtomicCopy;
784 return SetPropertyAtomic;
785 }
786 if (copy) return SetPropertyNonAtomicCopy;
787 return SetPropertyNonAtomic;
788
789 return 0;
David Chisnallc7ef4622011-03-23 22:52:06 +0000790 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000791};
792
John McCall0a7dd782012-08-21 02:47:43 +0000793/// Support for the ObjFW runtime. Support here is due to
794/// Jonathan Schleifer <js@webkeks.org>, the ObjFW maintainer.
795class CGObjCObjFW: public CGObjCGNU {
796protected:
797 /// The GCC ABI message lookup function. Returns an IMP pointing to the
798 /// method implementation for this message.
799 LazyRuntimeFunction MsgLookupFn;
800 /// The GCC ABI superclass message lookup function. Takes a pointer to a
801 /// structure describing the receiver and the class, and a selector as
802 /// arguments. Returns the IMP for the corresponding method.
803 LazyRuntimeFunction MsgLookupSuperFn;
804
805 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
806 llvm::Value *&Receiver,
807 llvm::Value *cmd,
808 llvm::MDNode *node) {
809 CGBuilderTy &Builder = CGF.Builder;
810 llvm::Value *args[] = {
811 EnforceType(Builder, Receiver, IdTy),
812 EnforceType(Builder, cmd, SelectorTy) };
John McCallbd7370a2013-02-28 19:01:20 +0000813 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
John McCall0a7dd782012-08-21 02:47:43 +0000814 imp->setMetadata(msgSendMDKind, node);
815 return imp.getInstruction();
816 }
817
818 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
819 llvm::Value *ObjCSuper,
820 llvm::Value *cmd) {
821 CGBuilderTy &Builder = CGF.Builder;
822 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
823 PtrToObjCSuperTy), cmd};
John McCallbd7370a2013-02-28 19:01:20 +0000824 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
John McCall0a7dd782012-08-21 02:47:43 +0000825 }
826
John McCallbd7370a2013-02-28 19:01:20 +0000827 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCallf7226fb2012-07-12 02:07:58 +0000828 const std::string &Name, bool isWeak) {
829 if (isWeak)
John McCallbd7370a2013-02-28 19:01:20 +0000830 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCallf7226fb2012-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,
841 0, SymbolName);
842
843 return ClassSymbol;
844 }
845
846public:
John McCall0a7dd782012-08-21 02:47:43 +0000847 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
848 // IMP objc_msg_lookup(id, SEL);
849 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
850 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
851 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
852 PtrToObjCSuperTy, SelectorTy, NULL);
853 }
John McCallf7226fb2012-07-12 02:07:58 +0000854};
Chris Lattner0f984262008-03-01 08:50:34 +0000855} // end anonymous namespace
856
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000857
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000858/// Emits a reference to a dummy variable which is emitted with each class.
859/// This ensures that a linker error will be generated when trying to link
860/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000861void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000862 std::string symbolRef = "__objc_class_ref_" + className;
863 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000864 if (TheModule.getGlobalVariable(symbolRef))
865 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000866 std::string symbolName = "__objc_class_name_" + className;
867 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
868 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000869 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
870 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000871 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000872 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000873 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000874}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000875
Chris Lattner5f9e2722011-07-23 10:55:15 +0000876static std::string SymbolNameForMethod(const StringRef &ClassName,
877 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000878 bool isClassMethod) {
879 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000880 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
881 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000882 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000883 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000884}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000885
David Chisnall9f6614e2011-03-23 16:36:54 +0000886CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
887 unsigned protocolClassVersion)
John McCallde5d3c72012-02-17 03:33:10 +0000888 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
889 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
890 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000891
892 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
893
David Chisnall9f6614e2011-03-23 16:36:54 +0000894 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000895 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000896 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000897 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000898 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000899 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000900 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000901 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000902 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000903 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000905 Int8Ty = llvm::Type::getInt8Ty(VMContext);
906 // C string type. Used in lots of places.
907 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
908
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000909 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000910 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000911 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000912 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000913 QualType selTy = CGM.getContext().getObjCSelType();
914 if (QualType() == selTy) {
915 SelectorTy = PtrToInt8Ty;
916 } else {
917 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
918 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000919
Owen Anderson96e0fc72009-07-29 22:16:19 +0000920 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000921 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
David Chisnall917b28b2011-10-04 15:35:30 +0000923 Int32Ty = llvm::Type::getInt32Ty(VMContext);
924 Int64Ty = llvm::Type::getInt64Ty(VMContext);
925
David Chisnall49de5282011-10-08 08:54:36 +0000926 IntPtrTy =
927 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
928
Chris Lattner391d77a2008-03-30 23:03:07 +0000929 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000930 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
931 ASTIdTy = CanQualType();
932 if (UnqualIdTy != QualType()) {
933 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000934 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000935 } else {
936 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000937 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000938 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner7650d952011-06-18 22:49:11 +0000940 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000941 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
942
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000943 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000944
945 // void objc_exception_throw(id);
946 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000947 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000948 // int objc_sync_enter(id);
949 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
950 // int objc_sync_exit(id);
951 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
952
953 // void objc_enumerationMutation (id)
954 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
955 IdTy, NULL);
956
957 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
958 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
959 PtrDiffTy, BoolTy, NULL);
960 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
961 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
962 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
963 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
964 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
965 PtrDiffTy, BoolTy, BoolTy, NULL);
966 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
967 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
968 PtrDiffTy, BoolTy, BoolTy, NULL);
969
Chris Lattner391d77a2008-03-30 23:03:07 +0000970 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000971 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000972 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
973 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000974
David Blaikie4e4d0842012-03-11 07:00:24 +0000975 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregore289d812011-09-13 17:21:33 +0000976 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +0000977 RuntimeVersion = 10;
978
David Chisnall9735ca62011-03-25 11:57:33 +0000979 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +0000980 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000981 // This is a bit of an hack. We should sort this out by having a proper
982 // CGObjCGNUstep subclass for GC, but we may want to really support the old
983 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000984 // Get selectors needed in GC mode
985 RetainSel = GetNullarySelector("retain", CGM.getContext());
986 ReleaseSel = GetNullarySelector("release", CGM.getContext());
987 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
988
989 // Get functions needed in GC mode
990
991 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000992 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
993 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000994 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000995 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
996 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000997 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000998 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
999 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001000 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +00001001 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001002 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +00001003 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001004 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +00001005 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1006 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001007 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001008}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001009
John McCallbd7370a2013-02-28 19:01:20 +00001010llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
David Chisnalld3fc7292011-06-30 10:14:37 +00001011 const std::string &Name,
1012 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +00001013 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +00001014 // With the incompatible ABI, this will need to be replaced with a direct
1015 // reference to the class symbol. For the compatible nonfragile ABI we are
1016 // still performing this lookup at run time but emitting the symbol for the
1017 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +00001018 //
1019 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1020 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +00001021 if (!isWeak)
1022 EmitClassRef(Name);
John McCallbd7370a2013-02-28 19:01:20 +00001023 ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001024
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001025 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +00001026 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001027 "objc_lookup_class");
John McCallbd7370a2013-02-28 19:01:20 +00001028 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +00001029}
1030
David Chisnallc7aed3b2011-06-29 13:16:41 +00001031// This has to perform the lookup every time, since posing and related
1032// techniques can modify the name -> class mapping.
John McCallbd7370a2013-02-28 19:01:20 +00001033llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnallc7aed3b2011-06-29 13:16:41 +00001034 const ObjCInterfaceDecl *OID) {
John McCallbd7370a2013-02-28 19:01:20 +00001035 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +00001036}
John McCallbd7370a2013-02-28 19:01:20 +00001037llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1038 return GetClassNamed(CGF, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +00001039}
1040
John McCallbd7370a2013-02-28 19:01:20 +00001041llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +00001042 const std::string &TypeEncoding, bool lval) {
1043
Chris Lattner5f9e2722011-07-23 10:55:15 +00001044 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +00001045 llvm::GlobalAlias *SelValue = 0;
1046
1047
Chris Lattner5f9e2722011-07-23 10:55:15 +00001048 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00001049 e = Types.end() ; i!=e ; i++) {
1050 if (i->first == TypeEncoding) {
1051 SelValue = i->second;
1052 break;
1053 }
1054 }
1055 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +00001056 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +00001057 llvm::GlobalValue::PrivateLinkage,
1058 ".objc_selector_"+Sel.getAsString(), NULL,
1059 &TheModule);
1060 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1061 }
1062
David Chisnallc7ef4622011-03-23 22:52:06 +00001063 if (lval) {
John McCallbd7370a2013-02-28 19:01:20 +00001064 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1065 CGF.Builder.CreateStore(SelValue, tmp);
David Chisnallc7ef4622011-03-23 22:52:06 +00001066 return tmp;
1067 }
1068 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +00001069}
1070
John McCallbd7370a2013-02-28 19:01:20 +00001071llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +00001072 bool lval) {
John McCallbd7370a2013-02-28 19:01:20 +00001073 return GetSelector(CGF, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001074}
1075
John McCallbd7370a2013-02-28 19:01:20 +00001076llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1077 const ObjCMethodDecl *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001078 std::string SelTypes;
1079 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCallbd7370a2013-02-28 19:01:20 +00001080 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +00001081}
1082
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00001083llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCall2b07dd32012-11-14 09:08:34 +00001084 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1085 // With the old ABI, there was only one kind of catchall, which broke
1086 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1087 // a pointer indicating object catchalls, and NULL to indicate real
1088 // catchalls
1089 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1090 return MakeConstantString("@id");
1091 } else {
1092 return 0;
1093 }
David Chisnall9735ca62011-03-25 11:57:33 +00001094 }
John McCall2b07dd32012-11-14 09:08:34 +00001095
1096 // All other types should be Objective-C interface pointer types.
1097 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1098 assert(OPT && "Invalid @catch type.");
1099 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1100 assert(IDecl && "Invalid @catch type.");
1101 return MakeConstantString(IDecl->getIdentifier()->getName());
1102}
1103
1104llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1105 if (!CGM.getLangOpts().CPlusPlus)
1106 return CGObjCGNU::GetEHType(T);
1107
David Chisnall80558d22011-03-20 21:35:39 +00001108 // For Objective-C++, we want to provide the ability to catch both C++ and
1109 // Objective-C objects in the same function.
1110
1111 // There's a particular fixed type info for 'id'.
1112 if (T->isObjCIdType() ||
1113 T->isObjCQualifiedIdType()) {
1114 llvm::Constant *IDEHType =
1115 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1116 if (!IDEHType)
1117 IDEHType =
1118 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1119 false,
1120 llvm::GlobalValue::ExternalLinkage,
1121 0, "__objc_id_type_info");
1122 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1123 }
1124
1125 const ObjCObjectPointerType *PT =
1126 T->getAs<ObjCObjectPointerType>();
1127 assert(PT && "Invalid @catch type.");
1128 const ObjCInterfaceType *IT = PT->getInterfaceType();
1129 assert(IT && "Invalid @catch type.");
1130 std::string className = IT->getDecl()->getIdentifier()->getName();
1131
1132 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1133
1134 // Return the existing typeinfo if it exists
1135 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnallacd76fe2012-03-20 16:25:52 +00001136 if (typeinfo)
1137 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnall80558d22011-03-20 21:35:39 +00001138
1139 // Otherwise create it.
1140
1141 // vtable for gnustep::libobjc::__objc_class_type_info
1142 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1143 // platform's name mangling.
1144 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1145 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1146 if (!Vtable) {
1147 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1148 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1149 }
1150 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +00001151 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +00001152 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1153
1154 llvm::Constant *typeName =
1155 ExportUniqueString(className, "__objc_eh_typename_");
1156
1157 std::vector<llvm::Constant*> fields;
1158 fields.push_back(Vtable);
1159 fields.push_back(typeName);
1160 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +00001161 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +00001162 NULL), fields, "__objc_eh_typeinfo_" + className,
1163 llvm::GlobalValue::LinkOnceODRLinkage);
1164 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +00001165}
1166
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001167/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +00001168llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +00001169
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001170 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +00001171
David Chisnall48272a02010-01-27 12:49:23 +00001172 // Look for an existing one
1173 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1174 if (old != ObjCStrings.end())
1175 return old->getValue();
1176
David Blaikie4e4d0842012-03-11 07:00:24 +00001177 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall13df6f62012-01-04 12:02:13 +00001178
1179 if (StringClass.empty()) StringClass = "NXConstantString";
1180
1181 std::string Sym = "_OBJC_CLASS_";
1182 Sym += StringClass;
1183
1184 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1185
1186 if (!isa)
1187 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1188 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1189 else if (isa->getType() != PtrToIdTy)
1190 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1191
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001192 std::vector<llvm::Constant*> Ivars;
David Chisnall13df6f62012-01-04 12:02:13 +00001193 Ivars.push_back(isa);
Chris Lattner13fd7e52008-06-21 21:44:18 +00001194 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001195 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001196 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall13df6f62012-01-04 12:02:13 +00001197 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001198 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +00001199 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1200 ObjCStrings[Str] = ObjCStr;
1201 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001202 return ObjCStr;
1203}
1204
1205///Generates a message send where the super is the receiver. This is a message
1206///send to self with special delivery semantics indicating which class's method
1207///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +00001208RValue
1209CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001210 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001211 QualType ResultType,
1212 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001213 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001214 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001215 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001216 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001217 const CallArgList &CallArgs,
1218 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001219 CGBuilderTy &Builder = CGF.Builder;
David Blaikie4e4d0842012-03-11 07:00:24 +00001220 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001221 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001222 return RValue::get(EnforceType(Builder, Receiver,
1223 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001224 }
1225 if (Sel == ReleaseSel) {
1226 return RValue::get(0);
1227 }
1228 }
David Chisnalldb831942010-05-01 12:37:16 +00001229
John McCallbd7370a2013-02-28 19:01:20 +00001230 llvm::Value *cmd = GetSelector(CGF, Sel);
David Chisnalldb831942010-05-01 12:37:16 +00001231
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001232
1233 CallArgList ActualArgs;
1234
Eli Friedman04c9a492011-05-02 17:57:46 +00001235 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1236 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001237 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001238
John McCallde5d3c72012-02-17 03:33:10 +00001239 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001240
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001241 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001242 if (isCategoryImpl) {
1243 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001244 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001245 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001246 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001247 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001248 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001249 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001250 }
David Chisnalldb831942010-05-01 12:37:16 +00001251 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001252 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001253 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001254 // Set up global aliases for the metaclass or class pointer if they do not
1255 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001256 // pointers to the class and metaclass structure created for the runtime
1257 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001258 // super_class pointer from either the class or metaclass structure.
1259 if (IsClassMessage) {
1260 if (!MetaClassPtrAlias) {
1261 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1262 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1263 Class->getNameAsString(), NULL, &TheModule);
1264 }
1265 ReceiverClass = MetaClassPtrAlias;
1266 } else {
1267 if (!ClassPtrAlias) {
1268 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1269 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1270 Class->getNameAsString(), NULL, &TheModule);
1271 }
1272 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001273 }
Chris Lattner71238f62009-04-25 23:19:45 +00001274 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001275 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001276 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001277 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001278 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001279 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001280 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001281 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001282 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001283 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001284 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001285 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001286 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001287
David Chisnalldb831942010-05-01 12:37:16 +00001288 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1289 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001290
David Chisnallc7ef4622011-03-23 22:52:06 +00001291 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnallc7ef4622011-03-23 22:52:06 +00001292
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001293 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001294 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
John McCallde5d3c72012-02-17 03:33:10 +00001295 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001296
David Chisnalldd5c98f2010-05-01 11:15:56 +00001297 llvm::Value *impMD[] = {
1298 llvm::MDString::get(VMContext, Sel.getAsString()),
1299 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1300 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1301 };
Jay Foad6f141652011-04-21 19:59:12 +00001302 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001303
David Chisnall4b02afc2010-05-02 13:41:58 +00001304 llvm::Instruction *call;
John McCallde5d3c72012-02-17 03:33:10 +00001305 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnall4b02afc2010-05-02 13:41:58 +00001306 call->setMetadata(msgSendMDKind, node);
1307 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001308}
1309
Mike Stump1eb44332009-09-09 15:08:12 +00001310/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001311RValue
1312CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001313 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001314 QualType ResultType,
1315 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001316 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001317 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001318 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001319 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001320 CGBuilderTy &Builder = CGF.Builder;
1321
David Chisnall664b7c72010-04-27 15:08:48 +00001322 // Strip out message sends to retain / release in GC mode
David Blaikie4e4d0842012-03-11 07:00:24 +00001323 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001324 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001325 return RValue::get(EnforceType(Builder, Receiver,
1326 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001327 }
1328 if (Sel == ReleaseSel) {
1329 return RValue::get(0);
1330 }
1331 }
David Chisnall664b7c72010-04-27 15:08:48 +00001332
David Chisnall664b7c72010-04-27 15:08:48 +00001333 // If the return type is something that goes in an integer register, the
1334 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1335 // ourselves.
1336 //
1337 // The language spec says the result of this kind of message send is
1338 // undefined, but lots of people seem to have forgotten to read that
1339 // paragraph and insist on sending messages to nil that have structure
1340 // returns. With GCC, this generates a random return value (whatever happens
1341 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001342 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1343 // the stack.
1344 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1345 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001346
1347 llvm::BasicBlock *startBB = 0;
1348 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001349 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001350
1351 if (!isPointerSizedReturn) {
1352 startBB = Builder.GetInsertBlock();
1353 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001354 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001355
1356 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1357 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001358 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001359 CGF.EmitBlock(messageBB);
1360 }
1361
David Chisnall0f436562009-08-17 16:35:33 +00001362 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001363 llvm::Value *cmd;
1364 if (Method)
John McCallbd7370a2013-02-28 19:01:20 +00001365 cmd = GetSelector(CGF, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001366 else
John McCallbd7370a2013-02-28 19:01:20 +00001367 cmd = GetSelector(CGF, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001368 cmd = EnforceType(Builder, cmd, SelectorTy);
1369 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001370
David Chisnallc7ef4622011-03-23 22:52:06 +00001371 llvm::Value *impMD[] = {
1372 llvm::MDString::get(VMContext, Sel.getAsString()),
1373 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1374 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1375 };
Jay Foad6f141652011-04-21 19:59:12 +00001376 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001377
David Chisnallc7ef4622011-03-23 22:52:06 +00001378 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001379 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1380 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001381 ActualArgs.addFrom(CallArgs);
John McCallde5d3c72012-02-17 03:33:10 +00001382
1383 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1384
David Chisnall89c30042011-10-24 14:07:03 +00001385 // Get the IMP to call
1386 llvm::Value *imp;
1387
1388 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1389 // functions. These are not supported on all platforms (or all runtimes on a
1390 // given platform), so we
1391 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall89c30042011-10-24 14:07:03 +00001392 case CodeGenOptions::Legacy:
David Chisnall89c30042011-10-24 14:07:03 +00001393 imp = LookupIMP(CGF, Receiver, cmd, node);
1394 break;
1395 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001396 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001397 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1398 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1399 "objc_msgSend_fpret");
John McCallde5d3c72012-02-17 03:33:10 +00001400 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall89c30042011-10-24 14:07:03 +00001401 // The actual types here don't matter - we're going to bitcast the
1402 // function anyway
1403 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1404 "objc_msgSend_stret");
1405 } else {
1406 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1407 "objc_msgSend");
1408 }
1409 }
1410
David Chisnall403bc3f2011-12-01 18:40:09 +00001411 // Reset the receiver in case the lookup modified it
1412 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001413
John McCallde5d3c72012-02-17 03:33:10 +00001414 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnall63e742b2010-05-01 12:56:56 +00001415
David Chisnall4b02afc2010-05-02 13:41:58 +00001416 llvm::Instruction *call;
John McCallde5d3c72012-02-17 03:33:10 +00001417 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001418 0, &call);
1419 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001420
David Chisnalla54da052010-05-20 13:45:48 +00001421
David Chisnall664b7c72010-04-27 15:08:48 +00001422 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001423 messageBB = CGF.Builder.GetInsertBlock();
1424 CGF.Builder.CreateBr(continueBB);
1425 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001426 if (msgRet.isScalar()) {
1427 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001428 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001429 phi->addIncoming(v, messageBB);
1430 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1431 msgRet = RValue::get(phi);
1432 } else if (msgRet.isAggregate()) {
1433 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001434 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001435 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001436 llvm::AllocaInst *NullVal =
1437 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001438 CGF.InitTempAlloca(NullVal,
1439 llvm::Constant::getNullValue(RetTy->getElementType()));
1440 phi->addIncoming(v, messageBB);
1441 phi->addIncoming(NullVal, startBB);
1442 msgRet = RValue::getAggregate(phi);
1443 } else /* isComplex() */ {
1444 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001445 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001446 phi->addIncoming(v.first, messageBB);
1447 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1448 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001449 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001450 phi2->addIncoming(v.second, messageBB);
1451 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1452 startBB);
1453 msgRet = RValue::getComplex(phi, phi2);
1454 }
1455 }
1456 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001457}
1458
Mike Stump1eb44332009-09-09 15:08:12 +00001459/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001460/// objc_category structures.
Bill Wendling795b1002012-02-22 09:30:11 +00001461llvm::Constant *CGObjCGNU::
1462GenerateMethodList(const StringRef &ClassName,
1463 const StringRef &CategoryName,
1464 ArrayRef<Selector> MethodSels,
1465 ArrayRef<llvm::Constant *> MethodTypes,
1466 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001467 if (MethodSels.empty())
1468 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001469 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001470 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001471 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1472 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001473 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001474 NULL);
1475 std::vector<llvm::Constant*> Methods;
1476 std::vector<llvm::Constant*> Elements;
1477 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1478 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001479 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001480 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001481 MethodSels[i],
1482 isClassMethodList));
1483 assert(Method && "Can't generate metadata for method that doesn't exist");
1484 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1485 Elements.push_back(C);
1486 Elements.push_back(MethodTypes[i]);
1487 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001488 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001489 Elements.push_back(Method);
1490 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001491 }
1492
1493 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001494 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001495 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001496 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001497 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001498
1499 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001500 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001501 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1502 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001503 NextPtrTy,
1504 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001505 ObjCMethodArrayTy,
1506 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001507
1508 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001509 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001510 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001511 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001512 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001514 // Create an instance of the structure
1515 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1516}
1517
1518/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendling795b1002012-02-22 09:30:11 +00001519llvm::Constant *CGObjCGNU::
1520GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1521 ArrayRef<llvm::Constant *> IvarTypes,
1522 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001523 if (IvarNames.size() == 0)
1524 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001525 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001526 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001527 PtrToInt8Ty,
1528 PtrToInt8Ty,
1529 IntTy,
1530 NULL);
1531 std::vector<llvm::Constant*> Ivars;
1532 std::vector<llvm::Constant*> Elements;
1533 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1534 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001535 Elements.push_back(IvarNames[i]);
1536 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001537 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001538 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001539 }
1540
1541 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001542 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001543 IvarNames.size());
1544
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001546 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001547 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001548 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001549 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001550 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001551 ObjCIvarArrayTy,
1552 NULL);
1553
1554 // Create an instance of the structure
1555 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1556}
1557
1558/// Generate a class structure
1559llvm::Constant *CGObjCGNU::GenerateClassStructure(
1560 llvm::Constant *MetaClass,
1561 llvm::Constant *SuperClass,
1562 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001563 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001564 llvm::Constant *Version,
1565 llvm::Constant *InstanceSize,
1566 llvm::Constant *IVars,
1567 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001568 llvm::Constant *Protocols,
1569 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001570 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001571 llvm::Constant *StrongIvarBitmap,
1572 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001573 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001574 // Set up the class structure
1575 // Note: Several of these are char*s when they should be ids. This is
1576 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001577 //
1578 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1579 // anyway; the classes will still work with the GNU runtime, they will just
1580 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001581 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001582 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001583 PtrToInt8Ty, // super_class
1584 PtrToInt8Ty, // name
1585 LongTy, // version
1586 LongTy, // info
1587 LongTy, // instance_size
1588 IVars->getType(), // ivars
1589 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001590 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001591 PtrTy, // dtable
1592 PtrTy, // subclass_list
1593 PtrTy, // sibling_class
1594 PtrTy, // protocols
1595 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001596 // New ABI:
1597 LongTy, // abi_version
1598 IvarOffsets->getType(), // ivar_offsets
1599 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001600 IntPtrTy, // strong_pointers
1601 IntPtrTy, // weak_pointers
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001602 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001603 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001604 // Fill in the structure
1605 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001606 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001607 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001608 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001609 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001610 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001611 if (isMeta) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001612 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001613 Elements.push_back(
1614 llvm::ConstantInt::get(LongTy,
1615 td.getTypeSizeInBits(ClassTy) /
1616 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001617 } else
1618 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001619 Elements.push_back(IVars);
1620 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001621 Elements.push_back(NULLPtr);
1622 Elements.push_back(NULLPtr);
1623 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001624 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001625 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001626 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001627 Elements.push_back(IvarOffsets);
1628 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001629 Elements.push_back(StrongIvarBitmap);
1630 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001631 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001632 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001633 // messages in the next ABI. We may already have some weak references to
1634 // this, so check and fix them properly.
1635 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1636 std::string(Name));
1637 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1638 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1639 llvm::GlobalValue::ExternalLinkage);
1640 if (ClassRef) {
1641 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1642 ClassRef->getType()));
1643 ClassRef->removeFromParent();
1644 Class->setName(ClassSym);
1645 }
1646 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001647}
1648
Bill Wendling795b1002012-02-22 09:30:11 +00001649llvm::Constant *CGObjCGNU::
1650GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1651 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001652 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001653 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001654 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1655 PtrToInt8Ty,
1656 NULL);
1657 std::vector<llvm::Constant*> Methods;
1658 std::vector<llvm::Constant*> Elements;
1659 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1660 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001661 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001662 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001663 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001664 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001665 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001666 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001667 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001668 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001669 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001670 IntTy, ObjCMethodArrayTy, NULL);
1671 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001672 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001673 Methods.push_back(Array);
1674 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1675}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001676
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001677// Create the protocol list structure used in classes, categories and so on
Bill Wendling795b1002012-02-22 09:30:11 +00001678llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson96e0fc72009-07-29 22:16:19 +00001679 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001680 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001681 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001682 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001683 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001684 ProtocolArrayTy,
1685 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001686 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001687 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1688 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001689 llvm::Constant *protocol = 0;
1690 llvm::StringMap<llvm::Constant*>::iterator value =
1691 ExistingProtocols.find(*iter);
1692 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001693 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001694 } else {
1695 protocol = value->getValue();
1696 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001697 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001698 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001699 Elements.push_back(Ptr);
1700 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001701 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001702 Elements);
1703 Elements.clear();
1704 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001705 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001706 Elements.push_back(ProtocolArray);
1707 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1708}
1709
John McCallbd7370a2013-02-28 19:01:20 +00001710llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001711 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001712 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001713 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001714 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCallbd7370a2013-02-28 19:01:20 +00001715 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001716}
1717
1718llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1719 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001720 SmallVector<std::string, 0> EmptyStringVector;
1721 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001722
1723 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001724 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001725 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1726 // Protocols are objects containing lists of the methods implemented and
1727 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001728 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001729 PtrToInt8Ty,
1730 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001731 MethodList->getType(),
1732 MethodList->getType(),
1733 MethodList->getType(),
1734 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001735 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001736 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001737 // The isa pointer must be set to a magic number so the runtime knows it's
1738 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001739 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001740 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001741 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1742 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001743 Elements.push_back(MethodList);
1744 Elements.push_back(MethodList);
1745 Elements.push_back(MethodList);
1746 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001747 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001748}
1749
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001750void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1751 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001752 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001753
1754 // Use the protocol definition, if there is one.
1755 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1756 PD = Def;
1757
Chris Lattner5f9e2722011-07-23 10:55:15 +00001758 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001759 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1760 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001761 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001762 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1763 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1764 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1765 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001766 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1767 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001768 std::string TypeStr;
1769 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001770 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001771 OptionalInstanceMethodNames.push_back(
1772 MakeConstantString((*iter)->getSelector().getAsString()));
1773 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001774 } else {
1775 InstanceMethodNames.push_back(
1776 MakeConstantString((*iter)->getSelector().getAsString()));
1777 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001778 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001779 }
1780 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001781 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1782 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1783 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1784 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001785 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001786 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1787 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001788 std::string TypeStr;
1789 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001790 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001791 OptionalClassMethodNames.push_back(
1792 MakeConstantString((*iter)->getSelector().getAsString()));
1793 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001794 } else {
1795 ClassMethodNames.push_back(
1796 MakeConstantString((*iter)->getSelector().getAsString()));
1797 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001798 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001799 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001800
1801 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1802 llvm::Constant *InstanceMethodList =
1803 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1804 llvm::Constant *ClassMethodList =
1805 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001806 llvm::Constant *OptionalInstanceMethodList =
1807 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1808 OptionalInstanceMethodTypes);
1809 llvm::Constant *OptionalClassMethodList =
1810 GenerateProtocolMethodList(OptionalClassMethodNames,
1811 OptionalClassMethodTypes);
1812
1813 // Property metadata: name, attributes, isSynthesized, setter name, setter
1814 // types, getter name, getter types.
1815 // The isSynthesized value is always set to 0 in a protocol. It exists to
1816 // simplify the runtime library by allowing it to use the same data
1817 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001818 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00001819 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1820 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001821 std::vector<llvm::Constant*> Properties;
1822 std::vector<llvm::Constant*> OptionalProperties;
1823
1824 // Add all of the property methods need adding to the method list and to the
1825 // property metadata list.
1826 for (ObjCContainerDecl::prop_iterator
1827 iter = PD->prop_begin(), endIter = PD->prop_end();
1828 iter != endIter ; iter++) {
1829 std::vector<llvm::Constant*> Fields;
David Blaikie581deb32012-06-06 20:45:41 +00001830 ObjCPropertyDecl *property = *iter;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001831
David Chisnallde38cb12013-02-28 13:59:29 +00001832 Fields.push_back(MakePropertyEncodingString(property, 0));
1833 PushPropertyAttributes(Fields, property);
David Chisnall891dac72012-10-16 15:11:55 +00001834
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001835 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1836 std::string TypeStr;
1837 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1838 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1839 InstanceMethodTypes.push_back(TypeEncoding);
1840 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1841 Fields.push_back(TypeEncoding);
1842 } else {
1843 Fields.push_back(NULLPtr);
1844 Fields.push_back(NULLPtr);
1845 }
1846 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1847 std::string TypeStr;
1848 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1849 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1850 InstanceMethodTypes.push_back(TypeEncoding);
1851 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1852 Fields.push_back(TypeEncoding);
1853 } else {
1854 Fields.push_back(NULLPtr);
1855 Fields.push_back(NULLPtr);
1856 }
1857 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1858 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1859 } else {
1860 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1861 }
1862 }
1863 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1864 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1865 llvm::Constant* PropertyListInitFields[] =
1866 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1867
1868 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001869 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001870 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1871 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1872 PropertyListInit, ".objc_property_list");
1873
1874 llvm::Constant *OptionalPropertyArray =
1875 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1876 OptionalProperties.size()) , OptionalProperties);
1877 llvm::Constant* OptionalPropertyListInitFields[] = {
1878 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1879 OptionalPropertyArray };
1880
1881 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001882 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001883 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1884 OptionalPropertyListInit->getType(), false,
1885 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1886 ".objc_property_list");
1887
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001888 // Protocols are objects containing lists of the methods implemented and
1889 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001890 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001891 PtrToInt8Ty,
1892 ProtocolList->getType(),
1893 InstanceMethodList->getType(),
1894 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001895 OptionalInstanceMethodList->getType(),
1896 OptionalClassMethodList->getType(),
1897 PropertyList->getType(),
1898 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001899 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001900 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001901 // The isa pointer must be set to a magic number so the runtime knows it's
1902 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001903 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001904 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001905 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1906 Elements.push_back(ProtocolList);
1907 Elements.push_back(InstanceMethodList);
1908 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001909 Elements.push_back(OptionalInstanceMethodList);
1910 Elements.push_back(OptionalClassMethodList);
1911 Elements.push_back(PropertyList);
1912 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001913 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001914 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001915 ".objc_protocol"), IdTy);
1916}
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +00001917void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001918 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001919 SmallVector<Selector, 1> MethodSels;
1920 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001921
1922 std::vector<llvm::Constant*> Elements;
1923 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1924 const std::string CategoryName = "AnotherHack";
1925 Elements.push_back(MakeConstantString(CategoryName));
1926 Elements.push_back(MakeConstantString(ClassName));
1927 // Instance method list
1928 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1929 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1930 // Class method list
1931 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1932 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1933 // Protocol list
1934 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1935 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001936 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001937 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001938 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001939 ProtocolArrayTy,
1940 NULL);
1941 std::vector<llvm::Constant*> ProtocolElements;
1942 for (llvm::StringMapIterator<llvm::Constant*> iter =
1943 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1944 iter != endIter ; iter++) {
1945 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1946 PtrTy);
1947 ProtocolElements.push_back(Ptr);
1948 }
1949 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1950 ProtocolElements);
1951 ProtocolElements.clear();
1952 ProtocolElements.push_back(NULLPtr);
1953 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1954 ExistingProtocols.size()));
1955 ProtocolElements.push_back(ProtocolArray);
1956 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1957 ProtocolElements, ".objc_protocol_list"), PtrTy));
1958 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001959 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001960 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1961}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001962
David Chisnall917b28b2011-10-04 15:35:30 +00001963/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1964/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1965/// bits set to their values, LSB first, while larger ones are stored in a
1966/// structure of this / form:
1967///
1968/// struct { int32_t length; int32_t values[length]; };
1969///
1970/// The values in the array are stored in host-endian format, with the least
1971/// significant bit being assumed to come first in the bitfield. Therefore, a
1972/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1973/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +00001974llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001975 int bitCount = bits.size();
David Chisnall9d06ba82011-10-25 10:12:21 +00001976 int ptrBits =
1977 (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
1978 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001979 uint64_t val = 1;
1980 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001981 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001982 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001983 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001984 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001985 SmallVector<llvm::Constant *, 8> values;
David Chisnall917b28b2011-10-04 15:35:30 +00001986 int v=0;
1987 while (v < bitCount) {
1988 int32_t word = 0;
1989 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1990 if (bits[v]) word |= 1<<i;
1991 v++;
1992 }
1993 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1994 }
1995 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1996 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1997 llvm::Constant *fields[2] = {
1998 llvm::ConstantInt::get(Int32Ty, values.size()),
1999 array };
2000 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
2001 NULL), fields);
David Chisnall49de5282011-10-08 08:54:36 +00002002 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00002003 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00002004}
2005
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002006void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002007 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2008 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002009 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002010 SmallVector<Selector, 16> InstanceMethodSels;
2011 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002012 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002013 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002014 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002015 InstanceMethodSels.push_back((*iter)->getSelector());
2016 std::string TypeStr;
2017 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002018 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002019 }
2020
2021 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002022 SmallVector<Selector, 16> ClassMethodSels;
2023 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002024 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002025 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002026 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002027 ClassMethodSels.push_back((*iter)->getSelector());
2028 std::string TypeStr;
2029 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002030 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002031 }
2032
2033 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002034 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00002035 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2036 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002037 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2038 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002039 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002040
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002041 std::vector<llvm::Constant*> Elements;
2042 Elements.push_back(MakeConstantString(CategoryName));
2043 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00002044 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002045 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002046 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002047 false), PtrTy));
2048 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002049 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002050 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002051 PtrTy));
2052 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002053 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002054 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00002055 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00002056 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00002057 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002058}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002059
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002060llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002061 SmallVectorImpl<Selector> &InstanceMethodSels,
2062 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002063 ASTContext &Context = CGM.getContext();
David Chisnallde38cb12013-02-28 13:59:29 +00002064 // Property metadata: name, attributes, attributes2, padding1, padding2,
2065 // setter name, setter types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00002066 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00002067 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2068 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002069 std::vector<llvm::Constant*> Properties;
2070
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002071 // Add all of the property methods need adding to the method list and to the
2072 // property metadata list.
2073 for (ObjCImplDecl::propimpl_iterator
2074 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
2075 iter != endIter ; iter++) {
2076 std::vector<llvm::Constant*> Fields;
David Blaikie262bc182012-04-30 02:36:29 +00002077 ObjCPropertyDecl *property = iter->getPropertyDecl();
David Blaikie581deb32012-06-06 20:45:41 +00002078 ObjCPropertyImplDecl *propertyImpl = *iter;
David Chisnall42ba04a2010-02-26 01:11:38 +00002079 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2080 ObjCPropertyImplDecl::Synthesize);
David Chisnallde38cb12013-02-28 13:59:29 +00002081 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2082 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002083
David Chisnall891dac72012-10-16 15:11:55 +00002084 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallde38cb12013-02-28 13:59:29 +00002085 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002086 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002087 std::string TypeStr;
2088 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2089 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002090 if (isSynthesized) {
2091 InstanceMethodTypes.push_back(TypeEncoding);
2092 InstanceMethodSels.push_back(getter->getSelector());
2093 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002094 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2095 Fields.push_back(TypeEncoding);
2096 } else {
2097 Fields.push_back(NULLPtr);
2098 Fields.push_back(NULLPtr);
2099 }
2100 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002101 std::string TypeStr;
2102 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2103 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002104 if (isSynthesized) {
2105 InstanceMethodTypes.push_back(TypeEncoding);
2106 InstanceMethodSels.push_back(setter->getSelector());
2107 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002108 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2109 Fields.push_back(TypeEncoding);
2110 } else {
2111 Fields.push_back(NULLPtr);
2112 Fields.push_back(NULLPtr);
2113 }
2114 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2115 }
2116 llvm::ArrayType *PropertyArrayTy =
2117 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2118 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2119 Properties);
2120 llvm::Constant* PropertyListInitFields[] =
2121 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2122
2123 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00002124 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002125 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2126 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2127 ".objc_property_list");
2128}
2129
David Chisnall29254f42012-01-31 18:59:20 +00002130void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2131 // Get the class declaration for which the alias is specified.
2132 ObjCInterfaceDecl *ClassDecl =
2133 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2134 std::string ClassName = ClassDecl->getNameAsString();
2135 std::string AliasName = OAD->getNameAsString();
2136 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2137}
2138
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002139void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2140 ASTContext &Context = CGM.getContext();
2141
2142 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00002143 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002144 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00002145 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002146 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002147 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002148 EmitClassRef(SuperClassName);
2149 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002150
2151 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00002152 ObjCInterfaceDecl *ClassDecl =
2153 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00002154 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002155 // Emit the symbol that is used to generate linker errors if this class is
2156 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002157 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00002158 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002159 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002160 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002161 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00002162 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002163 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00002164 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00002167 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00002168 int instanceSize =
2169 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002170
2171 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002172 SmallVector<llvm::Constant*, 16> IvarNames;
2173 SmallVector<llvm::Constant*, 16> IvarTypes;
2174 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002176 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00002177 SmallVector<bool, 16> WeakIvars;
2178 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002179
Mike Stump1eb44332009-09-09 15:08:12 +00002180 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00002181 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002182 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2183 // class}. The runtime will then set this to the correct value on load.
Richard Smith7edf9e32012-11-01 22:30:59 +00002184 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002185 instanceSize = 0 - (instanceSize - superInstanceSize);
2186 }
David Chisnall7f63cb02010-04-19 00:45:34 +00002187
Jordy Rosedb8264e2011-07-22 02:08:32 +00002188 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2189 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002190 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00002191 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002192 // Get the type encoding for this ivar
2193 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00002194 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002195 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002196 // Get the offset
Eli Friedmane5b46662012-11-06 22:15:52 +00002197 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00002198 uint64_t Offset = BaseOffset;
Richard Smith7edf9e32012-11-01 22:30:59 +00002199 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002200 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002201 }
David Chisnall63ff7032011-07-07 12:34:51 +00002202 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2203 // Create the direct offset value
2204 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2205 IVD->getNameAsString();
2206 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2207 if (OffsetVar) {
2208 OffsetVar->setInitializer(OffsetValue);
2209 // If this is the real definition, change its linkage type so that
2210 // different modules will use this one, rather than their private
2211 // copy.
2212 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2213 } else
2214 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002215 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002216 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002217 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002218 IVD->getNameAsString());
2219 IvarOffsets.push_back(OffsetValue);
2220 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002221 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2222 switch (lt) {
2223 case Qualifiers::OCL_Strong:
2224 StrongIvars.push_back(true);
2225 WeakIvars.push_back(false);
2226 break;
2227 case Qualifiers::OCL_Weak:
2228 StrongIvars.push_back(false);
2229 WeakIvars.push_back(true);
2230 break;
2231 default:
2232 StrongIvars.push_back(false);
2233 WeakIvars.push_back(false);
2234 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002235 }
David Chisnall917b28b2011-10-04 15:35:30 +00002236 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2237 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002238 llvm::GlobalVariable *IvarOffsetArray =
2239 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2240
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002241
2242 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002243 SmallVector<Selector, 16> InstanceMethodSels;
2244 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002245 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002246 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002247 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002248 InstanceMethodSels.push_back((*iter)->getSelector());
2249 std::string TypeStr;
2250 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002251 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002252 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002253
2254 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2255 InstanceMethodTypes);
2256
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002257
2258 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002259 SmallVector<Selector, 16> ClassMethodSels;
2260 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002261 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002262 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002263 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002264 ClassMethodSels.push_back((*iter)->getSelector());
2265 std::string TypeStr;
2266 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002267 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002268 }
2269 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002270 SmallVector<std::string, 16> Protocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00002271 for (ObjCInterfaceDecl::protocol_iterator
2272 I = ClassDecl->protocol_begin(),
2273 E = ClassDecl->protocol_end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002274 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002275
2276
2277
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002278 // Get the superclass pointer.
2279 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002280 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002281 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2282 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002283 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002284 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002285 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002286 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002287 // Generate the method and instance variable lists
2288 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002289 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002290 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002291 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002292 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2293 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002294 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002295 // we emit a symbol containing the offset for each ivar in the class. This
2296 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2297 // for the legacy ABI, without causing problems. The converse is also
2298 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002299
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002300 // Offset pointer for getting at the correct field in the ivar list when
2301 // setting up the alias. These are: The base address for the global, the
2302 // ivar array (second field), the ivar in this list (set for each ivar), and
2303 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002304 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002305 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002306 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002307 llvm::ConstantInt::get(IndexTy, 2) };
2308
Jordy Rosedb8264e2011-07-22 02:08:32 +00002309 unsigned ivarIndex = 0;
2310 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2311 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002312 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002313 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002314 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002315 // Get the correct ivar field
2316 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002317 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002318 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002319 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2320 if (offset) {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002321 offset->setInitializer(offsetValue);
2322 // If this is the real definition, change its linkage type so that
2323 // different modules will use this one, rather than their private
2324 // copy.
2325 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002326 } else {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002327 // Add a new alias if there isn't one already.
2328 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2329 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2330 (void) offset; // Silence dead store warning.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002331 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002332 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002333 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002334 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002335 //Generate metaclass for class methods
2336 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00002337 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002338 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002339 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002340
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002341 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002342 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002343 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00002344 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002345 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002346 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002347 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002348
2349 // Resolve the class aliases, if they exist.
2350 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002351 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002352 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002353 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002354 ClassPtrAlias = 0;
2355 }
2356 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002357 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002358 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002359 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002360 MetaClassPtrAlias = 0;
2361 }
2362
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002363 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002364 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002365 Classes.push_back(ClassStruct);
2366}
2367
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002368
Mike Stump1eb44332009-09-09 15:08:12 +00002369llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002370 // Only emit an ObjC load function if no Objective-C stuff has been called
2371 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002372 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002373 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002374
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002375 // Add all referenced protocols to a category.
2376 GenerateProtocolHolderCategory();
2377
Chris Lattner2acc6e32011-07-18 04:24:23 +00002378 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002379 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002380 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002381 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002382 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002383 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002384 }
2385
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002386 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002387 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002388 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002389 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002390 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002391 ConstantStrings.size() + 1);
2392 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002393
David Blaikie4e4d0842012-03-11 07:00:24 +00002394 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002395
Daniel Dunbar1b096952009-11-29 02:38:47 +00002396 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002397
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002398 Elements.push_back(MakeConstantString(StringClass,
2399 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002400 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002401 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002402 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002403 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002404 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002405 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002406 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002407 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002408 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002409 Elements.clear();
2410 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002411 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002412 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002413 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002414 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002415 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002416 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002417 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002418 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002419 llvm::Type::getInt16Ty(VMContext),
2420 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002421 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002422
2423 Elements.clear();
2424 // Pointer to an array of selectors used in this module.
2425 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002426 std::vector<llvm::GlobalAlias*> SelectorAliases;
2427 for (SelectorMap::iterator iter = SelectorTable.begin(),
2428 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2429
2430 std::string SelNameStr = iter->first.getAsString();
2431 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2432
Chris Lattner5f9e2722011-07-23 10:55:15 +00002433 SmallVectorImpl<TypedSelector> &Types = iter->second;
2434 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002435 e = Types.end() ; i!=e ; i++) {
2436
2437 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2438 if (!i->first.empty())
2439 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2440
2441 Elements.push_back(SelName);
2442 Elements.push_back(SelectorTypeEncoding);
2443 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2444 Elements.clear();
2445
2446 // Store the selector alias for later replacement
2447 SelectorAliases.push_back(i->second);
2448 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002449 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002450 unsigned SelectorCount = Selectors.size();
2451 // NULL-terminate the selector list. This should not actually be required,
2452 // because the selector list has a length field. Unfortunately, the GCC
2453 // runtime decides to ignore the length field and expects a NULL terminator,
2454 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002455 Elements.push_back(NULLPtr);
2456 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002457 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002458 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002459
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002460 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002461 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2462 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002463 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002464 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002465 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002466
2467 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002468 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2469
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002470 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002471 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002472 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002473 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002474 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002475 // If selectors are defined as an opaque type, cast the pointer to this
2476 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002477 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002478 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2479 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002480 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002481
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002482 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002483 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002484 Classes.size()));
2485 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002486 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002487 Categories.size()));
2488 // Create an array of classes, then categories, then static object instances
2489 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2490 // NULL-terminated list of static object instances (mainly constant strings)
2491 Classes.push_back(Statics);
2492 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002493 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002494 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002495 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002496 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2497
2498 // The symbol table is contained in a module which has some version-checking
2499 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002500 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002501 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002502 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002503 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002504 // Runtime version, used for ABI compatibility checking.
2505 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002506 // sizeof(ModuleTy)
Micah Villmow25a6a842012-10-08 16:25:52 +00002507 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002508 Elements.push_back(
2509 llvm::ConstantInt::get(LongTy,
2510 td.getTypeSizeInBits(ModuleTy) /
2511 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002512
2513 // The path to the source file where this module was declared
2514 SourceManager &SM = CGM.getContext().getSourceManager();
2515 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2516 std::string path =
2517 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2518 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002519 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002520
David Chisnallf0748852011-07-07 11:22:31 +00002521 if (RuntimeVersion >= 10)
David Blaikie4e4d0842012-03-11 07:00:24 +00002522 switch (CGM.getLangOpts().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002523 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002524 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002525 break;
David Chisnallf0748852011-07-07 11:22:31 +00002526 case LangOptions::NonGC:
David Blaikie4e4d0842012-03-11 07:00:24 +00002527 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +00002528 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2529 else
2530 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2531 break;
2532 case LangOptions::HybridGC:
2533 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2534 break;
2535 }
David Chisnalla2120032011-05-22 22:37:08 +00002536
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002537 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2538
2539 // Create the load function calling the runtime entry point with the module
2540 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002541 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002542 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002543 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2544 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002545 llvm::BasicBlock *EntryBB =
2546 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002547 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002548 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002549
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002550 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002551 llvm::FunctionType::get(Builder.getVoidTy(),
2552 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002553 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002554 Builder.CreateCall(Register, Module);
David Chisnall29254f42012-01-31 18:59:20 +00002555
David Chisnalldccaa232012-02-01 19:16:56 +00002556 if (!ClassAliases.empty()) {
David Chisnall29254f42012-01-31 18:59:20 +00002557 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2558 llvm::FunctionType *RegisterAliasTy =
2559 llvm::FunctionType::get(Builder.getVoidTy(),
2560 ArgTypes, false);
2561 llvm::Function *RegisterAlias = llvm::Function::Create(
2562 RegisterAliasTy,
2563 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2564 &TheModule);
2565 llvm::BasicBlock *AliasBB =
2566 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2567 llvm::BasicBlock *NoAliasBB =
2568 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2569
2570 // Branch based on whether the runtime provided class_registerAlias_np()
2571 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2572 llvm::Constant::getNullValue(RegisterAlias->getType()));
2573 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2574
2575 // The true branch (has alias registration fucntion):
2576 Builder.SetInsertPoint(AliasBB);
2577 // Emit alias registration calls:
2578 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2579 iter != ClassAliases.end(); ++iter) {
2580 llvm::Constant *TheClass =
2581 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2582 true);
2583 if (0 != TheClass) {
2584 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2585 Builder.CreateCall2(RegisterAlias, TheClass,
2586 MakeConstantString(iter->second));
2587 }
2588 }
2589 // Jump to end:
2590 Builder.CreateBr(NoAliasBB);
2591
2592 // Missing alias registration function, just return from the function:
2593 Builder.SetInsertPoint(NoAliasBB);
2594 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002595 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002596
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002597 return LoadFunction;
2598}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002599
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002600llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002601 const ObjCContainerDecl *CD) {
2602 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002603 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002604 StringRef CategoryName = OCD ? OCD->getName() : "";
2605 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002606 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002607 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002608
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002609 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002610 llvm::FunctionType *MethodTy =
John McCallde5d3c72012-02-17 03:33:10 +00002611 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002612 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2613 MethodName, isClassMethod);
2614
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002615 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002616 = llvm::Function::Create(MethodTy,
2617 llvm::GlobalValue::InternalLinkage,
2618 FunctionName,
2619 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002620 return Method;
2621}
2622
David Chisnall789ecde2011-05-23 22:33:28 +00002623llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002624 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002625}
2626
David Chisnall789ecde2011-05-23 22:33:28 +00002627llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002628 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002629}
2630
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002631llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2632 bool copy) {
2633 return 0;
2634}
2635
David Chisnall789ecde2011-05-23 22:33:28 +00002636llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002637 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002638}
David Chisnall789ecde2011-05-23 22:33:28 +00002639llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002640 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002641}
David Chisnalld397cfe2012-12-17 18:54:24 +00002642llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2643 return 0;
2644}
2645llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Fariborz Jahaniane3173022012-01-06 18:07:23 +00002646 return 0;
2647}
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002648
Daniel Dunbar309a4362009-07-24 07:40:24 +00002649llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002650 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002651}
2652
David Chisnall9f6614e2011-03-23 16:36:54 +00002653void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002654 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002655 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002656}
Chris Lattner5dc08672009-05-08 00:11:50 +00002657
David Chisnall0faa5162009-12-24 02:26:34 +00002658
David Chisnall9f6614e2011-03-23 16:36:54 +00002659void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002660 const ObjCAtTryStmt &S) {
2661 // Unlike the Apple non-fragile runtimes, which also uses
2662 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2663 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnallc6860042012-11-07 16:50:40 +00002664 // objects are created by objc_exception_throw and destroyed by
John McCallf1549f62010-07-06 01:34:17 +00002665 // the personality function; this avoids the need for bracketing
2666 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2667 // (or even _Unwind_DeleteException), but probably doesn't
2668 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002669 //
David Chisnall80558d22011-03-20 21:35:39 +00002670 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002671 // exception handler.
2672 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2673 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002674}
2675
David Chisnall9f6614e2011-03-23 16:36:54 +00002676void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002677 const ObjCAtThrowStmt &S,
2678 bool ClearInsertionPoint) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002679 llvm::Value *ExceptionAsObject;
2680
Chris Lattner5dc08672009-05-08 00:11:50 +00002681 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002682 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002683 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002684 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002685 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002686 "Unexpected rethrow outside @catch block.");
2687 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2688 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002689 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnallc6860042012-11-07 16:50:40 +00002690 llvm::CallSite Throw =
John McCallbd7370a2013-02-28 19:01:20 +00002691 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnallc6860042012-11-07 16:50:40 +00002692 Throw.setDoesNotReturn();
Eli Friedmanc972c922012-08-10 21:26:17 +00002693 CGF.Builder.CreateUnreachable();
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002694 if (ClearInsertionPoint)
2695 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002696}
2697
David Chisnall9f6614e2011-03-23 16:36:54 +00002698llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002699 llvm::Value *AddrWeakObj) {
John McCallbd7370a2013-02-28 19:01:20 +00002700 CGBuilderTy &B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002701 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002702 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002703}
2704
David Chisnall9f6614e2011-03-23 16:36:54 +00002705void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002706 llvm::Value *src, llvm::Value *dst) {
John McCallbd7370a2013-02-28 19:01:20 +00002707 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002708 src = EnforceType(B, src, IdTy);
2709 dst = EnforceType(B, dst, PtrToIdTy);
2710 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002711}
2712
David Chisnall9f6614e2011-03-23 16:36:54 +00002713void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002714 llvm::Value *src, llvm::Value *dst,
2715 bool threadlocal) {
John McCallbd7370a2013-02-28 19:01:20 +00002716 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002717 src = EnforceType(B, src, IdTy);
2718 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002719 if (!threadlocal)
2720 B.CreateCall2(GlobalAssignFn, src, dst);
2721 else
2722 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002723 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002724}
2725
David Chisnall9f6614e2011-03-23 16:36:54 +00002726void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002727 llvm::Value *src, llvm::Value *dst,
2728 llvm::Value *ivarOffset) {
John McCallbd7370a2013-02-28 19:01:20 +00002729 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002730 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002731 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002732 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002733}
2734
David Chisnall9f6614e2011-03-23 16:36:54 +00002735void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002736 llvm::Value *src, llvm::Value *dst) {
John McCallbd7370a2013-02-28 19:01:20 +00002737 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002738 src = EnforceType(B, src, IdTy);
2739 dst = EnforceType(B, dst, PtrToIdTy);
2740 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002741}
2742
David Chisnall9f6614e2011-03-23 16:36:54 +00002743void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002744 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002745 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002746 llvm::Value *Size) {
John McCallbd7370a2013-02-28 19:01:20 +00002747 CGBuilderTy &B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002748 DestPtr = EnforceType(B, DestPtr, PtrTy);
2749 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002750
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002751 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002752}
2753
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002754llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2755 const ObjCInterfaceDecl *ID,
2756 const ObjCIvarDecl *Ivar) {
2757 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2758 + '.' + Ivar->getNameAsString();
2759 // Emit the variable and initialize it with what we think the correct value
2760 // is. This allows code compiled with non-fragile ivars to work correctly
2761 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002762 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2763 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002764 // This will cause a run-time crash if we accidentally use it. A value of
2765 // 0 would seem more sensible, but will silently overwrite the isa pointer
2766 // causing a great deal of confusion.
2767 uint64_t Offset = -1;
2768 // We can't call ComputeIvarBaseOffset() here if we have the
2769 // implementation, because it will create an invalid ASTRecordLayout object
2770 // that we are then stuck with forever, so we only initialize the ivar
2771 // offset variable with a guess if we only have the interface. The
2772 // initializer will be reset later anyway, when we are generating the class
2773 // description.
2774 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002775 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedmane5b46662012-11-06 22:15:52 +00002776 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnalld901da52010-04-19 01:37:25 +00002777
David Chisnall49de5282011-10-08 08:54:36 +00002778 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002779 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002780 // Don't emit the guess in non-PIC code because the linker will not be able
2781 // to replace it with the real version for a library. In non-PIC code you
2782 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002783 // GCC-compiled class.
Chandler Carruth5e219cf2012-04-08 16:40:35 +00002784 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002785 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002786 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002787 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2788 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2789 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2790 IvarOffsetGV, Name);
2791 } else {
2792 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002793 llvm::Type::getInt32PtrTy(VMContext), false,
2794 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002795 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002796 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002797 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002798}
2799
David Chisnall9f6614e2011-03-23 16:36:54 +00002800LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002801 QualType ObjectTy,
2802 llvm::Value *BaseValue,
2803 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002804 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002805 const ObjCInterfaceDecl *ID =
2806 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002807 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2808 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002809}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002810
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002811static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2812 const ObjCInterfaceDecl *OID,
2813 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002814 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2815 next = next->getNextIvar()) {
2816 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002817 return OID;
2818 }
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002820 // Otherwise check in the super class.
2821 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2822 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002824 return 0;
2825}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002826
David Chisnall9f6614e2011-03-23 16:36:54 +00002827llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002828 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002829 const ObjCIvarDecl *Ivar) {
John McCall260611a2012-06-20 06:18:46 +00002830 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002831 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002832 if (RuntimeVersion < 10)
2833 return CGF.Builder.CreateZExtOrBitCast(
2834 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2835 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2836 PtrDiffTy);
2837 std::string name = "__objc_ivar_offset_value_" +
2838 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2839 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2840 if (!Offset)
2841 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002842 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2843 llvm::Constant::getNullValue(IntTy), name);
David Chisnall66148452012-04-06 15:39:12 +00002844 Offset = CGF.Builder.CreateLoad(Offset);
2845 if (Offset->getType() != PtrDiffTy)
2846 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2847 return Offset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002848 }
Eli Friedmane5b46662012-11-06 22:15:52 +00002849 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2850 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002851}
2852
David Chisnall9f6614e2011-03-23 16:36:54 +00002853CGObjCRuntime *
2854clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall260611a2012-06-20 06:18:46 +00002855 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +00002856 case ObjCRuntime::GNUstep:
David Chisnall9f6614e2011-03-23 16:36:54 +00002857 return new CGObjCGNUstep(CGM);
John McCall260611a2012-06-20 06:18:46 +00002858
David Chisnall11d3f4c2012-07-03 20:49:52 +00002859 case ObjCRuntime::GCC:
John McCall260611a2012-06-20 06:18:46 +00002860 return new CGObjCGCC(CGM);
2861
John McCallf7226fb2012-07-12 02:07:58 +00002862 case ObjCRuntime::ObjFW:
2863 return new CGObjCObjFW(CGM);
2864
John McCall260611a2012-06-20 06:18:46 +00002865 case ObjCRuntime::FragileMacOSX:
2866 case ObjCRuntime::MacOSX:
2867 case ObjCRuntime::iOS:
2868 llvm_unreachable("these runtimes are not GNU runtimes");
2869 }
2870 llvm_unreachable("bad runtime");
Chris Lattner0f984262008-03-01 08:50:34 +00002871}